本文介绍了Silverstripe条件验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含多项操作的表单,例如创建订单和创建报价。
I have a form which has multiple actions e.g. Create Order & Create Quote.
根据所单击的操作,我需要应用其他验证。例如
Depending on what action is clicked I need to apply different validation. e.g. Order Ref is not required for a quote.
在Silverstripe中有可能吗?如果不是,我该怎么办?
Is this possible within Silverstripe? If not how would I got about it?
public function Order($request=null) {
$form = Form::create(
$this,
__FUNCTION__,
FieldList::create(
TextField::create('Name', 'Your Full Name'),
TextField::create('OrderRef', 'Purchase Order #')
),
FieldList::create(
LiteralField::create('Cancel', '<a class="cancel button alert">Don\'t save</a>'),
FormAction::create('saveQuote', 'Save Quote'),
FormAction::create('saveOrder', 'Save Order')->addExtraClass('success')
),
RequiredFields::create('Name', 'OrderRef')
);
return $form;
}
推荐答案
为此,您将可能需要创建一个自定义的 RequiredFields
子类,以有条件地设置所需的字段:
To do this, you will probably need to create a custom RequiredFields
subclass to conditionally set which fields are required:
class CustomValidator extends RequiredFields {
public function php($data) {
if($this->form->buttonClicked()->actionName() == 'saveQuote') {
$this->addRequiredField('FieldName'); // ...
} else {
$this->addRequiredField('OtherFieldName'); // ...
}
return parent::php($data);
}
}
然后,您可以使用以下形式:
You then use this in your form like:
$form = new Form(
$this, 'FormName', $fields, $actions, new CustomValidator()
);
这篇关于Silverstripe条件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!