Jump to content

Symfony and FormTypes


Go to solution Solved by ignace,

Recommended Posts

Hi!

 

For a form I would like to render a selectbox with values from another relation: Type.

This is a many-to-one relation, owned by Type.

Type has many Games, while Game has one Type

 

My question is, how do I show a selectbox with values from Type?

e.g:

Game: Monopoly

Select Type: (selectbox)

- Party game

- Strategy

- Co-op

- etc.

 

-----------------------------------------------

 

This is what I have:

 

GameType.php

<?php

namespace AppBundle\Form;

use AppBundle\Entity\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class GameType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name');
        $builder
        ->add( 'types', choiceType::class, [
        'class' => 'AppBundle:Type',
        'choice_label' => 'name',
        'multiple' => false,
        'choices_as_values' => true,
        'expanded' => true
    ] );


    }
    
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'types' =>  [],
            'data_class' => 'AppBundle\Entity\Game'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'appbundle_game';
    }


}

Entity/Game.php

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;


/**
 * Game
 *
 * @ORM\Table(name="game")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\GameRepository")
 */
class Game
{
    /**
     * @ORM\ManyToOne(targetEntity="Type", inversedBy="games")
     * @ORM\JoinColumn(name="type_id", referencedColumnName="id")
     */
    private $type;



    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;


    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, unique=true)
     */
    private $name;


    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Game
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return mixed
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * @param mixed $type
     */
    public function setType($type)
    {
        $this->type = $type;
    }



}

Entity/Type.php

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;


/**
 * Type
 *
 * @ORM\Table(name="type")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\TypeRepository")
 */
class Type
{
    /**
     * @ORM\OneToMany(targetEntity="Game", mappedBy="type")
     */
    private $games;

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

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;




    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Type
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return mixed
     */
    public function getGames()
    {
        return $this->games;
    }

    /**
     * @param mixed $games
     */
    public function setGames($games)
    {
        $this->games = $games;
    }

}

I'm starting out with Symfony, any help is greatly appreciated!

Link to post
Share on other sites

Thanks for the reply, but by now I'm already using that.

I've changed my code so I want to edit my original post, now I'm looking for the edit button... How silly is that :)

 

I now have selectbox but it replaced my exisiting textfield, I think I know why that is, textfield holds the value for Game.name but the newly added selectbox holds the value of type.name.

 

GameType.php

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add( 'name', EntityType::class, [
                'class' => 'AppBundle:Game',
                'choice_label' => 'name',
                'label' => 'name'
            ] );
        $builder
            ->add( 'name', EntityType::class, [
                'class' => 'AppBundle:Type',
                'choice_label' => 'name',
                'multiple' => false,
                'expanded' => false
            ] );
    }

Could it be that it has something to do with the same property, name?

Edited by jiros1
Link to post
Share on other sites
  • Solution

Thanks for the reply, but by now I'm already using that.

I've changed my code so I want to edit my original post, now I'm looking for the edit button... How silly is that :)

 

I now have selectbox but it replaced my exisiting textfield, I think I know why that is, textfield holds the value for Game.name but the newly added selectbox holds the value of type.name.

 

GameType.php

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add( 'name', EntityType::class, [
                'class' => 'AppBundle:Game',
                'choice_label' => 'name',
                'label' => 'name'
            ] );
        $builder
            ->add( 'name', EntityType::class, [
                'class' => 'AppBundle:Type',
                'choice_label' => 'name',
                'multiple' => false,
                'expanded' => false
            ] );
    }
Could it be that it has something to do with the same property, name?

 

Yes. Your field name should explain it's value:

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add( 'game', EntityType::class, [
                'class' => 'AppBundle:Game',
                'choice_label' => 'name',
                'label' => 'name'
            ] )
            ->add( 'type', EntityType::class, [
                'class' => 'AppBundle:Type',
                'choice_label' => 'name',
                'multiple' => false,
                'expanded' => false
            ] );
    }

Afterwards you can access these fields like:

$form->get('game')
// and
$form->get('type')
Edited by ignace
  • Like 1
Link to post
Share on other sites

Hi Ignace,

thanks to your hint I've made the following changes and got it working:

 

GameType:

        $builder
            ->add('name', TextType::class, [
                'attr' => [
                    'class' => 'form-control',
                ],
            ]);
        $builder
            ->add('type', EntityType::class, [
                'class' => 'AppBundle:Type',
                'choice_label' => function ($type) {
                    return $type->getName();
                },
                'multiple' => false,
                'expanded' => false,
                'attr' => [
                    'class' => 'form-control',
                ],

            ]);

game/show.html.twig

    <table>
        <tbody>
            <tr>
                <th>Name</th>
                <td>{{ game.name }}</td>
            </tr>
            <tr>
                <th>Type</th>
                <td>
                    {% if  game.type is not null  %}
                    {{ game.type.name}}
                    {% endif %}
                </td>
            </tr>
        </tbody>
    </table>
Link to post
Share on other sites
This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.