Symfony 表单 - 复选框的映射

Symfony forms - mapping of checkbox

我可以指定表单域如何映射到数据吗class?

假设我有一个带复选框的表单,并且在我的数据实体上该字段存储为字符串。

class FormType extends AbstractType {

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

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('issueType', CheckboxType::class, [
            'label' => 'issueType',
        ]);
    }

}

class DataEntity {

    /** @var string Either PLASTIC or PAPER */
    private $issueType;

    public function getIssueType() {
        return $this->issueType;
    }
    public function setIssueType($issueType) {
        $this->issueType = $issueType;
    }

}

我可以将复选框映射为 'PLASTIC' 如果是 'PLASTIC' 如果是 false 则映射为 'PAPER' 吗?

您可以使用数据转换器将布尔值转换为字符串。请参阅本教程:https://symfony.com/doc/current/form/data_transformers.html.

$builder->get('issueType')
    ->addModelTransformer(new CallbackTransformer(
        function ($type) {
            // your logic here
            return $type;
        },
        function ($type) {
            // your logic here
            return $type;
        }
    ));

尝试:

$builder->add('newsletter', 'choice', array(
    'label' => 'Newsletter erhalten',
    'attr' => array(
        'class' => 'form-control',
    ),
    'choices' => array(array('yes' => 'plastic'), array('no' => 'paper')),
    'expanded' => true,
    'multiple' => true,
    'required' => false,
));

也在这里查看答案Symfony2 Change checkbox values from 0/1 to 'no'/'yes'