简体   繁体   中英

symfony2 select form with Entity Relations

I'm new in symfony2 and I have to create a select form from 3 tables/objects:

**Game table:**
id,another_column
game_1, 2
game_2, 4
game_3, 10
game_4, 1

**Score table:**
id,user_id,game_id
1,4,game_1
2,4,game_3

After the user is authenticated (I'm using sof user bundle), I have to create a select form with all unplayed games. In this case my select form needs to have two options (game_2 and game_4).

ScoreFormType.php

<?php
/**
 * @package evaluation
 */
namespace GameBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class ScoreFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('game');
    }

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

DefaultController.php

<?php

namespace AppBundle\Controller;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityRepository;
use GameBundle\Entity\Score;
use GameBundle\Form\Type\ScoreFormType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    /**
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction(Request $request)
    {    
        $m = $this->getDoctrine()->getManager();
        $parameters = [];
        if (null !== $this->getUser()) {
            $score = new Score();
            $score
                ->setUser($this->getUser())
                ->setPoints(rand(1,50))
            ;
            $form = $this->createForm(new ScoreFormType(), $score);

            $parameters['form'] = $form->createView();
        }

        return $this->render('AppBundle::index.html.twig', $parameters);
    }

}

Is there any example that can help me? I tried to do a research but nothing relevant.

Thank you.

You should first get your games from the database then add them to your form with:

$form = $this->createForm(new ScoreFormType(), $games);

In your ScoreFormType.php create this:

public function __construct($aYourGames = array())
{
    $this->aYourgames = $aYourGames['Your data'];
}

Now create your "select":

->add('games', 'choice', array(
            'required' => true,
            'label' => 'games',
            'choices' => $this->aYourgames
            )
        )

You can also give a class to your select it will help when you use Javascript:

'attr' => array('class' => 'govChoice'),

I assume the following Entities:

Game :

class Game 
{
    private $id;
    private $title;
}

Score :

class Score
{
    private $id;
    private $user_id; 

    /** 
     * @ORM\ManyToOne(targetEntity="Game")
     */
    private $game_id;
}

FormType :

<?php
/**
 * @package evaluation
 */
namespace GameBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class ScoreFormType extends AbstractType
{

    private $user;

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

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $user = $this->user;

        $builder->add('game', 'entity', array(
                        'class' => 'GameBundle:Game',
                        'property' => 'title',
                        'query_builder' => function (EntityRepository $er) use ($user) {
                               return $er->createQueryBuilder('game')
                                    ->where('game.id NOT IN(SELECT score.game_id FROM GameBundle:Score score WHERE score.user_id = :user'))
                                    ->setParameter('user', $user)
                                    ->orderBy('game.title', 'ASC');
                     ));
    }

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

DefaultController :

<?php

namespace AppBundle\Controller;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityRepository;
use GameBundle\Entity\Score;
use GameBundle\Form\Type\ScoreFormType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends Controller
{
    /**
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction(Request $request)
    {    
        $m = $this->getDoctrine()->getManager();
        $parameters = [];
        $form = $this->createForm(new ScoreFormType($this->getUser()));

        $parameters['form'] = $form->createView();

        return $this->render('AppBundle::index.html.twig', $parameters);
    }

}

Maybe you'll need a bit fiddling around with the query in the form, but that would be one possibility to solve it with basic tools provided by the form component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM