我需要在Symfony2应用程序的多个位置输入一对日期和时间。为此,我创建了一个custom_datetime
表单类型。我想决定是否需要time
,如果整个custom_datetime都有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';
}
}
custom_datetime
则是其他形式。目前我这样使用它:
// 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]);
不幸的是,time
字段在HTML中呈现时会获得必需的属性。
应该采取哪些措施才能让custom_datetime
的父表单传递有关时间字段的“必需”信息?
答案 0 :(得分:0)
您不应该使用attr
属性。
$builder
->add('time', 'text', array('required' => true))