Symfony表单 - 复选框的映射

时间:2018-01-15 15:09:55

标签: php symfony symfony-forms

我可以指定表单字段如何映射到数据类吗?

我们说我的表格带有复选框,在我的数据实体上,该字段存储为字符串。

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'如果真的和' PAPER'如果是假的?

2 个答案:

答案 0 :(得分:1)

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

SELECT * FROM `locations` ORDER BY id DESC limit 1

答案 1 :(得分:0)

尝试:

$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'