Home > other >  How can I show another Entity linked to the main one on html.twig?
How can I show another Entity linked to the main one on html.twig?

Time:11-02

I have a problem with showcasing an Entity's property on another one's html.twig that is linked.

Basically, one entity called Cats, one Entity called Appointment relation ManyToOne (one cat can have several appointments but one appointment is linked to one cat only)

Cats entity:

/**
 * @ORM\OneToMany(targetEntity=Appointment::class, mappedBy="cat", orphanRemoval=true)
 */
private $appointments;

/**
 * @return Collection|Appointment[]
 */
public function getAppointments(): Collection
{
    return $this->appointments;
}

public function addAppointment(Appointment $appointment): self
{
    if (!$this->appointments->contains($appointment)) {
        $this->appointments[] = $appointment;
        $appointment->setCat($this);
    }

    return $this;
}

public function removeAppointment(Appointment $appointment): self
{
    if ($this->appointments->removeElement($appointment)) {
        // set the owning side to null (unless already changed)
        if ($appointment->getCat() === $this) {
            $appointment->setCat(null);
        }
    }

    return $this;
}

Appointment entity:

/**
 * @ORM\ManyToOne(targetEntity=Cats::class, inversedBy="appointments", cascade={"persist"} )
 * @ORM\JoinColumn(nullable=false)
 */
private $cat;

public function getCat(): ?Cats
{
    return $this->cat;
}

public function setCat(?Cats $cat): self
{
    $this->cat = $cat;

    return $this;
}

And here is what I tried to do in html.twig for appointment_show

{% extends 'base.html.twig' %}
{% block title %}Appointment{% endblock %}
{% block main %}

<h1>Appointment</h1>

{% for cat in appointment.cats %}
    <div>
        <td>{{ appointment.cat_id }}</td>
    </div>
{% endfor %}

So I keep getting for error:

Neither the property "cats" nor one of the methods "cats()", "getcats()"/"iscats()"/"hascats()" or "__call()" exist and have public access in class "App\Entity\Appointment".

Can you help?

CodePudding user response:

Thank you, I changed my code to the following and it worked:

{% for appointment in appointments %}
    {% set cat = appointment.cat %}
        <div>
            {{ cat.id }}
        </div>
{% endfor %}
  • Related