如何使字段验证依赖于另一个字段使用ZF2中的数组表单设置?

时间:2016-06-03 16:30:44

标签: forms validation zend-framework2 zend-form zend-form-element

在我的表单中,我有一个字段foo,它在数据库表中应该是唯一的。所以我在其验证器列表中添加了Zend\Validator\Db\NoRecordExists

namespace Bar\Form\Fieldset;

use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\Db\Adapter\AdapterInterface;

class BuzFieldset extends Fieldset implements InputFilterProviderInterface
{
    protected $dbAdapter;

    public function __construct($name = null, $options = []) {...}

    public function setDbAdapter(AdapterInterface $dbAdapter) {...}

    public function init()
    {
        $this->add([
            'name' => 'id',
            'type' => 'hidden'
        ]);
        $this->add(
            [
                'name' => 'foo',
                'type' => 'text',
                'options' => [...],
                'attributes' => [
                    'required' => 'required',
                    'class' => 'form-control'
                ]
            ]);
        ...
    }

    public function getInputFilterSpecification()
    {
        return [
            'foo' => [
                'required' => true,
                'validators' => [
                    [
                        'name' => 'Regex',
                        'options' => [
                            'pattern' => '/.../',
                            'message' => _(...)
                        ]
                    ],
                    [
                        'name' => 'Zend\Validator\Db\NoRecordExists',
                        'options' => [
                            'table' => 'buz',
                            'field' => 'foo',
                            'adapter' => $this->dbAdapter
                        ]
                    ]
                ]
            ],
            ...
        ];
    }
}

现在我想使用相同的表单来更新条目,当然也无法验证表单。因此,我需要根据字段NoRecordExists对此字段进行id验证。如果设置id(也就是说,它更新,而不是创建),则应该应用所有验证器(例如此处Regex),但不应该应用此验证器。怎么做?

1 个答案:

答案 0 :(得分:3)

您可以查看Callback验证程序。此验证器将允许您访问表单上下文,以便您获取其他字段的值。使用NoRecordExists验证程序中的Callback验证程序使其依赖。像这样的东西。我没有对此进行测试,但你会明白这一点。

'foo' => [
    'required' => true,
    'validators' => [
        [
            'name' => 'Callback',
            'options' => [
                'callback' => function($value, $context = []) {
                    if (empty($context['id'])) {
                        return $this->noRecordExistsValidator->isValid($value);
                    }

                    return true;
                },
            ],
        ]
    ]
]

您需要将NoRecordExistsValidator作为依赖项注入此表单类,或者更好地创建一个单独的InputFilter和相应的工厂,它们完全设置InputFilter并注入该实例进入Fieldset对象。

相关问题