Home > Mobile >  Symfony 5 Error, I have problem on properties access
Symfony 5 Error, I have problem on properties access

Time:08-19

I'm getting this error and I don't know where is the problem

Neither the property "image_medecin" nor one of the methods "image_medecin()", "getimage_medecin()"/"isimage_medecin()"/"hasimage_medecin()" or "__call()" exist and have public access in class "App\Entity\Medecin"

The problem is I want to show the doctor Image in the view <templates\medecin\show.html.twig> I'm reading from an object medecin as data for the doctor , the problem is all its properties are displayed but the image_medecin property no, I don't know why, Please guys give some help here I'm stuck for hours!

Check the error image here

Check My Entity Medecin:

<?php

namespace App\Entity;

use App\Repository\MedecinRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: MedecinRepository::class)]
class Medecin
{
    public string $UPLOAD_FOLDER = "C:\Users\\email\OneDrive\Bureau\Symfony\clinique\public\assets\Uploads";

    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column()]
    private ?int $id = null;

    #[ORM\Column(length: 40)]
    private ?string $matricule = null;

    #[ORM\Column(type: Types::TEXT, nullable: true)]
    private ?string $experience = null;

    #[ORM\Column]
    private ?float $salaire = null;

    #[ORM\Column(type: Types::TIME_MUTABLE)]
    private ?\DateTimeInterface $temps_travail = null;

    #[ORM\Column(type: Types::DATE_MUTABLE)]
    private ?\DateTimeInterface $jour_travail = null;

    #[ORM\Column(length: 200 , nullable: true)]
    private ?string $image_medecin = null;

    #[ORM\Column(length: 25)]
    private ?string $status_medecin = null;

    #[ORM\OneToOne(mappedBy: 'fk_medecin', cascade: ['persist', 'remove'])]
    private ?User $user = null;

    #[ORM\ManyToMany(targetEntity: Dossier::class, mappedBy: 'fk_medecin')]
    private Collection $dossiers;

    #[ORM\ManyToMany(targetEntity: Specialite::class, inversedBy: 'medecins')]
    private Collection $fk_specialite;

    public function __construct()
    {
        $this->dossiers = new ArrayCollection();
        $this->fk_specialite = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getMatricule(): ?string
    {
        return $this->matricule;
    }

    public function setMatricule(string $matricule): self
    {
        $this->matricule = $matricule;

        return $this;
    }

    public function getExperience(): ?string
    {
        return $this->experience;
    }

    public function setExperience(?string $experience): self
    {
        $this->experience = $experience;

        return $this;
    }

    public function getSalaire(): ?float
    {
        return $this->salaire;
    }

    public function setSalaire(float $salaire): self
    {
        $this->salaire = $salaire;

        return $this;
    }

    public function getTempsTravail(): ?\DateTimeInterface
    {
        return $this->temps_travail;
    }

    public function setTempsTravail(\DateTimeInterface $temps_travail): self
    {
        $this->temps_travail = $temps_travail;

        return $this;
    }

    public function getJourTravail(): ?\DateTimeInterface
    {
        return $this->jour_travail;
    }

    public function setJourTravail(\DateTimeInterface $jour_travail): self
    {
        $this->jour_travail = $jour_travail;

        return $this;
    }

    public function getImageMedecin(): ?string
    {
        return $this->image_medecin;
    }

    public function setImageMedecin(string|null $image_medecin): self
    {
        $this->image_medecin = $image_medecin;

        return $this;
    }

    
    public function getStatusMedecin(): ?string
    {
        return $this->status_medecin;
    }

    public function setStatusMedecin(string $status_medecin): self
    {
        $this->status_medecin = $status_medecin;

        return $this;
    }

    public function getUser(): ?User
    {
        return $this->user;
    }

    public function setUser(?User $user): self
    {
        // unset the owning side of the relation if necessary
        if ($user === null && $this->user !== null) {
            $this->user->setFkMedecin(null);
        }

        // set the owning side of the relation if necessary
        if ($user !== null && $user->getFkMedecin() !== $this) {
            $user->setFkMedecin($this);
        }

        $this->user = $user;

        return $this;
    }

    /**
     * @return Collection<int, Dossier>
     */
    public function getDossiers(): Collection
    {
        return $this->dossiers;
    }

    public function addDossier(Dossier $dossier): self
    {
        if (!$this->dossiers->contains($dossier)) {
            $this->dossiers[] = $dossier;
            $dossier->addFkMedecin($this);
        }

        return $this;
    }

    public function removeDossier(Dossier $dossier): self
    {
        if ($this->dossiers->removeElement($dossier)) {
            $dossier->removeFkMedecin($this);
        }
        
        return $this;
    }

    /**
     * @return Collection<int, Specialite>
     */
    public function getFkSpecialite(): Collection
    {
        return $this->fk_specialite;
    }

    public function addFkSpecialite(Specialite $fkSpecialite): self
    {
        if (!$this->fk_specialite->contains($fkSpecialite)) {
            $this->fk_specialite[] = $fkSpecialite;
        }

        return $this;
    }

    public function removeFkSpecialite(Specialite $fkSpecialite): self
    {
        $this->fk_specialite->removeElement($fkSpecialite);

        return $this;
    }
}

