Create list of entities in FormBuilder

0

I have a User CRUD and a permissions CRUD.
The idea is now to add a user's CRUD tab to allow you to select permissions.
The starting idea is to have a complete list of all possible permissions with a checkbox next to each other. Then the user can select the permissions he wants without the need to open a modal dialog or something of the genre.

In the backend we get all checked checkboxes and iterate to give the required INSERTS / DELETES in the user_permission table.

In PHP this would be something like:

<?php
$permissions = retrieveAllPermissions();
foreach($permissions as $permission) {
  echo '<input type="checkbox" name="permissions[]" value="' . $permission->id . '">';
  echo $permission->name;
  echo '<br>';
}


// processamento POST
$permissionsChecked = $_POST['permissions'];
// Algum logica para deletar e inserir novamente as permissoes

How can I get this result with Symfony?

  

EDIT 3/26/2015

The relationship of tables is many-to-many with a relational table. In this way:
user
permission user_permission

    
asked by anonymous 25.03.2015 / 19:11

1 answer

1

It's pretty easy.

Suppose you have two entities, a User and a Permission , and a ManyToMany relationship between them:

Class User :

<?php

namespace AppBundle\Entity;

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

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

    /**
     * @ORM\ManyToMany(targetEntity="Permission")
     * @ORM\JoinTable(name="user_permission",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="permission_id", referencedColumnName="id")})
     */
    protected $permissions;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->permissions = new ArrayCollection();
    }

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

    /**
     * Add permissions
     *
     * @param Permission $permission
     * @return User
     */
    public function addPermission(Permission $permission)
    {
        $this->permissions[] = $permission;

        return $this;
    }

    /**
     * Remove permissions
     *
     * @param Permission $permission
     */
    public function removePermission(Permission $permission)
    {
        $this->permissions->removeElement($permission);
    }

    /**
     * Get permissions
     *
     * @return Collection
     */
    public function getPermissions()
    {
        return $this->permissions;
    }
}

Class Permission :

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

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

    /**
     * @ORM\Column(type="text")
     */
    protected $name;

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

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

        return $this;
    }

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

The ManyToMany relationship I created is unidirectional since I only want to know the permissions from the user - not the other way around.

Next, we create Form for creating a user. In this Form , we define that it is possible to relate one or more Permission to a User .

<?php

namespace AppBundle\Form\Type;

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

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('permissions', null, [
                'property' => 'name'
            ]);
    }

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

Finally, we created the controller to handle the permissions change requests for a given user:

<?php

namespace AppBundle\Controller;

use AppBundle\Entity\User;
use AppBundle\Form\Type\UserType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration as Sensio;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class UserController extends Controller
{
    /**
     * @Sensio\Route("/user/{user}/permissions")
     */
    public function userPermissionsAction(Request $request, User $user)
    {
        $form = $this->createForm(new UserType(), $user);
        $form->add('save', 'submit', array('label' => 'Salvar permissões'));

        $form->handleRequest($request);
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();
        }

        return $this->render('user/permissions.html.twig', [
            'form' => $form->createView()
        ]);
    }
}

The form will look like this:

Whenweaddandremoveuserpermissionsthroughthisform,youcanseeDoctrinequeriesintheapplicationlogs.

AddingPermissions:

[2015-03-2612:57:14]doctrine.DEBUG:"START TRANSACTION" [] []
[2015-03-26 12:57:14] doctrine.DEBUG: INSERT INTO user_permission (user_id, permission_id) VALUES (?, ?) [1,1] []
[2015-03-26 12:57:14] doctrine.DEBUG: INSERT INTO user_permission (user_id, permission_id) VALUES (?, ?) [1,2] []
[2015-03-26 12:57:14] doctrine.DEBUG: INSERT INTO user_permission (user_id, permission_id) VALUES (?, ?) [1,3] []
[2015-03-26 12:57:14] doctrine.DEBUG: "COMMIT" [] []

Removing Permissions:

[2015-03-26 12:58:09] doctrine.DEBUG: "START TRANSACTION" [] []
[2015-03-26 12:58:09] doctrine.DEBUG: DELETE FROM user_permission WHERE user_id = ? [1] []
[2015-03-26 12:58:09] doctrine.DEBUG: "COMMIT" [] []

I hope I have helped. :)

    
26.03.2015 / 13:58