在Symfony formtype中过滤集合

时间:2017-04-10 19:12:10

标签: forms symfony doctrine

摘要

我有三个实体: 用户,组织和OrganistionUser。

我创建了一个包含OrganisationUsers嵌入式集合的组织表单。这很有效。我无法工作的是,只有没有关联的用户(对组织)才会被查询'并显示在OrganisationForm的选择框中。

详细

实体1:组织     

class Organisation
{

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     *
     * @ORM\Column(type="string", nullable=true)
     */
    protected $name;


    /**
     * @ORM\OneToMany(targetEntity="OrganisationUser", mappedBy="organisation_id", cascade={"persist", "remove"}, orphanRemoval=true)
     *
     * @Expose
     */
    private $users;

申请2:用户 (我扩展了FOSUserBundle)

<?php


/**
 * @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;


    /**
     * @var string
     */
    protected $username;

    /**
     * @var \Doctrine\Common\Collections\ArrayCollection
     * @ORM\OneToMany(targetEntity="OrganisationUser", mappedBy="user_id", cascade={"ALL"}, orphanRemoval=true)
     */
    protected $organisationusers;

我成功地嵌入了一系列表格。在我的“创建新组织形式”中我可以添加许多用户,并将它们保存到数据库中。

它们保存在OrganisationUser表中(因为我只想将现有用户与组织关联)。

OrganisationUser实体(实际上我有三个实体)看起来像:

申请3:OrganisationUser

<?php


class OrganisationUser
{

    protected $id;


    /**
     * @var ProjectId
     * @ORM\ManyToOne(targetEntity="Organisation", inversedBy="organisationusers")
     * @ORM\JoinColumn(name="organisation_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $organisation_id;


    /**
     * @var ProjectId
     * @ORM\ManyToOne(targetEntity="User", inversedBy="organisationusers")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $user_id;

现在,在我的表格(OrganisionType)中,我嵌入了一个OrganisationUser的集合。但我想操纵数据(我不想显示所有用户。只有与组织无关的用户)。我怎样才能做到这一点。我已经看过这里和这里但是这个问题没有解决方案所以我创建了一个新问题。

OrganistionType:

<?php

class OrganisationType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {


        $builder
            ->add('name')
            ->add('address')
            ->add('postal')
            ->add('city')
            ->add('phone')
            ->add('email')
            ->add('role');

        $builder->add('users', 'collection', array(
            'entry_type' => new OrganisationUserType(),
            'allow_add' => true,
            'allow_delete' => true,
            'by_reference' => false,
            'required' => false,
        ));


    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Organisation',
        ));
    }
}

OrganisationUserType:

<?php

class OrganisationUserType extends AbstractType
{

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder
            ->add('user_id', null ,array(
                'label' => 'User'
            ))
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\OrganisationUser'
        ));
    }

}

控制器

<?php

/**
 * Organisation controller.
 *
 * @Route("/organisation")
 */
class OrganisationController extends Controller
{    
    /**
     * Creates a new Organisation entity.
     *
     * @Route("/new", name="organisation_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $organisation = new Organisation();
        $form = $this->createForm('AppBundle\Form\OrganisationType', $organisation);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($organisation);
            $em->flush();

            return $this->redirectToRoute('organisation_show', array('id' => $organisation->getId()));
        }

        return $this->render('organisation/new.html.twig', array(
            'organisation' => $organisation,
            'form' => $form->createView(),
        ));
    }

这是渲染时的样子: enter image description here 并且,让我们说如果testuser3已经与组织关联,我不希望他出现在下拉列表中:)

1 个答案:

答案 0 :(得分:1)

好的,我找到了。在我的OrganisationType中,我使用OrganisationUserType来嵌入用户集合。所以在OrganisationUserType中我必须查询结果: 当然这不是正确的查询,但我现在知道在哪里操纵数据。现在我可以去寻找正确的查询:)

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
use App\Http\Requests;

class UserController extends Controller
{
    public function getWelcome()
    {
        $user = new User();
        if (Auth::user()){
            return redirect()->route('dashboard');
        }
        return view('welcome',  array('user'=> Auth::user()), compact('users') );
    }    

    public function userSignUp(Request $request)
    {

        $this->validate($request,[
            'email' => 'required|email|unique:users',
            'username' => 'required|max:120',
            'password' => 'required|min:4'

        ]);

        $email = $request['email'];
        $username = $request['username'];
        $password = bcrypt($request['password']);

        $user = new User();
        $user->email = $email;
        $user->username = $username;
        $user->password = $password;

        $user->save();
        return redirect()->route('dashboard'); 
    }

    public function postSignin(Request $request)
    {
        $remember = $request->input('remember_me');

        if(Auth::attempt(['email'=> $request['email'], 'password' => $request['password']], $remember )){
            return redirect()->route('dashboard');
        }

        return redirect()->back();
    }    

    public function getLogout()
    {
        Auth::logout();
        return redirect()->route('home');
    }
}