Search code examples
symfonyformbuilder

how to set field value for collection type in symfony2


//--form timesheettype---it is not entity class

class TimeSheetType extends AbstractType {

        public function buildForm(FormBuilder $builder, array $options) {
            $builder->
                    add('dailyTimeSheet', 'collection', array('type' => new DailyType(), 'allow_add' => true, 'allow_delete' => true, 'prototype' => true,))
                    ->add('comment','textarea');
        }

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

    }

//--- DailyType -- there is entity for this type

class DailyType extends AbstractType {


    public function buildForm(FormBuilder $builder, array $options) {


        $builder->add('project','entity',array('class'=> 'Parabola\EntityBundle\Entity\Project','property'=>'name'))
               ->add('projectTask', 'entity', array('class'=> 'Parabola\EntityBundle\Entity\ProjectTask','property'=>'name'))
                ->add('hours', 'text');

    }
    public function getDefaultOptions(array $options)
    {
        return array('data_class' => 'Parabola\EntityBundle\Entity\TimeSheetDaily');
    }

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

//-- controller--

$repository = $this->getDoctrine()
                ->getRepository('ParabolaEntityBundle:TimeSheetDaily')->findAll();
        $form = $this->createForm(new \Parabola\TimeSheetBundle\Form\TimeSheetType(),$repository);

I have entity class TimeSheetDaily. While building form of TimeSheetType, I am passing array of TimeSheetDaily class object to form type. and that TimeSheetType has collection of DailyType. It is not Setting value to the collection field which is nothing but a TimeSheetDaily entity.


Solution

  • Have you defined __constructor of TimeSheetDaily class? Do you have something like this?

    public function __construct(){
    //....
    
    $this->dailyTimeSheet = new ArrayCollection();
    
    //....
    };
    

    It's important to correctly initialize this collection in order for Symfony to be able to insert data into it....