0

Using symfony 2.6 and twig : I have answers provided by a lot of users in my database. I want to create a form linsing all of them for a given user, to allow him to edit them.

I get these responses with the following code :

Controller :

$responses = $this->getDoctrine()->getRepository('AppBundle:Response')
->findBy(
    array('user' => $usr,
        'response' => 1,
        'response' => 2
    ),
    array('id' => 'ASC')
);

$form = $this->createForm(new ActionType, $responses)->createView();

ActionType :

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('check', 'entity', array(
            'required' => false,
            'class' => 'AppBundle:Response',
            'property'      => 'id',
            'property_path' => '[id]',
            'multiple'      => true,
            'expanded'      => true,
        ))
    ;
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => null,
        'csrf_protection' => false
    ));
}

This answer does exactly what I want, but I can't get it working. The form generated is way too huge : it takes the whole Response table... Do you have any clue why ?

Community
  • 1
  • 1
Leogout
  • 1,187
  • 1
  • 13
  • 32

1 Answers1

0

If you rely solely on doctrine lazy loading it will load all your related entities, it's both good and bad like that.

To filter your responses for user fetch your data with QueryBuilder like so:

$responses = $queryBuilder->select('u', 'r')
                ->from('YourBundle:User', 'u')
                ->join('u.responses', 'r')
                ->where('u.id = :userId')
                ->orderBy('u.id', 'ASC')
                ->setParameter('userId', $yourUserEntity->getId())
                ->getQuery()->getResult();

As above, specifically selecting the entities you want hydrated avoids a lazy load of all available data.

Richard
  • 4,079
  • 1
  • 14
  • 17