How to determine form field type in php

<form name="form" action="" method="get">
  <input type="text" name="name" id="name" value="My name">
    <textarea name="about_me" id="about_me"></textarea>
    <input type="radio" name="gender" value="male" />
    <input type="radio" name="gender" value="female" />

    <select name="level">
        <option value="Beginner">Beginner</option>
        <option value="Intermediate">Intermediate</option>
        <option value="Expert">Expert </option>
    </select>
</form>

I have a form

My form fields are dynamically added. After submitting the form, I need to determine the type of field, I need to know, since the name is the value of the text field, about_me is the input to textarea, gender is the radio option, the level of the drop-down menu, etc.
is that any way to find out the type of a form field in php.

+4
source share
1 answer

First: use the MyWay approach. It is straightforward and dead simple. However, if you want to create a more complex structure, you can use the following code. It sets hidden fields as an array and contains the name and type, separated by a symbol ::

HTML page:

<form name="form" action="" method="get">

    <input type="hidden" name="fields[]" value="name:text">
    <input type="hidden" name="fields[]" value="about_me:textarea">
    <input type="hidden" name="fields[]" value="gender:radio">
    <input type="hidden" name="fields[]" value="level:select">

    <input type="text" name="name" id="name" value="My name">
    <textarea name="about_me" id="about_me"></textarea>
    <input type="radio" name="gender" value="male" />
    <input type="radio" name="gender" value="female" />

    <select name="level">
        <option value="Beginner">Beginner</option>
        <option value="Intermediate">Intermediate</option>
        <option value="Expert">Expert </option>
    </select>
</form>

Then in your PHP file:

$fields = $_POST["fields"];
foreach ($fields as $field) {
    list($name, $type) = explode(':', $field);
    $val = (!empty($_POST[$name]))?$_POST[$name]:"";
    if ($type == "textarea") {
        // do sth. useful with it
        // the value is in $val (if there one)
    }
}
+1
source

Source: https://habr.com/ru/post/1617400/


All Articles