HTML/PHP - default input value

前端 未结 10 1312
梦如初夏
梦如初夏 2020-12-11 16:48

I have a post php form and a set of inputs:

  1. Your Name
  2. Your Last Name
  3. My Name

Every input looks the same, only the names change

相关标签:
10条回答
  • 2020-12-11 17:33

    You could use my tiny library ValueResolver in this case, for example:

    $default = ValueResolver::resolve(get_option('your_name'), '<whatever your default value is>');
    

    and don't forget to use namespace use LapaLabs\ValueResolver\Resolver\ValueResolver;

    There are also ability to typecasting, for example if your variable's value should be integer, so use this:

    $id = ValueResolver::toInteger('6 apples', 1); // returns 6
    $id = ValueResolver::toInteger('There are no apples', 1); // returns 1 (used default value)
    

    Check the docs for more examples

    0 讨论(0)
  • 2020-12-11 17:36

    you can change the get_option() function to be something like

    function get_option($name) {
       $defaults = array(
          'fist_name' => 'Mike',
          'fist_name' => 'Wordpressor',
          'my_name' => 'Dunno'
       );
       // get the value from the $defaults array
       $val = $defaults[$name];
    
       // but if the same value has already been posted - replace the default one
       if (isset($_POST[$name])) {
          $val = $_POST[$name];
       }
       return $val;
    }
    
    0 讨论(0)
  • 2020-12-11 17:38

    Set some variable at start with the post variables.

    like

    $name_val = "";
    if(isset($_POST["your_name"])
    {
        $name_val = $_POST["your_name"];
    }
    
    <input type="text" name="your_name" value="<?= $name_val?>">
    
    0 讨论(0)
  • 2020-12-11 17:39

    Since value is the default, just add a condition around your get_option-function, maybe something like this:

    <input type="text" name="your_name" value="<?php $var = get_option('your_name'); if ($var == '') $var = 'your_default'; echo $var; ?>" />
    
    0 讨论(0)
提交回复
热议问题