У меня проблема при отображении таблицы на ветке. Позвольте мне объяснить, у меня есть две сущности User и Role, которые связаны с отношением ManyToMany, поэтому у меня есть сводная таблица user_role. Проблема в том, что когда я хочу отобразить таблицу пользователей с их ролями в таблице, я получаю сообщение об ошибке:
Возникла исключительная ситуация во время рендеринга шаблона ("Catchable Fatal Error: Не удалось преобразовать объект класса Doctrine \ ORM \ PersistentCollection в строку ").
Вот код для пользователя. php
class User implements UserInterface, \Serializable
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=180, unique=true)
*/
private $username;
/**
* @var string The hashed password
* @ORM\Column(type="string")
*/
private $password;
/**
* @ORM\Column(type="boolean", nullable=false, options={"default" : 0})
*/
private $isActive;
/**
* @ORM\Column(type="string", unique=true, length=64)
*/
private $token;
/**
* @ORM\Column(type="datetime")
*/
private $expiresAt;
/**
* @ORM\ManyToMany(targetEntity="Role", inversedBy="users", fetch="LAZY")
* @ORM\JoinTable(name="user_role",
* joinColumns={
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="role_id", referencedColumnName="id")
* }
* )
*
*/
private $roles = [];
public function __construct()
{
$this->roles = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUsername(): string
{
return (string)$this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
/**
* @inheritDoc
*/
public function getRoles(): array //array return
{
$roles[] = $this->roles;
var_dump($roles);
// Afin d'être sûr qu'un user a toujours au moins 1 rôle
if (empty($roles)) {
$roles[] = 'ROLE_ADMIN';
}
return $roles;
}
/**
* @see UserInterface
*/
public function getPassword(): string
{
return (string)$this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* @see UserInterface
*/
public function getSalt()
{
// not needed when using the "bcrypt" algorithm in security.yaml
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getIsActive(): ?bool
{
return $this->isActive;
}
public function setIsActive(bool $isActive): self
{
$this->isActive = $isActive;
return $this;
}
public function getToken(): ?string
{
return $this->token;
}
public function setToken(string $token): self
{
$this->token = $token;
return $this;
}
public function getExpiresAt(): ?\DateTimeInterface
{
return $this->expiresAt;
}
public function setExpiresAt(\DateTimeInterface $expiresAt): self
{
$this->expiresAt = $expiresAt;
return $this;
}
public function isExpired(): bool
{
return $this->getExpiresAt() <= new \DateTime();
}
public function createToken()
{
return substr(str_replace(['+', '/'], ['-', '_'], base64_encode(random_bytes(50))), 0, 63);
}
public function setRoles($roles)
{
if (is_array($roles)) {
$this->roles = $roles;
} else {
$this->roles->clear();
$this->roles->add($roles);
}
return $this;
}
/**
* Add userRoles
*
* @param \App\Entity\Role $roles
* @return User
*/
public function addRoles(\App\Entity\Role $roles)
{
$this->roles[] = $roles;
return $this;
}
/**
* Remove userRoles
*
* @param \App\Entity\Role $roles
*/
public function removeRoles(\App\Entity\Role $roles)
{
$this->roles->removeElement($roles);
}
/**
* String representation of object
* @link https://php.net/manual/en/serializable.serialize.php
* @return string the string representation of the object or null
* Transform object to string
*/
public function serialize()
{
return serialize([
$this->id,
$this->username,
$this->password,
$this->isActive,
$this->token,
$this->expiresAt,
$this->roles
]);
}
/**
* @param string $serialized
* Transform string to object
*/
public function unserialize($serialized)
{
list(
$this->id,
$this->username,
$this->password,
$this->isActive,
$this->token,
$this->expiresAt
) = unserialize($serialized, ['allowed_classes' => false]);
}
А вот код для роли. php
class Role implements \Serializable
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
/**
* @ORM\Column(type="string", length=255)
*/
private $description;
/**
* @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users = [];
public function __construct()
{
$this->users = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
/*
* methods for RoleInterface
*/
/*public function getRoles()
{
return $this->getName();
}*/
/**
* Add users
*
* @param \App\Entity\User $users
* @return Role
*/
public function addUser(\App\Entity\User $users)
{
$this->users[] = $users;
return $this;
}
/**
* Remove users
*
* @param \App\Entity\User $users
*/
public function removeUser(App\Entity\User $users)
{
$this->users->removeElement($users);
}
/**
* Get users
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
/**
* String representation of object
* @link https://php.net/manual/en/serializable.serialize.php
* @return string the string representation of the object or null
* Transform object to string
*/
public function serialize()
{
return serialize([
$this->id,
$this->name,
$this->description
]);
}
/**
* @param string $serialized
* Transform string to object
*/
public function unserialize($serialized)
{
list(
$this->id,
$this->name,
$this->description
) = unserialize($serialized, ['allowed_classes' => false]);
}
Ensuite dans mon controller j'ai fait un findAll()
/**
* @Route("/admin/user", name="admin_user_index")
* @return \Symfony\Component\HttpFoundation\Response
*/
public function listUser(UserRepository $user)
{
return $this->render('admin/security_user/list_user.html.twig', ['user' => $user->findAll()]);
}
Тогда в моей ветке я получаю данные в массиве
{% for list in user %}
<TR>
<TD>{{ list.id }}</TD>
<TD>{{ list.username }}</TD>
<TD>{{ list.password }}</TD>
<TD>
{% for role in list.roles %}
{{ role }}
{% endfor %}
</TD>
<TD>{{ list.isActive }}</TD>
<TD>
<a href="{{ path('admin_user_edit', {id: list.id}) }}" class="btn btn-secondary">Editer</a>
<form method="post" action="{{ path('admin_user_delete', {id: list.id}) }}" style="display: inline-block"
onsubmit="return confirm('Voulez-vous vraiment supprimer l\'utilisateur ?')">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token('delete' ~ list.id) }}">
<button class="btn btn-primary">Supprimer</button>
</form>
</TD>
</TR>
{% endfor %}
Я хотел бы знать, как искать данные роли вместо persistentCollection
Если кто-нибудь из вас сможет меня просветить, заранее спасибо.