nilesh suryavanshi
nilesh suryavanshi

Reputation: 408

Form element validation in Phalcon framework (check if element exists)

I am beginner in Phalcon framework, I have to validate form elements in .volt page

I have one form class file where I write hidden filed for record edit purpose, I'm storing record's id in hidden filed when its in edit mode

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

The problem is when I rendering this hidden filed in add.volt

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

Its working fine in time of edit mode, but in new record time its give error

Phalcon\Forms\Exception: Element with ID=tax_categories_id is not a part of the form

I know the why error is coming but i am not able to validate this field in .volt file

Upvotes: 3

Views: 2253

Answers (3)

Jim
Jim

Reputation: 36

Just check if the element is exist

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

Upvotes: 1

yergo
yergo

Reputation: 4960

Assuming you have crated something close to:

<?php

use Phalcon\Forms\Form,
    Phalcon\Forms\Element\Text,
    Phalcon\Forms\Element\Hidden;

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 options, you may have one field declared, or two instead. Now when someone sends you this form back, for validation you have to set it up again with proper $options['edit'], depending on if you have $_REQUEST['id'] declared or not:

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

$form->bind($_REQUEST);
if($form->isValid()) {
    //...
}

Quite an advanced (but with some gaps anyway) manual is here. Bet you were there already, but just in case.

Btw, form are iterators & traversables, so you can loop over them to render only elements, that are declared. Writing this because you have put {{ form.render('tax_categories_id')}} as an example and that makes me feel like you are generating fields by hand.

Upvotes: 0

David Duncan
David Duncan

Reputation: 1858

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

//controller.php
$this->view->setVar('options', $options);


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

Upvotes: 1

Related Questions