Evaluating dynamic field value with name from array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
opera13
Forum Newbie
Posts: 1
Joined: Thu Sep 18, 2008 5:09 pm

Evaluating dynamic field value with name from array

Post by opera13 »

I'm having an awful time trying to get a form field defined by a variable (which is stored in an array) to evaluate out to its value.

In my code, I create a class that defines a way of constructing a form. Later I define a multidimensional array that is sent to the class to create the form. Up to that point, everything works and displays nicely. Once I enter data into my fields and submit them, however, I reach a problem. The values are definately being sent, because I can call them outright, as I do in the first two lines of the function DisplayForm(). But I cannot get them to evaluate out to their values if I try to pull the field names from the array. Additionally, straightforwardly declaring the variables as $name or $description, without the scope of $_POST, is ineffective within the function, which surprises me. (This may be simple ignorance, as this is my first function.). Please help! The code follows.

Code: Select all

<?php
 
class Form {
 
   function DisplayForm( ) {
        echo "Name:". $_POST['name']. "<br>";
        echo "Description:".$_POST['description']. "<br>";
        
        foreach($this->Fields as $value){
            $fieldName="$"."_POST"."['".$value[2]."']";         
            echo $value[2].":".${fieldName}."<br />";
        } 
    
echo "<form action=\"class_testb.php\" method=\"post\">\n";
foreach($this->Fields as $value){
switch($value[0]){
case "textbox":
echo $value[1]. " <input type=\"text\" name=\"".$value[2]."\" value=\"\" /><br/>\n";
break;
case "textarea":
echo $value[1]. "<textarea name=\"".$value[2]. "\" rows=\"5\" cols=\"50\"/></textarea><br/>\n";
break;
        }
    }
echo "<input type=\"submit\" name=\"submit\" value=\"submit\"/>\n";
echo "</form>\n";
   }
 
   function SetFields( $FormFields ) {
     $this->Fields = $FormFields;   
  }
}
$Sample = new Form;
 // array(type of field, label for field,   name of field, validation required)
$Fields = array(    array("textbox","Name","name" , "required"),
        array("textarea",   "Description","description" , "required"),
                    );
$Sample->SetFields( $Fields );
$Sample->DisplayForm(); 
?>p
Post Reply