Search code examples
phpformsnette

Set conditional Validation on Chained Methods in Nette Forms


I am trying to render a form using Nette\Forms where the field types are stored in the database. So depending upon whether the field is an email or a simple text input; the validation type will differ as follows:

// For textbox       
$form->addText($field['name'], $field['label'])
     ->setRequired('Enter your ' . $field['label']);

// For Email
$form->addText($field['name'], $field['label'])
      ->setRequired('Enter your email')
      ->addRule(FORM::EMAIL, 'Enter a valid email');

If it was just one field I could do it with a a if condition but there will be a lot more fields and it just seems impractical to do this. And since it's a chained method I can't break the methods by putting intermediate if statement like following:

$form->addText($field['name'], $field['label'])
      ->setRequired('Enter your email');
    if ($field['type'] == ['email']) {
        $form->addRule(FORM::EMAIL, 'Enter a valid email');
    }   

Is there a better way to achieve this than using conditional statements for each set of rules?


Solution

  • You are calling addRule() on the $form object itself, and not the returned value of the $form->addText() call.

    $name = $form->addText($field['name'], $field['label'])
    if ($field['type'] == ['email']) {
        $name->setRequired('Enter your email')
        ->addRule(FORM::EMAIL, 'Enter a valid email');
    }