Era*_*ray 5 php zend-form zend-framework2
我有一个moneyFieldset有2个字段,金额和货币.
class MoneyFieldset ...
{
public function __construct($name = null, $options = array())
{
parent::__construct($name, $options);
$this->setHydrator(...);
$this->add(array(
'name' => 'currency',
'type' => 'select',
'options' => array(
'value_options' => \Core\Service\Money::getAvailableCurrencies(true),
),
'attributes' => array(
'value' => \Core\Service\Money::DEFAULT_CURRENCY,
),
));
$this->add(array(
'name' => 'amount',
'type' => 'text',
));
}
}
public function getInputFilterSpecification()
{
$default = [
'amount' => [
'required' => false,
'allow_empty' => true,
'filters' => [
['name' => AmountFilter::class]
],
'validators' => [
]
],
'currency' => [
'required' => false,
'allow_empty' => true,
'filters' => [
['name' => StringToUpper::class]
],
'validators' => [
]
]
];
return \Zend\Stdlib\ArrayUtils::merge($default, $this->filterSpec, true);
}
Run Code Online (Sandbox Code Playgroud)
我在我的其他字段集中使用moneyFieldset:
// Price Field
$this->add(array(
'name' => 'price',
'type' => 'form.fieldset.moneyFieldset',
'attributes' => array(
'required' => true,
'invalidText' => 'Please type an amount'
),
'options' => array(
...
),
));
Run Code Online (Sandbox Code Playgroud)
当我像这样设置过滤器时:
function getInputFilterSpecification()
{
'price' => [
'required' => true,
'allow_empty' => false,
],
}
Run Code Online (Sandbox Code Playgroud)
它不起作用,因为价格有2个字段,那么我怎么能说价格[金额]和价格[curreny]是必需的?
您可以使用以下数组结构提供嵌套字段集(在表单上下文中)的输入规范。
public function getInputFilterSpecification()
{
return [
// ...
'price' => [
'type' => 'Zend\InputFilter\InputFilter',
'amount' => [
'required' => true,
],
'currency' => [
'required' => true,
]
],
//...
];
}
Run Code Online (Sandbox Code Playgroud)
如果您要动态修改输入过滤器的值,则可能值得考虑使用服务工厂类创建验证器,然后使用对象 API 而不是数组将其附加到表单。