gpt4 book ai didi

zend-framework2 - ZF2 动态表单过滤器/验证器

转载 作者:行者123 更新时间:2023-12-02 00:15:08 24 4
gpt4 key购买 nike

我正在设置一个 Controller 来创建一个表单。我不能使用扩展到 Form 类,所以我需要在我的 Controller 上构建我的表单。

$form = new Form('example');
$fieldset = new Fieldset('default');
$fieldset->add(array('name' => 'example_field', 'attributes' => array('type' => 'text', 'id' => 'example_field'), 'options' => array('label' => 'Example Field',),));
$form->add($fieldset);

这里的主要问题是,如何在不需要创建实现 InputFilterAwareInterface 的类的情况下为每个元素/字段集定义过滤器和验证器,这样我就可以在我的 Controller 中执行所有操作?

提前致谢!

最佳答案

您可以通过处理表单的 InputFilter 添加/删除表单验证器,这是我的示例:

$form = new \Zend\Form\Form();
$name = array(
'name' => 'username',
'options' => array(
'label' => 'Your name',
),
'attributes' => array(
'type' => 'text'
),
);
$form->add($name);


$filter = $form->getInputFilter();
$filter->remove('username');
$filter->add(array(
'name' => 'username',
'required' => true,
'validators' => array (
'stringLength' => array (
'name' => 'StringLength',
'options' => array (
'max' => '3',
),
),
),
));
$form->setInputFilter($filter);


$form->setData(array(
'username' => 'longtext',
));
$form->prepare();
echo $form->isValid(); //false
print_r($form->getMessages()); //stringLengthTooLong error will show

关于zend-framework2 - ZF2 动态表单过滤器/验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13587093/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com