A simple way to working with forms in php.
composer require simettric/simple-form
$config = new Config();
$config->addFieldDefinition("customField", "\\Namespace\\CustomField");
$builder = new FormBuilder($config);
$builder->create("message")
->add("firstName")
->add("lastName")
->add("email", "email")
->add("subject", "choice", array("choices"=>array())) //InArray is implicit unless we configure our own ChoiceValidator in the "validators" key
->add("message", "textarea", array(
"validators" => array(
new NotEmpty(),
new StringLength(array("min"=>4))
));
$data_array = array("firstName"=>"John");
$form = $builder->getForm($data_array);
class MessageForm extends AbstractForm{
function configure(FormBuilder $builder){
$this->name = "message";
$builder->add("firstName")
->add("lastName")
->add("email", "email")
->add("subject", "choice", array("choices"=>array())) //ChoiceValidator is implicit unless we configure our own ChoiceValidator in the "validators" key
->add("message", "textarea", array(
"validators" => array(
new NotEmpty(),
new StringLength(array("min"=>4))
));
}
}
$data_array = array("firstName"=>"John");
$form = new MessageForm($data_array, $config);
SimpleForm uses Zend Validator to manage the fields validation in its forms.
$builder->add("message", "textarea", array(
"label" => "Write your message",
"validators" => array(
new NotEmpty(),
new StringLength(array("min"=>4)
)
));
In your controller, you can bind the request data and check if the form is valid
$form->bind( $_POST["contact"] );
if($form->isValid()){
echo $form->getValue("firstName");
}
<?php echo $form["firstName"] ?>
Outputs:
<div>
<label for="contact_firstName">firstName</label>
<input type="text" name="contact[firstName]" required="required">
<span class="error">Error message</span>
</div>
You can render each HTML tag individually:
<?php echo $form["firstName"]->getLabelTag() ?>
<?php echo $form["firstName"]->getInputTag(array("class"=>"the attribute value")) ?>
<?php echo $form["firstName"]->getErrorTag() ?>
Also, you can get an array of error values
<?php foreach( $form["firstName"]->getErrorArray() as $error ){} ?>