PHP code example of yokai / many-to-many-matrix-bundle
1. Go to this page and download the library: Download yokai/many-to-many-matrix-bundle library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
yokai / many-to-many-matrix-bundle example snippets
namespace App\Entity;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
#[ORM\Table(name: 'user')]
class User
{
#[ORM\Column(type: 'integer')]
#[ORM\Id]
#[ORM\GeneratedValue]
private ?int $id = null;
#[ORM\Column(type: 'string', unique: true)]
private string $email;
/**
* @var Collection<Role>
*/
#[ORM\ManyToMany(targetEntity: Role::class, inversedBy: 'users')]
private Collection $roles;
public function __toString(): string
{
return $this->email;
}
//...
}
namespace App\Entity;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
#[ORM\Table(name: 'role')]
class Role
{
#[ORM\Column(type: 'integer')]
#[ORM\Id]
#[ORM\GeneratedValue]
private ?int $id = null;
#[ORM\Column(type: 'string', unique: true)]
private string $role;
/**
* @var Collection<User>
*/
#[ORM\ManyToMany(targetEntity: User::class, inversedBy: 'roles')]
private Collection $users;
public function __toString(): string
{
return $this->role;
}
//...
}
namespace App\Controller;
use App\Entity\Role;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Yokai\ManyToManyMatrixBundle\Form\Type\ManyToManyMatrixType;
class MatrixController extends AbstractController
{
#[Route(path: '/role-matrix', name: 'role-matrix')]
public function roleMatrixAction(Request $request, EntityManagerInterface $manager): Response
{
$roles = $manager->getRepository(Role::class)->findAll();
$form = $this->createForm(
ManyToManyMatrixType::class,
$roles,
[
'class' => Role::class,
'association' => 'users',
]
);
$form->handleRequest($request);
if (!$form->isSubmitted() || !$form->isValid()) {
return $this->render('role-matrix.html.twig', [
'form' => $form->createView(),
]);
}
foreach ($roles as $role) {
$manager->persist($role);
}
$manager->flush();
return $this->redirectToRoute('role-matrix');
}
}