Check my Controller in ( show Method ):

<?php

namespace App\Controller;

use App\Entity\Medecin;
use App\Entity\User;
use App\Form\MedecinType;
use App\Form\UserType;
use App\Repository\UserRepository;
use App\Repository\MedecinRepository;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;


#[Route('/medecin')]
class MedecinController extends AbstractController
{
    #[Route('/', name: 'app_medecin_index', methods: ['GET'])]
    public function index(MedecinRepository $medecinRepository): Response
    {
    //    ["0" => "Inactive" , "1" => "Active" , "2" => "Malade" , "3" => "En Congé"] 
        $medecinData = $medecinRepository->findAllDoctors();
        return $this->render('medecin/test.html.twig', [
            'medecins' => $medecinData 
        ]);
    }

    #[Route('/new', name: 'app_medecin_new', methods: ['GET', 'POST'])]
    public function new(Request $request, MedecinRepository $medecinRepository , UserRepository $userRepository , UserPasswordHasherInterface $passwordHasher): Response
    {
        // Creating The User Form will be created From the class UserType Generator Form To link the Medecin Data to the User Entity Related With The Foreign Key
        $user = new User();
        $formUser = $this->createForm(UserType::class, $user);
        $formUser->remove('user_role');
        $formUser->handleRequest($request);
        // Creating The Medecin Form will be created From the class MedecinType Generator Form 
        $medecin = new Medecin();
        $formMedecin = $this->createForm(MedecinType::class, $medecin);
        $formMedecin->handleRequest($request);

        $plaintextPassword = ''; // get the plain password from the form

        if ($formMedecin->isSubmitted() && $formMedecin->isValid()) {

                // Setting the value null by default for the medecin Image
                $medecin -> setImageMedecin(null);
                // if this condition is not true than it means a file has uploaded , not an empty field file input .
                  if(!($_FILES['medecin']['error']['image_medecin'] == UPLOAD_ERR_NO_FILE)) {
                    // This file superglobal gets all the information from the file that we want to upload using an input from a form
                    $photo = $_FILES['medecin'];
                    // $_files array contains  : name/ type / tmp_name / error / size
                    $fileName = $photo['name']['image_medecin'];
                    $fileTmpName = $photo['tmp_name']['image_medecin'];
                    $fileSize = $photo['size']['image_medecin'];
                    $fileError = $photo['error']['image_medecin'];
                
                    // to get the extension of the file
                    $fileExt = explode('.', $fileName);
                    // Make sure that always the extension comes in small letters
                    $fileActualExt = strtolower(end($fileExt));
                
                    // inside this array we gonna tell it which type of files we want to allow inside the website
                    $allowed = array('jpg' , 'jpeg' , 'png' , 'webp');
                
                    if(in_array($fileActualExt , $allowed)) {
                        // if the file error is equal to 0 that means that we had no erros uploading this file 
                        if($fileError == 0){
                
                            if($fileSize < 5000000){

                                $fileNameNew = "doctor".uniqid().".". $fileActualExt;
                                $fileDestination = $medecin-> UPLOAD_FOLDER  . "/medecin/" . $fileNameNew ;
                                move_uploaded_file($fileTmpName,$fileDestination);
                                $medecin->setImageMedecin($fileNameNew);
        
                            } else {
                                echo "Your file is too big !";
                                exit ;
                            }
                
                            } else {
                            echo "There was an error uploading your file !";
                            exit ;
                            }
                
                    } else {
                        echo "You can not upload files of this type !";
                        exit ;
                    }
                }              
            // Making Sure that the matricule is UpperCase
            strtoupper($medecin->getMatricule());    
            // Adding the medecin to the database
            $medecinRepository->add($medecin, true);

            $user -> setFkMedecin($medecin);
            strtoupper($user -> getCin());
            $user -> setUserRole('ROLE_MEDECIN');
            $hashedPassword = $passwordHasher->hashPassword(
                $user,
                $plaintextPassword
            );
            
            $user->setPassword($hashedPassword);
            $userRepository->add($user, true);

            return $this->redirectToRoute('app_medecin_index', [], Response::HTTP_SEE_OTHER);
        }

        return $this->renderForm('medecin/new.html.twig', [
            'form' => $formUser ,
            'medecinForm' => $formMedecin
        ]);
    }

