Miles M.
Miles M.

Reputation: 4169

How to set a default value in a Symfony 2 form field?

I've been trying to set up a form with Symfony 2.

So I followed the tutorial and I've created a special class for creating the form and handling the validation process outside the controller (as shown in the documentation)

But now I need to fill in a field automatically, I've heard that I have to do it in the ProductType.php, where the form (for my product) is created.

But I don't know how to do, here is my buildForm function in ProductType.php :

class QuotesType extends AbstractType
{
    private $id;

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

    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('user_name',              'text')
            ->add('user_lastname',          'text')
            ->add('user_email',             'email')
            ->add('user_comments',          'textarea')
            ->add('user_product_id',        'hidden', array(
                'data' => $this->product_id,
            ));
        ;
    }

and it obviously doesnt work since I got a SQL error saying that my field is null.

How can I put a default value to the user_product_id ? should I do it directly to the object ?

EDIT:

Here is a part of the code of my entity :

namespace QN\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * QN\MainBundle\Entity\Quotes
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="QN\MainBundle\Entity\QuotesRepository")
 */
class Quotes
{

    public function __construct($p_id)
    {
        $this->date = new \Datetime('today');
    }
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var integer $user_product_id
     *
     * @ORM\Column(name="user_product_id", type="integer")
     */
    private $user_product_id = "1";

    /**
     * @var datetime $date
     *
     * @ORM\Column(name="date", type="datetime")
     */
    private $date;

And my controller :

public function requestAction($id)
    {
        $repository = $this->getDoctrine()
                           ->getEntityManager()
                           ->getRepository('QNMainBundle:Categories');
    $categories = $repository->findAll();

    $quote = new Quotes($id);
    $form = $this->createForm(new QuotesType(), $quote);

    $formHandler = new QuotesHandler($form, $this->get('request'), $this->getDoctrine()->getEntityManager());

    if( $formHandler->process() )
    {
        return $this->redirect( $this->generateUrl('QNMain_Product', array('id' => $id)) );
    }

    return $this->render('QNMainBundle:Main:requestaform.html.twig', array(
        'categories' => $categories,
        'id' => $id,
        'form' => $form->createView(),
    ));

}

My Handler :

namespace QN\MainBundle\Form;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManager;
use QN\MainBundle\Entity\Quotes;

class QuotesHandler
{
    protected $form;
    protected $request;
    protected $em;

    public function __construct(Form $form, Request $request, EntityManager $em)
    {
        $this->form    = $form;
        $this->request = $request;
        $this->em      = $em;
    }

    public function process()
    {
        if( $this->request->getMethod() == 'POST' )
        {
            $this->form->bindRequest($this->request);

            if( $this->form->isValid() )
            {
                $this->onSuccess($this->form->getData());

                return true;
            }
        }

        return false;
    }

    public function onSuccess(Quotes $quote)
    {
        $this->em->persist($quote);
        $this->em->flush();
    }

}

I've also put here the Date I try to set up in the entity, I might do something wrong in both case since I can't make it work neither ..Date is not in the buildForm function, I don't know if I should ..

Upvotes: 4

Views: 10725

Answers (2)

yceruto
yceruto

Reputation: 9575

Another way is creating a Form Type Extension:

namespace App\Form\Extension;

// ...

class DefaultValueTypeExtension extends AbstractTypeExtension
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (null !== $default = $options['default']) {   
            $builder->addEventListener(
                FormEvents::PRE_SET_DATA,
                static function (FormEvent $event) use ($default) {
                    if (null === $event->getData()) {
                        $event->setData($default);
                    }
                }
            );
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefault('default', null);
    }

    public static function getExtendedTypes(): iterable
    {
        yield FormType::class;
    }
}

Now any possible value can be passed as default to any form field:

$form->add('user', null, ['default' => $this->getUser()]);
$form->add('user_product_id', null, ['default' => 1]);

This method is specially useful when you don't have a chance to hook into the initialization process of the bound object.

Upvotes: 5

Samy Dindane
Samy Dindane

Reputation: 18706

What you're trying to do here is creating a security hole: anyone would be able to inject any ID in the user_product_id field and dupe you application. Not mentioning that it's useless to render a field and to not show it.

You can set a default value to user_product_id in your entity:

/**
 * @ORM\Annotations...
 */
private $user_product_id = 9000;

Upvotes: 3

Related Questions