从 Symfony 禁用日期和月份 DateType::class

Disable days and month from Symfony DateType::class

->add('attendFrom', DateType::class, array(
                'widget' => 'choice',
                'html5' => false,
                'months' => array(),
                'days' => array(),
                'attr' => array(
                    'placeholder' => 'Start year, e.g., 1980 ',
                )
            ))

有一种类型我试图从中禁用日期和月份。我只想显示年份。这可能吗?

我找到了一些解决方案来隐藏树枝中的日期和月份,但我想知道是否可以从 FormType 中禁用它。

干杯

yyyy放入format选项

形式:

->add('attendFrom', DateType::class, array(
    'format' => 'yyyy',
    'widget' => 'choice',
    'html5' => false,
    'attr' => array(
        'placeholder' => 'Start year, e.g., 1980 ',
    )
))

Update-1

在 twig 中隐藏月份和日期控件

树枝:

{{ 
    form_widget(
        form.formName.attendFrom.day, 
        { 
            'attr': { 'style': 'display:none' }
        }
    )
    form_widget(
        form.formName.attendFrom.month, 
        { 
            'attr': { 'style': 'display:none' }
        }
    ) 
}}

参考:Link

您只需使用

创建一个 ChoiceType 字段
...
'choices' => range(date('Y') - 10, date('Y') + 10),
...

但是,如果您在提交表单后需要一个 DateTime 对象,那么您应该定义自己的 View Transformer

在您的表单中输入 class 添加以下行:

public function buildForm(
    FormBuilderInterface $builder,
    array $options
)
{
    $builder
        ->add(
            $builder->create('attendFrom', DateType::class, [
                'widget' => 'choice',
            ])
            ->addViewTransformer(new IncompleteDateTransformer())
        );
}

此外,创建您自己的 View Transformer:

/**
 * Class IncompleteDateTransformer.
 */
class IncompleteDateTransformer implements DataTransformerInterface
{
    /**
     * {@inheritdoc}
     */
    public function transform($value)
    {
        return $value;
    }

    /**
     * {@inheritdoc}
     */
    public function reverseTransform($value)
    {
        if (!is_array($value)) {
            return $value;
        }

        if (empty($value['year'])) {
            return $value;
        }

        $value['day'] = $value['day'] ?? 1;
        $value['month'] = $value['month'] ?? 1;

        return $value;
    }
}

然后,仅渲染 attendFrom.year 字段或通过 form_row/form_widget 函数中的 attr 参数隐藏 attendFrom.monthattendFrom.day 字段。有关隐藏其他字段的示例,请参见 Gopal Joshi 的回答。