    #[Route('/{id}', name: 'app_medecin_show', methods: ['GET'])]
    public function show(Medecin $medecin , UserRepository $userRepository): Response
    {
        // echo "<pre>"; var_dump($medecin); echo"</pre>"; exit ;
        return $this->render('medecin/show.html.twig', [
            'medecin' => $medecin
        ]);
    }

    #[Route('/{id}/edit', name: 'app_medecin_edit', methods: ['GET', 'POST'])]
    public function edit(Request $request, int $id , Medecin $medecin, User $user, MedecinRepository $medecinRepository): Response
    {
        $formMedecin = $this->createForm(MedecinType::class, $medecin);
        $formMedecin->handleRequest($request);

        $formUser = $this->createForm(UserType::class, $user);
        $formUser->remove('user_role');
        $formUser->handleRequest($request);

        if ($formMedecin->isSubmitted() && $formMedecin->isValid()) {
            $medecinRepository->add($medecin, true);


            return $this->redirectToRoute('app_medecin_index', [], Response::HTTP_SEE_OTHER);
        }

        return $this->renderForm('medecin/edit.html.twig', [
            'medecin' => $medecin,
            'form' => $formUser,
            'medecinForm' => $formMedecin
        ]);
    }

    #[Route('/{id}/delete', name: 'app_medecin_delete', methods: ['POST'])]
    public function delete(Request $request, Medecin $medecin, MedecinRepository $medecinRepository): Response
    {
        if ($this->isCsrfTokenValid('delete'.$medecin->getId(), $request->request->get('_token'))) {
            $medecinRepository->remove($medecin, true);
        }
        return $this->redirectToRoute('app_medecin_index', [], Response::HTTP_SEE_OTHER);
    }
}

And this the view line ( 34 (Where the error occurs)) :

{% extends 'base.html.twig' %}

{% block title %}Medecin{% endblock %}

