#symfony #twig #symfony4
#symfony #twig #symfony4
Вопрос:
Мой блог
Здесь у меня небольшая проблема с моим кодом для получения пользователя в Twig, у меня есть множество связей между таблицей статей и таблицей пользователей, я хочу получить автора статьи, но не могу. в базе данных все хорошо, но в Twig я не знаю, как это сделать.
Mon code
ArticleController.php
/**
* @Route("/add-article", name="add_article", methods={"GET","POST"})
*/
public function new(Request $request): Response
{
$article = new Article();
$form = $this->createForm(ArticleFormType::class, $article);
$form->handleRequest($request);
if ($form->isSubmitted() amp;amp; $form->isValid())
{
$article->setUsers($this->getUser());
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($article);
$entityManager->flush();
return $this->redirectToRoute('blog_articles');
}
return $this->render('articles/Article-form.html.twig', [
'form_title'=> 'Ajouter un Article',
'form_article' => $form->createView(),
]);
}
Мой Twig
{% for article in articles %}
<div class="col-md-6 col-lg-4">
<div class="card mb-4 shadow-sm">
<!-- CONDITIONS POUR L'AFFICHAGE DES PHOTOS-->
{% if article.photo is defined and article.photo is not null %}
<img src="{{asset('images/')}}{{ article.photo }}" class="img-fluid" width="100%" height="225">
{% else %}
<img src="{{asset('images/img-17.jpg')}}" class="img-fluid" width="100%" height="225">
{% endif %}
<div class="card-body">
<!--BOUCLE POUR RECUPERER LE CATEGORIE DE CHAQUE ARTICLE-->
{% for categorie in article.categories %}
<span class="text-left" style="color: grey;">{{ categorie.nom }}</span>
{% endfor %}
<!-- FIN DE LA BOUCLE-->
<h4 class="text-center titre">
<a href="{{ path('blog_article', {'id': article.id}) }}"> {{ article.titre }} </a>
</h4>
<p class="card-text">{{ article.description }}</p>
<div class="d-flex justify-content-between align-items-center">
<!-- Post Author -->
<p class="text-muted">{{ article.users.nom }} - {{ article.createdAt| date('d/m/Y')}}</p>
<div class="social">
<ul class="list-inline">
<a href="" class="mr-4"><i class="fa fa-heart" aria-hidden="true"></i> 3 </a>
<a href=""><i class="fas fa-comments" aria-hidden="true"></i> 5 </a>
</ul>
</div>
</div>
</div>
</div>
</div>
{% endfor %}
<!-- FIN DE LA BOUCLE POUR LES ARTICLES-->
Что я получаю
Impossible to access an attribute ("nom") on a null variable.
Article.php
<?php
namespace AppEntity;
use AppRepositoryArticleRepository;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineORMMapping as ORM;
/**
* @ORMEntity(repositoryClass=ArticleRepository::class)
*/
class Article
{
/**
* @ORMId
* @ORMGeneratedValue
* @ORMColumn(type="integer")
*/
private $id;
/**
* @ORMColumn(type="string", length=50)
*/
private $titre;
/**
* @ORMColumn(type="string", length=255)
*/
private $description;
/**
* @ORMColumn(type="text")
*/
private $contenu;
/**
* @ORMColumn(type="string", length=255, nullable=true)
*/
private $photo;
/**
* @ORMColumn(type="string", length=255)
*/
private $slug;
/**
* @ORMColumn(type="datetime")
*/
private $created_at;
/**
* @ORMColumn(type="datetime", nullable=true)
*/
private $updated_at;
/**
* @ORMOneToMany(targetEntity=Commentaire::class, mappedBy="articles", orphanRemoval=true)
*/
private $commentaires;
/**
* @ORMManyToMany(targetEntity=Categorie::class, inversedBy="articles")
*/
private $categories;
/**
* @ORMManyToOne(targetEntity=User::class, inversedBy="articles")
*/
private $users;
public function __construct()
{
$this->commentaires = new ArrayCollection();
$this->categories = new ArrayCollection();
$this->created_at= new DateTime('now');
}
public function getId(): ?int
{
return $this->id;
}
public function getTitre(): ?string
{
return $this->titre;
}
public function setTitre(string $titre): self
{
$this->titre = $titre;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getContenu(): ?string
{
return $this->contenu;
}
public function setContenu(string $contenu): self
{
$this->contenu = $contenu;
return $this;
}
public function getPhoto(): ?string
{
return $this->photo;
}
public function setPhoto(?string $photo): self
{
$this->photo = $photo;
return $this;
}
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(string $slug): self
{
$this->slug = $slug;
return $this;
}
public function getCreatedAt(): ?DateTimeInterface
{
return $this->created_at;
}
public function setCreatedAt(DateTimeInterface $created_at): self
{
$this->created_at = $created_at;
return $this;
}
public function getUpdatedAt(): ?DateTimeInterface
{
return $this->updated_at;
}
public function setUpdatedAt(?DateTimeInterface $updated_at): self
{
$this->updated_at = $updated_at;
return $this;
}
/**
* @return Collection|Commentaire[]
*/
public function getCommentaires(): Collection
{
return $this->commentaires;
}
public function addCommentaire(Commentaire $commentaire): self
{
if (!$this->commentaires->contains($commentaire)) {
$this->commentaires[] = $commentaire;
$commentaire->setArticles($this);
}
return $this;
}
public function removeCommentaire(Commentaire $commentaire): self
{
if ($this->commentaires->removeElement($commentaire)) {
// set the owning side to null (unless already changed)
if ($commentaire->getArticles() === $this) {
$commentaire->setArticles(null);
}
}
return $this;
}
/**
* @return Collection|categorie[]
*/
public function getCategories(): Collection
{
return $this->categories;
}
public function addCategory(categorie $category): self
{
if (!$this->categories->contains($category)) {
$this->categories[] = $category;
}
return $this;
}
public function removeCategory(categorie $category): self
{
$this->categories->removeElement($category);
return $this;
}
public function getUsers(): ?user
{
return $this->users;
}
public function setUsers(?user $users): self
{
$this->users = $users;
return $this;
}
}
User.php
<?php
namespace AppEntity;
use AppRepositoryUserRepository;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineORMMapping as ORM;
use SymfonyBridgeDoctrineValidatorConstraintsUniqueEntity;
use SymfonyComponentSecurityCoreUserUserInterface;
/**
* @ORMEntity(repositoryClass=UserRepository::class)
* @UniqueEntity(fields={"email"}, message="There is already an account with this email")
*/
class User implements UserInterface
{
/**
* @ORMId
* @ORMGeneratedValue
* @ORMColumn(type="integer")
*/
private $id;
/**
* @ORMColumn(type="string", length=180, unique=true)
*/
private $email;
/**
* @ORMColumn(type="json")
*/
private $roles = [];
/**
* @var string The hashed password
* @ORMColumn(type="string")
*/
private $password;
/**
* @ORMColumn(type="boolean")
*/
private $isVerified = false;
/**
* @ORMColumn(type="string", length=50)
*/
private $nom;
/**
* @ORMColumn(type="string", length=50)
*/
private $prenom;
/**
* @ORMOneToMany(targetEntity=Article::class, mappedBy="users")
*/
private $articles;
/**
* @ORMOneToMany(targetEntity=Commentaire::class, mappedBy="users", orphanRemoval=true)
*/
private $commentaires;
public function __construct()
{
$this->articles = new ArrayCollection();
$this->commentaires = new ArrayCollection();
}
public function __toString()
{
return $this->prenom . ' ' . $this->nom;
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* @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 isVerified(): bool
{
return $this->isVerified;
}
public function setIsVerified(bool $isVerified): self
{
$this->isVerified = $isVerified;
return $this;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getPrenom(): ?string
{
return $this->prenom;
}
public function setPrenom(string $prenom): self
{
$this->prenom = $prenom;
return $this;
}
/**
* @return Collection|Article[]
*/
public function getArticles(): Collection
{
return $this->articles;
}
public function addArticle(Article $article): self
{
if (!$this->articles->contains($article)) {
$this->articles[] = $article;
$article->setUsers($this);
}
return $this;
}
public function removeArticle(Article $article): self
{
if ($this->articles->removeElement($article)) {
// set the owning side to null (unless already changed)
if ($article->getUsers() === $this) {
$article->setUsers(null);
}
}
return $this;
}
/**
* @return Collection|Commentaire[]
*/
public function getCommentaires(): Collection
{
return $this->commentaires;
}
public function addCommentaire(Commentaire $commentaire): self
{
if (!$this->commentaires->contains($commentaire)) {
$this->commentaires[] = $commentaire;
$commentaire->setUsers($this);
}
return $this;
}
public function removeCommentaire(Commentaire $commentaire): self
{
if ($this->commentaires->removeElement($commentaire)) {
// set the owning side to null (unless already changed)
if ($commentaire->getUsers() === $this) {
$commentaire->setUsers(null);
}
}
return $this;
}
}
phpMyAdmin
Это статья, user_Id 1. это хорошо, у меня есть вся необходимая информация в базе данных. моя проблема в том, что я не могу показать имя человека, который создал статью.
Мне жаль , что мой английский не идеален.
Комментарии:
1. Я искренне надеюсь, что вы не назвали свойство в статье «пользователи», потому что это раздражает. Теоретически способ доступа хорош, если это один пользователь и свойство было вызвано
users
, я надеюсь, что это не так. вероятно, более уместно посмотреть объект article. и вы действительно уверены, что у конкретной статьи (статей) есть пользователи?2. Где именно ты застрял? Какой из двух
nom
случаев вызывает проблему? И как выглядит ваша сущность?3. Проблема в том, что при первом создании статьи пользователь не задан. $article = новая статья(); $article->setUsers($this->getUser());
4. если у пользователя в базе данных «nom» not null, не возможно ли, что ошибка исходит из «категорий»?
{{ categorie.nom }}
5. Если у статьи может быть нулевой пользователь , вы можете присвоить значение по умолчанию , подобное этому , в twig :
{{ article.users.nom|default('visitor') }}
Ответ №1:
в сообщении об ошибке говорится, что свойство users статьи равно null, что приводит нас к ошибке в сопоставлении ORM, поскольку вы говорите, что поле базы данных user_id статьи имеет правильное значение (1).
Это означает, что ошибка, скорее всего, находится в аннотации над свойством users. Глядя на ваш код, я замечаю, что одна вещь, которая привлекает мое внимание, — это ваш синтаксис при указании на targetEntity . Вы используете User::class, но согласно документации doctrine, он должен быть таким targetEntity=»User» или таким targetEntity=»App Entity User»
/**
* @ORMManyToOne(targetEntity=User::class, inversedBy="articles")
*/
private $users;
https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/reference/association-mapping.html
Возможно, я ошибаюсь, возможно, что doctrine принимает весь этот синтаксис, но я думаю, что стоит проверить этот момент
РЕДАКТИРОВАТЬ — поскольку проблема не в том, что указано выше, еще одна вещь, которую следует проверить, — это способ заполнения объекта Article. Я думал, вы должны использовать метод getData() следующим образом:
$form = $this->createForm(ArticleType::class);
$form->handleRequest($request);
if ($form->isSubmitted() amp;amp; $form->isValid()) {
// new article object come back populated by the form
$article = $form->getData();
// record the new article
$em = $this->getDoctrine()->getManager();
$em->persist($article);
$em->flush();
}
Комментарии:
1. Я с symfony 5, отображение другое.
2. о, хорошо, не знал этого, спасибо за ваш отзыв
Ответ №2:
код идеален, единственная проблема, с которой я столкнулся, заключается в том, что некоторые статьи были созданы до подключения, и по этой причине пользователь был нулевым в базе данных и не мог его отобразить. Я удалил эти статьи, и проблема была решена.