如何将参数传递给自定义 Zend 验证器?
我正在尝试在 Zend 框架中编写一个验证器。
验证器查询数据库以检查特定记录是否存在,此查询使用 where 子句。 where 子句的值由表单上的另一个字段指定,那么如何将该值传递到验证器中呢?
这就是我添加验证器的方式:
$adgroup_name->addValidator(new Generic_ValidateUniqueAdGroupName() ); break;
在我的验证器中,我有:
// Query which gets an array of existing ad group names in db
$q = Doctrine_Query::create()
->select('a.name')
->from('AdGroup a')
->where('a.name = ?', $value)
->andWhere('a.campaign_id = ?', $campaign_id);
$adgroup_names_result = $q->fetchOne(array(), Doctrine::HYDRATE_ARRAY);
如何传入 $campaign_id?我已尝试以下方法但不起作用:
$adgroup_name->addValidator(new Generic_ValidateUniqueAdGroupName($campaign_id) ); break;
I am trying to write a validator in Zend framework.
The validator queries the database to check if a particular record exists, this query uses a where clause. The value for the where clause is specified by another field on the form, so how do I pass this value into the validator?
This is how I add my validator:
$adgroup_name->addValidator(new Generic_ValidateUniqueAdGroupName() ); break;
Within my validator I have:
// Query which gets an array of existing ad group names in db
$q = Doctrine_Query::create()
->select('a.name')
->from('AdGroup a')
->where('a.name = ?', $value)
->andWhere('a.campaign_id = ?', $campaign_id);
$adgroup_names_result = $q->fetchOne(array(), Doctrine::HYDRATE_ARRAY);
How do I pass in $campaign_id? I've tried the following and it doesn't work:
$adgroup_name->addValidator(new Generic_ValidateUniqueAdGroupName($campaign_id) ); break;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
原理与“确认密码”验证器中使用的原理相同。提交表单时,您需要在字段中获取表单中另一个元素的值。。这就是尝试使用 Campaign_id 实例化验证器不起作用的原因:
$campaign_id
的值尚未设置。当元素在其验证器上调用
isValid()
时,它会传递名为$context
的第二个参数,该参数填充了提交的表单值的数组。因此,验证器中的isValid()
方法应如下所示:The principle is the same as used in "confirm password" validators. You need the value of another element in the form in the field when the form is submitted. That's why attempting to instantiate the validator with the campaign_id is not working: the value of
$campaign_id
is not yet set.When an element calls
isValid()
on its validators, it passes a second parameter called$context
that is filled with an array of submitted form values. So yourisValid()
method in your validator should look something like this:我认为要使
new Generic_ValidateUniqueAdGroupName($campaign_id)
工作,您需要为 Generic_ValidateUniqueAdGroupName 类定义一个构造函数和一个名为 $_campaign_id 的变量。草稿如下:通过此,您可以在查询中以
$this->_campaign_id
的形式访问 id。I think to make
new Generic_ValidateUniqueAdGroupName($campaign_id)
work you need to define a constructor for Generic_ValidateUniqueAdGroupName class and a variable called e.g. $_campaign_id. A draft is below:With this, you would access the id in your query as
$this->_campaign_id
.您需要提供
$options
参数:在 Zend_Form_Element:
所以,你会这样做:
You need to supply the
$options
argument:Implementation in Zend_Form_Element:
So, you'd do something like this: