[英]Passing invididual field's “required” information to a compound Symfony2 form
I need to enter a pair of date and time in multiple places of my Symfony2 application. 我需要在Symfony2应用程序的多个位置输入一对日期和时间。 To accomplish this, I've created a custom_datetime
form type. 为此,我创建了一个custom_datetime
表单类型。 I'd like to decide whether time
is required by occassion, while keeping date
required if the whole custom_datetime has a required
flag. 我想确定是否偶尔需要time
,同时如果整个custom_datetime具有required
标志,则使date
保持required
。
class DateTime extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('date', 'text', [
'attr' => ['required' => true] // Here I maybe should inherit what is passed by the parent form
])
->add('time', 'text', [
'attr' => ['required' => $options['time_required']]
])
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'time_required' => false
));
}
public function getName()
{
return 'custom_datetime';
}
}
The custom_datetime
is then by other forms. 然后, custom_datetime
采用其他形式。 Currently I use it like this: 目前,我像这样使用它:
// date should be entered, time should not -- this does not currently work
$builder->add('dt', 'custom_datetime', ['required' => true, 'time_required' => false]);
// date + time should be entered
$builder->add('dt', 'custom_datetime', ['required' => true, 'time_required' => true]);
// neither of date or time is required
$builder->add('dt', 'custom_datetime', ['required' => false]);
Unfortunately the time
field gets the required attribute when rendered in HTML. 不幸的是,当以HTML呈现时, time
字段会获得必填属性。
What should be done to allow the parent form of custom_datetime
to pass "required" information about time field? 为了使custom_datetime
的父窗体传递有关时间字段的“必需”信息,应该怎么做?
You shouldn't use the attr
attribute for this. 您不应为此使用attr
属性。
$builder
->add('time', 'text', array('required' => true))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.