Jan Tajovsky
Jan Tajovsky

Reputation: 1211

Symfony forms - mapping of checkbox

Can I specify how the form field shold be mapped on data class?

Let's say I have form with check box and on my data entity the field is stored as string.

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;
    }

}

Can I made the checkbox to be mapped as 'PLASTIC' if ture and 'PAPER' if false?

Upvotes: 1

Views: 1320

Answers (2)

Kareem Essawy
Kareem Essawy

Reputation: 615

try :

$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,
));

also check the answer here Symfony2 Change checkbox values from 0/1 to 'no'/'yes'

Upvotes: 0

Michał Szczech
Michał Szczech

Reputation: 456

You can use data transformer to cast bolean to the string. See this tutorial: 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;
        }
    ));

Upvotes: 1

Related Questions