添加一个模型转换器,以嵌入形式转换多个字段

Add a model transformer that transforms multiple fields in embedded form

我正在尝试从 2 个输入字段中读取 \DateInterval,如下所示:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', TextType::class, ['label' => "Name"])
        ->add('duration', DateIntervalType::class, ['label' => false])
    ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(['data_class' => NamedInterval::class]);
}

这是我的 DateIntervalType::buildForm

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('amount', IntegerType::class)
        ->add('kind', ChoiceType::class, ['choices' => ['Year' => 'Y', 'Month' => 'M', 'Week' => 'W']])
    ;
}

这是我试过的变压器:

$builder->get('duration')->addModelTransformer(new CallbackTransformer(
    function ($property) {
        return new \DateInterval('P' . $property['amount'] . $property['kind']);
    },
    function ($property) {
        /* compute $specString from $property assuming it's a \DateInterval */
        /* ... */
        return ['amount' => 1, 'kind' => 'W'];
    }
));

因此这是行不通的,在从表单数据转换为 \DateInterval 时验证表单后,我的 $property 总是 null,我什至不确定我是否曾经使用过从 \DateInterval 到形成数据的转换器,我做错了什么?

看来 CallbackTransformer 是反的:

$builder->get('duration')->addModelTransformer(new CallbackTransformer(
    function ($property) {
        /* compute specString from $property assuming it's a \DateInterval */
        /* ... */
        return ['amount' => 1, 'kind' => 'W'];
    },
    function ($property) {
        if (!$property) return null;
        return new \DateInterval('P' . $property['amount'] . $property['kind']);
    }
));

现在它就像一个魅力!

编辑:由于 \DateInterval 将周数转换为天数,因此选项列表中也应该有一个选项 'Day' => 'D'