Create list of entities in Formbuilder

Asked

Viewed 103 times

0

I have a User CRUD and a CRUD of permissions.
The idea now is to add a tab to the user’s CRUD to allow selecting permissions.
The initial 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 back-end we take all checkboxes checked and make an iteration to give the proper INSERTS/DELETES in the user_permission table.

In plain 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 26/03/2015

The relation of the tables is Many-to-Many with a relational table. Thus:
user
permission
usuario_permissao

  • Wow, what a gaffe! I thought I was in soEN. hehe, I’ll edit it :)

  • How is the database relationship between a user and a permission? Many-to-Many with relational table?

  • That’s right. Many-to-Many with a relational table. I will edit the question and add this information

1 answer

1


It’s pretty easy.

Suppose you have two entities, one User and a Permission, and a relationship ManyToMany among 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 relationship ManyToMany that I created is unidirectional because I only care about knowing permissions from the user - and not the other way around.

Then we created the Form to create a user. In this Form, we define that it is possible to relate one or more Permission in 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 permissions change requests for a particular 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:

inserir a descrição da imagem aqui

When we add and remove user permissions through this form, you can see in the application logs the darlings of the Doctrine.

Adding permissions:

[2015-03-26 12: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’ve helped. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.