Validating form element in Phalcon structure (check if element exists)

I am new to Phalcon framework, I have to validate form elements on the page .volt

I have one form class file where I write a hidden file dedicated to edit a post, I store the post id in a hidden file when it is in edit mode

if ($options["edit"] == 1) {
       // $tax_categories_id = new Hidden("tax_categories_id");
        $this->add(new Hidden('tax_categories_id'));


The problem is that I am creating this hidden content in add.volt

 {{ form.render('tax_categories_id')}} 


It works fine during edit mode, but at new recording time it gets error

Phalcon \ Forms \ Exception: Item with id = tax_categories_id is not part of the form

I know why the error is occurring, but I cannot validate this field in the file .volt


source to share

3 answers

In the controller, can you set the $ options variable and then check it inside the view?

$this->view->setVar('options', $options);

{% if options['edit'] %}
    {{ form.render('tax_categories_id')}} 
{% endif %]




Just check if the element exists

// add.volt
{% if form.has('tax_categories_id') %}
    {{ form.render('tax_categories_id') }}
{% endif %}




Assuming you have something close to:


use Phalcon\Forms\Form,

class UsersForm extends Form
    public function initialize($options = [])
        if ( isset($options['edit']) && $options['edit'] ) {
            $this->add(new Hidden('id'));

        $this->add(new Text('name'));


So! Depending on the parameters, you can have one or two fields declared. Now when someone submits this form back to you, in order to validate, you need to set it again with the correct one $options['edit']

, depending on whether you are declared $_REQUEST['id']

or not:

$form = null;
if( isset($_REQUEST['id']) ) {
    $form = new UsersForm();
} else {
    $form = new UsersForm(['edit' => true]);

if($form->isValid()) {


Pretty advanced (but with some whitespace) here anyway . A bet that you've already been there, but just in case.

Btw, form are iterators and traversals, so you can iterate over them to display only the declared elements. By writing this because you put {{ form.render('tax_categories_id')}}

as an example and make me feel like you are creating fields manually.



All Articles