How to set a default value in Symfony2 so that automatic CRUD generated forms don't require those fields? How to set a default value in Symfony2 so that automatic CRUD generated forms don't require those fields? php php

How to set a default value in Symfony2 so that automatic CRUD generated forms don't require those fields?


Your boolean value need to have nullable set as true:

/** * @var string $sale * * @ORM\Column(name="sale", type="boolean", nullable=true) */private $sale = false;


In Object-oriented programming you should use constructor of the entity to set a default value for an attribute:

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


I haven't used the CRUD auto-generation tool, but I know that by default, each and every field is required. YOu must explicitly pass 'required' => false as an option for your fields.

This can be done in the form classes

namespace Acme\DemoBundle\Form\Type;use Symfony\Component\Form\AbstractType;use Symfony\Component\Form\FormBuilder;class FooType extends AbstractType{    public function buildForm(FormBuilder $builder, array $options)    {        $builder->add('field', 'text', array('required' => false));    }    public function getName()    {        return 'foo';    }}

The same can be achived in a Form class generated inside your controller

namespace Acme\DemoBundle\Controller;use Acme\DemoBundle\Entity\Foo;use Symfony\Bundle\FrameworkBundle\Controller\Controller;use Symfony\Component\HttpFoundation\Request;class DefaultController extends Controller{    public function newAction(Request $request)    {        // ...            $form = $this->createFormBuilder($foo)            ->add('field', 'text', array('required' => false)            ->getForm();        // ...        return $this->render('AcmeDemoBundle:Default:new.html.twig', array(            'form' => $form->createView(),        ));    }}