Forms

Sense uses Simettric Simple Form and Zend Validator in order to manage and validate your forms.

The form class

The first step is defining your Form class. In this class you can create and configure all the fields for your form.

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))
                                            ));

    }


}

Using your form in the controller


function yourAction()
{
    //optionally, your can pass the default values for your form in this array
    $data_array = array(
        "firstName" => "default value"
    );

    $form = $this->createForm("MessageForm", $data_array);

    //if you are using >=php5.5
    $form = $this->createForm(MessageForm::class, $data_array);

    if(isset($_POST["contact"]))
    {
        $form->bind( $_POST["contact"] );

        if($form->isValid()){

           echo $form->getValue("firstName");

        }
    }

    return $this->templateResult('your_template.php', array(
        "form" => $form
    ));

}

The form view

<?php $form = senseView()->get("form") ?>


<?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 ){} ?>