John Davidson

php - Access a property from another property in controller

0 comments
Message:


I'm bulding a webapp in Symfony, and I need to access to some properties of an entity in a controller to add this values to $candidature entity. Thank you for the help.


Controller.php :


class CandidatureController extends AbstractController
{
#[Route('/candidature', name: 'app_candidature')]
public function index(EntityManagerInterface $entityManager): Response
{
$candidature = new Candidature();

//$candidatNom = $entityManager->getRepository(ProfileCandidat::class)->findBy($Nom);

$candidature->setNom($candidatNom);
$candidature->setPrenom('Charles');
$candidature->setCv('cv');
$candidature->setPostId('4');

$entityManager->persist($candidature);
$entityManager->flush();
return $this->render('candidature/index.html.twig', [
'controller_name' => 'CandidatureController',
]);
}
}


My Answer:
To access properties of an entity in a controller, you first need to fetch the entity from the database using the entity manager. Once you have the entity object, you can access its properties and set them in the new entity object you are creating.

Here is an example of how you can access properties of an entity in a controller:

php
class CandidatureController extends AbstractController
{
#[Route('/candidature', name: 'app_candidature')]
public function index(EntityManagerInterface $entityManager): Response
{
$profileCandidat = $entityManager->getRepository(ProfileCandidat::class)->findOneBy(['id' => 1]); // Assuming you want to fetch a specific ProfileCandidat entity

$candidature = new Candidature();

$candidature->setNom($profileCandidat->getNom());
$candidature->setPrenom('Charles');
$candidature->setCv('cv');
$candidature->setPostId('4');

$entityManager->persist($candidature);
$entityManager->flush();

return $this->render('candidature/index.html.twig', [
'controller_name' => 'CandidatureController',
]);
}
}


In this example, we are fetching a specific `ProfileCandidat` entity from the database using the entity manager and setting its `Nom` property to the `Nom` property of the `Candidature` entity we are creating. You can access other properties of the `ProfileCandidat` entity in a similar way.

Rate this post

5 of 5 based on 6132 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us