in a many to many relationship
In the controller , how can I get all the users join to a specific event?
I have tried to get users from the specific event, but it get all users of all events.
I need to get users from the specific event because i want notify all those users via email.
capture of table sql
public function notificarATodos(MailerInterface $mailer, Request $request, UserPasswordEncoderInterface $passwordEncoder, Evento $evento, User $user): Response
{
$user_repo = $this->getDoctrine()->getRepository(User::class);
$user = $user_repo->findAll();
$evento = $this->getDoctrine()->getRepository(Evento::class)->findOneById($evento);
//$user->GetEventos($evento);
$evento->GetUsers($user);
dump($user);die;
$form = $this->createForm(ContactoFormType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$email = $user->getEmail();
$contactFormData = $form->getData();
$email = (new Email())
->from('')
->to($user->getEmail())
->subject($contactFormData['asunto'],
'text/plain')
->text($contactFormData['mensaje'],
'text/plain');
$mailer->send($email);
$this->addFlash('success', 'EMAIL ENVIADO CORRECTAMENTE');
return $this->redirect($this->generateUrl('evento_detalle', ['id' => $evento->getId()]));
}
return $this->render('user/contactar.html.twig', [
'form' => $form->createView(),
]);
}
This is pretty much exactly the same as https://stackoverflow.com/a/65905944/6127393
$users = $evento->GetUsers();
...
if ($form->isSubmitted() && $form->isValid()) {
foreach($users as $user){
$email = $user->getEmail();
...
}
}
Related
In my project I want to use the object created by my precedent form:
Here is the schema of my database:
My QuizController
public function creation(Request $request){
$quiz = new Quiz();
$user = $this->getUser();
$formQuiz = $this->createForm(QuizType::class, $quiz);
$formQuiz->handleRequest($request);
if ($formQuiz->isSubmitted() && $formQuiz->isValid() ) {
$quiz->setCreatedAt(new DateTimeImmutable());
$quiz->setCreatedBy($user);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($quiz);
$entityManager->flush();
return $this->redirectToRoute('creation_questions');
}
return $this->render('quiz/creation.html.twig', [
'formQuiz' => $formQuiz->createView(),
]);
}
And my QuestionController that must be connected with the quiz form
public function creation_questions(Request $request){
$quiz = ?
$question = new Questions();
$formQuestions = $this->createForm(QuestionType::class, $question);
$formQuestions->handleRequest($request);
if ($formQuestions->isSubmitted() && $formQuestions->isValid() ) {
$question->setCreatedAt(new DateTimeImmutable());
$question->setQuiz($quiz);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($question);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('questions/questions.html.twig', [
'formQuestion' => $formQuestions->createView()
]);
}
What do I have to write in place of the '?'?
You don't show your routing but you could use paramConverte "magic" from SensioFrameworkExtraBundle and do something like this.
/**
* #Route("/some-route/{id}", name="some_route_name")
*/
public function creation_questions(Request $request, Quiz $quiz)
{
$question = new Questions();
$formQuestions = $this->createForm(QuestionType::class, $question);
$formQuestions->handleRequest($request);
if ($formQuestions->isSubmitted() && $formQuestions->isValid()) {
$question->setCreatedAt(new DateTimeImmutable());
$question->setQuiz($quiz);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($question);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('questions/questions.html.twig', [
'formQuestion' => $formQuestions->createView()
]);
}
Where the {id} part of /someRoute/{id} is the Quiz Id. Symfony should automagically fetch the Quiz matching that id. Or you can be more explicit about how the param converter should interpret such a value. More info here https://symfony.com/bundles/SensioFrameworkExtraBundle/current/annotations/converters.html
Alternatively, you could pass the quiz id and fetch the quiz manually (less magic but totally legit).
/**
* #Route("/some-route/{id}", name="some_route_name")
*/
public function creation_questions(Request $request, int $id)
{
$entityManager = $this->getDoctrine()->getManager();
$quiz = $entityManager->getRepository(Quiz::class)->find($id);
$question = new Questions();
$formQuestions = $this->createForm(QuestionType::class, $question);
$formQuestions->handleRequest($request);
if ($formQuestions->isSubmitted() && $formQuestions->isValid()) {
$question->setCreatedAt(new DateTimeImmutable());
$question->setQuiz($quiz);
$entityManager->persist($question);
$entityManager->flush();
return $this->redirectToRoute('home');
}
return $this->render('questions/questions.html.twig', [
'formQuestion' => $formQuestions->createView()
]);
}
I am trying to make a simple CSV uploader with contacts and make them as array using Symfony serializer/CSV encoder. The problem is that when i get data from csv and i dump it i get everything fine i think. But when i want to loop over the array to echo email field or try to create new Objects and save them to database i get an error that index 'Email Address' is undefined. How that can be possible, if when i var_dump in a loop and die after first array on the list i see that 'Email Address' field exists.
Link to image - https://imgur.com/a/7bSJT0z
/**
* #Route("/upload-csv", name="upload")
*/
public function uploadCsv(Request $request)
{
$form = $this->createForm(ContactType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$em = $this->getDoctrine()->getManager();
$data = $form->getData();
$file = $data->getCsv();
//dump($file);
$serializer = $this->container->get('serializer');
$cons = $serializer->decode(file_get_contents($file), 'csv');
foreach ($cons as $con)
{
$contact = new Contact();
$contact->setEmail($con['Email Address']);
$contact->setFirstName($con['First Name']);
$contact->setLastName($con['Last Name']);
$contact->setCountry($data->getCountry());
$em->persist($contact);
}
$em->flush();
}
return $this->render('base.html.twig', [
'form' => $form->createView()
]);
}
How to retrive values of posted form, for example in controller i check if is any username already if it redirect back to route which render the form, but how to retrive the last post values to not fill data of this form again.
example of controle:
/**
* #Route("/dystrybutor/pracownicy/add", name="dystrybutor_pracownicy_add")
*/
public function new(UserManagerInterface $userManager, EntityManagerInterface $entityManager, Request $request)
{
$pracownik = new Pracownik();
$form = $this->createForm(PracownikType::class, $pracownik);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$id = $this->getUser()->getDystrybutorId();
$username = $form["username"]->getData();
$password = $form["password"]->getData();
$email = $form["email"]->getData();
$userManager = $this->get('fos_user.user_manager');
$checkUser = $userManager->findUserByUsername($username);
if($checkUser) {
$this->addFlash(
'danger',
'Login jest już zajęty!'
);
return $this->redirectToRoute('dystrybutor_pracownicy_add');
}
else {
Generally you should just pass the $pracownik object to the action where you redirect to and then just pass it as argument when creating your form. This can be done with a lot of ways but I would suggest to use the forward method in your controller:
public function new(UserManagerInterface $userManager, EntityManagerInterface $entityManager, Request $request, Pracownik $pracownik = null){
$pracownik = $pracownik ?? new Pracownik();
$form = $this->createForm(PracownikType::class, $pracownik);
...
if($checkUser) {
$this->addFlash('danger','Login jest już zajęty!');
return $this->forward('App\Controller\DystrybutorController::new', array(
'pracownik' => $pracownik
));
}
Im creating a simple user class
- User -> entity
- Address -> entity
When a user got created i create a address record in my db.
Now when a user gets edited and changed his addres :
If the address exist he need to take that existing address
if the address not exist Symfony needs to create a new one and use the new address.
Atm I can create users and their address, but when I edit a users address:
The current existing adress get overwrited instead of creating a new one.
Maybe i missed some logic or am i doing it wrong.
here's my code :
public function editAction(Request $request,Users $user)
{
$form = $this->createForm(UserForm::class, $user);
if ($request->getMethod() == 'POST') {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$form = $form->getData();
$this->tryEditAction($user, $form);
return $this->redirectToRoute('admin_userslist');
}
}
$label = "Gebruiker aanpassen";
return $this->render('#ProjectUser/backend/edit.html.twig', array(
'form' => $form->createView(),
'user' => $user,
'label' => $label,
));
}
And here is the TryEditAction :
public function tryEditAction($user, $form)
{
$formAddress = $form->getAddress();
$formAddressStreet = $formAddress->getStreet();
$formAddressStreetNr = $formAddress->getStreetNr();
$formAddressStreetBus = $formAddress->getStreetBus();
$entityManager = $this->getDoctrine()->getManager();
//***
// Getting the entitymanager to get all addresses stored in our db
// Check if this address exist, so we change or edit the address accordingly to the user
//**
$address = $entityManager->getRepository('ProjectLocationBundle:Address')
->findOneBy(
array(
'street' => $formAddressStreet,
'street_nr' => $formAddressStreetNr,
'street_bus' => $formAddressStreetBus
)
);
if($address):
$foundAddress = $address;
$user->setAddress($foundAddress);
$foundAddress->setUser($user);
$entityManager->persist($foundAddress);
else:
$newAddress = new Address();
$newAddress = $formAddress;
$entityManager->persist($newAddress);
$entityManager->flush($newAddress);
$user->setAddress($newAddress);
endif;
// dump($user); die;
$userName = $user->getUsername();
$slug = $this->slugify($userName);
$user->setSlug($slug);
$entityManager->persist($user);
$entityManager->flush();
return $user;
}
I'm using Symfony2 with FOSUserBundle, the problem I have encountered was in editing a user account, when I tried to edit a specific user account, the retrieved user info is correct but when I tried to update the retrieved user info, the currently logged account would be the one being edited not the retrieved user account, how is it possible? What's wrong with my code?
ProfileController :
//edit user
public function editUserAction($id, Request $request)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('MatrixUserBundle:User')->find($id);
if (!is_object($user)) {
throw new AccessDeniedException('This user does not have access to this section.');
}
/** #var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$formFactory = $this->get('fos_user.profile.form.factory');
$form = $formFactory->createForm();
$form->setData($user);
$form->handleRequest($request);
if ($form->isValid()) {
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
$userManager->updateUser($user);
$session = $this->getRequest()->getSession();
$session->getFlashBag()->add('message', 'Successfully updated');
$url = $this->generateUrl('matrix_edi_viewUser');
$response = new RedirectResponse($url);
}
return $this->render('FOSUserBundle:Profile:edit.html.twig', array(
'form' => $form->createView()
));
}
After the given user is correctly updated, you are returning a redirection to a custom route.
I guess the route matrix_edi_viewUser is an override of the original FOSUB\ProfileController::showAction.
Also, you have to create a specific showUserAction and pass it the updated user as argument.
The following code should works :
public function showUserAction($id)
{
$user = $em->getDoctrine()
->getManager()
->getRepository('MatrixUserBundle:User')
->find($id);
if (!is_object($user)) {
throw new AccessDeniedException('This user does not have access to this section.');
}
return $this->render('FOSUserBundle:Profile:show.html.twig', array('user' => $user));
}
The route :
matrix_edi_viewUser:
path: /users/{id}/show
defaults: { _controller: MatrixUserBundle:Profile:showUser }
And in your editAction, change your redirection to :
$url = $this->generateUrl('matrix_edi_viewUser', array('id' => $user->getId());
$response = new RedirectResponse($url);
Now, the user informations displayed in show will be the informations of the updated user.