1

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?

2 Answers 2

1

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;
        }
    ));
Sign up to request clarification or add additional context in comments.

Comments

0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.