Bug in documentation – form custom validation

4 years ago

horakmar
Member | 16
+
0
-

Example in documentation (Forms) doesn't work for me:

function divisibilityValidator($item, $arg){
    return $item->value % $arg === 0;
}

$form->addText('number', 'Number:')
    ->addRule('divisibilityValidator', 'Number must be divisible by %d.', 8);

Issues an error “Validator divisibilityValidator not found”.

Anonymous function works OK:

$divisibilityValidator = function($item, $arg){
    return $item->value % $arg === 0;
}

$form->addText('number', 'Number:')
    ->addRule($divisibilityValidator, 'Number must be divisible by %d.', 8);

4 years ago

Machy8
Member | 59
+
0
-

Try this:

public function divisibilityValidator($item, $arg)
{
    return $item->value % $arg === 0;
}

public function createComponentMyForm ()
{
        $form = new Nette\Application\UI\Form;
        $form->addText('number', 'number:')
            ->addRule($this->divisibilityValidator, 'Number must be divisible by %d.', 8);
        return $form;
}

4 years ago

Aurielle
Member | 1283
+
+3
-

The example from docs doesn't work for you because the code implies a function defined in the global namespace, not a method in the current class, even if the syntax is the same.

A bit of explanation of @Machy8's solution, the $this->divisibilityValidator syntax in ->addRule($this->divisibilityValidator, 'Number must be divisible by %d.', 8); is a bit of a magic, the standard PHP way of specifying a callback would be passing an array, like this:

$form->addText(...)
    ->addRule([$this, 'divisibilityValidator'], 'Number must be ...', ...);

4 years ago

horakmar
Member | 16
+
0
-

OK, thanks for explanation.

Martin