将单个字段“必需”信息传递给复合Symfony2表单

时间:2013-02-07 22:19:45

标签: php forms symfony symfony-forms

我需要在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的父表单传递有关时间字段的“必需”信息?

1 个答案:

答案 0 :(得分:0)

您不应该使用attr属性。

$builder
    ->add('time', 'text', array('required' => true))