{% block body %}
    <h1>Medecin</h1>
{{ dump(medecin) }}

    <a href="{{ path('app_medecin_index') }}">back to list</a>

    <a href="{{ path('app_medecin_edit', {'id': medecin.id}) }}">edit</a>

    {{ include('medecin/_delete_form.html.twig') }}


        <div >
            <div >
                <div >
                    <div >
                        <h4 >My Profile</h4>
                    </div>

                    <div >
                        <a href="edit-profile.html" ><i ></i> Edit Profile</a>
                    </div>
                </div>
                <div >
                    <div >
                        <div >
                            <div >
                                <div >
                                    <div >
                                    
                                <img src="{{ medecin.image_medecin ? "asset('assets/Uploads/medecin/')" ~ medecin.image_medecin : "https://img.freepik.com/free-photo/doctor-with-his-arms-crossed-white-background_1368-5790.jpg?w=2000"}}" alt="Medecin Image">
                                    </div>
                                </div>
                                <div >
                                    <div >
                                        <div >
                                            <div >
                                                <h3 >{{ medecin.user.nom ~ ' ' ~ medecin.user.prenom }}</h3>
                                                <small >Gynecologist</small>
                                                <div >Employee ID : {{ medecin.matricule }}</div>
                                                <div ><a href="chat.html" >Send Message {{ medecin.matricule }}</a></div>
                                            </div>
                                        </div>
                                        <div >
                                            <ul >
                                                <li>
                                                    <span >Phone:</span>
                                                    <span ><a href="#">{{ medecin.user.telephone }}</a></span>
                                                </li>
                                                <li>
                                                    <span >Email:</span>
                                                    <span ><a href="#">{{ medecin.user.email }}</a></span>
                                                </li>
                                                <li>
                                                    <span >Age:</span>
                                                    <span >{{ medecin.user.age }}</span>
                                                </li>
                                                <li>
                                                    <span >Address:</span>
                                                    <span >{{ medecin.user.address }}</span>
                                                </li>
                                                <li>
                                                    <span >Gender:</span>
                                                    <span >Male</span>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>                        
                        </div>
                    </div>
                </div>
                </div>
                <div >
                    <div >
                        <div  id="experienceCard">
                            <h3 >Experience</h3>
                            <div >
                                <ul >
                                    <li>
                                        <div >
                                            <div ></div>
                                        </div>
                                        <div >
                                            <div >
                                                <a href="#/" >Consultant Gynecologist</a>
                                                <span >Jan 2014 - Present (4 years 8 months)</span>
                                            </div>
                                        </div>
                                    </li>
                                    <li>
                                        <div >
                                            <div ></div>
                                        </div>
                                        <div >
                                            <div >
                                                <a href="#/" >Consultant Gynecologist</a>
                                                <span >Jan 2009 - Present (6 years 1 month)</span>
                                            </div>
                                        </div>
                                    </li>
                                    {# <li>
                                        <div >
                                            <div ></div>
                                        </div>
                                        <div >
                                            <div >
                                                <a href="#/" >Consultant Gynecologist</a>
                                                <span >Jan 2004 - Present (5 years 2 months)</span>
                                            </div>
                                        </div>
                                    </li> #}
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                        </div>
                        <div  id="bottom-tab2">
                            Tab content 2
                        </div>
                        <div  id="bottom-tab3">
                            Tab content 3
                        </div>
                    </div>
                </div>
            </div>

        </div>
{% endblock %}

CodePudding user response:

The error is pretty explicit

Neither the property "image_medecin" nor one of the methods "image_medecin()", "getimage_medecin()"/"isimage_medecin()"/"hasimage_medecin()" or "__call()" exist and have public access in class "App\Entity\Medecin"

Twig try to access the attribute image_medecin in your object medecin but it's private it can't be directly accessed.

So it tried image_medecin(), getimage_medecin, isimage_medecin(), hasimage_medecin() and lastly magic method __call().

You can directly use the correct method in your twig template:

<img src="{{ medecin.getImageMedecin() ? "asset('assets/Uploads/medecin/')" ~ medecin.getImageMedecin() : "https://img.freepik.com/free-photo/doctor-with-his-arms-crossed-white-background_1368-5790.jpg?w=2000"}}" alt="Medecin Image">

  • Related