简体   繁体   中英

Load options into drop down on a form based on user's id in symfony 2

I have a question for you and to give you some idea of what i'm doing, i will try and explain the idea. I have a system where user's are able to add geckos to a database, when that gecko is added, it saves the user id into a column called user_id - this works perfect and sets me up for what i am trying to achieve now.

I have a system where user's are able to add weight entries for that gecko, problem is, right now it just loads every gecko in the database, not the one's that are specific to that user.

Here is a portion from my Weight.php entity:

/**
 * @ORM\ManyToOne(targetEntity="Gecko", inversedBy="weights")
 * @ORM\JoinColumn(name="gecko_id", referencedColumnName="id")
 */
private $geckoId;

Which is linked to this part in the Gecko.php :

/**
 * @ORM\OneToMany(targetEntity="Weight", mappedBy="geckoId", cascade={"persist", "remove"})
*/
private $weights;

And here is the user part inside Gecko.php entity which links the current user's id to save to the database:

/**
 * @ORM\ManyToOne(targetEntity="Breedr\UserBundle\Entity\User", inversedBy="geckos")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
protected $user;

And the linked part in the User.php entity:

/**
 * @ORM\OneToMany(targetEntity="Breedr\GeckoBundle\Entity\Gecko", mappedBy="user", cascade={"persist", "remove"})
 */
protected $geckos;

Now, here is my Weight entities Form ( WeightType.php ):

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('weighedDate')
        ->add('weight')
        ->add('geckoId')
    ;
}

Which gives you a drop down based on the parts above that look like this: 重量输入表

So what i am now trying to achieve is to ONLY show the geckos that are linked with the current user's ID. What is the best way to achieve this?

Thanks in advance :)

Andy

EDIT:

Here is my WeightType file:

<?php

namespace Breedr\GeckoBundle\Form;

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

class WeightType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('weighedDate')
            ->add('weight')
            ->add('geckoId')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Breedr\GeckoBundle\Entity\Weight'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'breedr_geckobundle_weight';
    }
}

EDIT 2: Here is my create form snippet:

private function createCreateForm(Weight $entity)
    {
        $form = $this->createForm(new WeightType(), $entity, array(
            'action' => $this->generateUrl('weight_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

You must use entity Field Type + query_build option. Thus You can build a custom query in order to filter the results, for instance:

<?php 
namespace AppBundle\Form\Type;

use Doctrine\ORM\EntityRepository;
// ...

$builder->add('users', 'entity', array(
    'class' => 'AcmeHelloBundle:User',
    'query_builder' => function (EntityRepository $er) {
        return $er->createQueryBuilder('u')
            ->orderBy('u.username', 'ASC');
    },
));

On your specific case your form type might looks like something like this:

<?php 
# maybe you need to fix some namespaces...

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class WeightType extends AbstractType
{

     /** @var int */
    protected $currentUserId;

    /**
     * param int $currentUserId It can be passed from controller 
     * when creating form instance
     */
    public function __construct($currentUserId)
    {
        $this->currentUserId = $currentUserId;
    }

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

        $builder->add('users', 'entity', array(
            'class' => 'GeckoBundle:Gecko',
            'query_builder' => function (EntityRepository $er) use ($id) {
                return $er->createQueryBuilder('g')
                    ->where('user_id = ?')                  
                    ->setParameter(0, $id);
            },
        ));
    }    
}

On the controller...

<?php 
//...

public function add()
{
   $currentUserId = $this->getUser()->getId(); # may be it...
   $form = $this->createForm(new WeigthType($currentUserId));
}

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