Back to Top

Symfony – Set EntityType form field default value

Updated 16 July 2021

In this post we learn how to set default value to EntityType form field . EntityType form is especially designed for load options from doctrine entity.

You can easily set default value to EntityType form field by setting the refrence to ‘data’ attribute.

<?php
// src/Webkul/Form/ProductType.php
namespace Webkul\ProductBundle\Form;

use Symfony\Component\Form\AbstractType;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class UserAccount extends AbstractType
{

    public $container;

    public function __construct($container) {
        $this->container = $container;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {   
        $builder->add('name', 'text', array(
            'label' => 'Product Name',
            'attr' => array(
                    'placeholder' => 'Enter product name'
                )
            )
        );

        $builder->add('category', 'entity', array(
            'class' => 'WebkulProductBundle:Category',
            'property' => 'name',
            'attr' => array(
                    'class' => 'selectpicker'
            ),
            'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('c');
            },
            'data' => $this->container->get('doctrine.orm.entity_manager')->getReference("WebkulProductBundle:Category", 4)
        ));

        $builder->add('save', 'submit', array(
                'label' => 'Save',
                'attr' => array(
                        'class'=>'save-btn'
                    )
                )
            );
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Webkul\ProductBundle\Entity\Product',
            'cascade_validation' => true,
        ));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $this->configureOptions($resolver);
    }

    public function getName()
    {
        return 'product_form';
    }
}

Searching for an experienced
Symfony Company ?
Find out More
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home