How Can I specified the object of my precedent form? - php

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()
]);
}

Related

How I can implement code for card registration with MangoPay API?

I would like to transfer the card details to mangopay
At first, I put the necessary code for the registration provided by the API
public function Registration($user)
{
$CardRegistration = new \MangoPay\CardRegistration();
$CardRegistration->UserId = $user->getIdMangopay();
$CardRegistration->Currency = "EUR";
$CardRegistration->CardType = "CB_VISA_MASTERCARD";
$Result = $Api->CardRegistrations->Create($CardRegistration);
}
then I call this function when submitting my form during a purchase
public function payment(Request $request, ApiUser $ApiUser): Response
{
$payment = new PaymentMethod();
$form = $this->createForm(RegistrationCard::class);
$form->handleRequest($request);
if ($form->isSubmitted()){
$name = $form->get('name')->getData();
$cardnumber = $form->get('cardnumber')->getData();
if($name){
$payment->setName($name);
}
if($cardnumber){
$payment->setCardNumber($cardnumber);
}
$ApiUser->Registration($form);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($payment);
$entityManager->flush();
return $this->redirectToRoute("profil");
}
return $this->render('home/payment.html.twig', [
'controller_name' => 'HomeController',
]);
}

Symfony get users on relation to many to many

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();
...
}
}

How to save data from Postman in Symfony?

I try to send data from Postman to this function
public function new(Request $request): Response
{
$tag = new Tag();
$form = $this->createForm(TagType::class, $tag);
$form->submit($request->request->all());
if ($form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($tag);
$entityManager->flush();
$message = "Tag was successfully added";
return new JsonResponse(array("message: $message"));
}
$errors = $form->getErrors();
return new JsonResponse(array("message:$errors"));
}
If i send data as 'form-data' i can save it to database.
But i can't understand how to accept 'raw' Json 'application/json'
I can only manually take value from Request with
$tagTitle = $request->query->get('title');
And i can't do it with some FOSUserBundle etc.
I can use only jms/serializer. If i will need it.
You need to fetch the json from $request->getContent() first:
public function new(Request $request): Response
{
$tag = new Tag();
$form = $this->createForm(TagType::class, $tag);
$form->submit(json_decode($request->getContent(), true));
if ($form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($tag);
$entityManager->flush();
$message = "Tag was successfully added";
return new JsonResponse(array("message: $message"));
}
$errors = $form->getErrors();
return new JsonResponse(array("message:$errors"));
}

Symfony2: Inserting a collection of files

While trying to insert a collection of entities which have a file field, i couldn't figure out if there's is a better way to create the UploadedFile Object being cast by the Document::document annotation. Here's my code, any help on improving it is very appreciated :)
public function createAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$user = $this->get('security.context')->getToken()->getUser();
$entity = new Paper();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$entity->setAuthor($user);
$em->persist($entity);
// chotest foreach in the universe
if (isset($_FILES) && array_key_exists('arkad1a_cfpbundle_paper', $_FILES)) {
foreach ($_FILES['arkad1a_cfpbundle_paper']['name']['documents'] as $k => $v) {
$document = new UploadedFile(
$_FILES['arkad1a_cfpbundle_paper']['tmp_name']['documents'][$k]['document'],
$_FILES['arkad1a_cfpbundle_paper']['name']['documents'][$k]['document'],
$_FILES['arkad1a_cfpbundle_paper']['type']['documents'][$k]['document'],
$_FILES['arkad1a_cfpbundle_paper']['size']['documents'][$k]['document'],
$_FILES['arkad1a_cfpbundle_paper']['error']['documents'][$k]['document'],
false
);
$Document = new \Arkad1a\CFPBundle\Entity\Document();
$Document->setAuthor($user)
->setDocument($document)
->setPaper($entity)
->upload();
$em->persist($Document);
}
}
$em->flush();
return $this->redirect($this->generateUrl('paper_show', array('id' => $entity->getId())));
} else {
die('invalid');
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}

Symfony2 How to process dynamic embed forms collection?

I try this cookbook about embed form:
http://symfony.com/doc/current/cookbook/form/form_collections.html
But the embed foreign key (task_id field in Tag table) is not save, always NULL
Here the complete code: https://gist.github.com/1755140
Do you know why?
Thank
Edit::
My trouble was in process form action. Like the tag form is embed dynamically, so i don't know how many tag(s) i will have. If i add in createAction
$tag1 = new Tag();
$task->addTags($tag1);
only the first embed form was correctly save! How to save the other tags?
public function createAction(Request $request)
{
$task = new Task();
$tag1 = new Tag();
$task->addTags($tag1);
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
Edit2:
My solution which resolve the trouble, what do you think about it? Better?
public function createAction(Request $request)
{
$task = new Task();
$tasks = $request->request->get('task', array());
if (isset($tasks['tags'])) {
$tags = $tasks['tags'];
foreach($tags as $tag) {
$tag = new Tag();
$task->addTags($tag);
}
}
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
Edit3:
A much better alternative (not tested again)
http://www.siteduzero.com/tutoriel-3-523899-creer-des-formulaires-avec-symfony2.html#ss_part_2
public function createAction(Request $request)
{
$task = new Task();
$form = $this->createForm(new TaskType(), $task);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($task);
foreach($task->getTags() as $tag) {
$em->persist($tag);
}
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
return array(
'form' => $form->createView()
);
}
In TaskController on line 29 try to use $task->addTags($tag1); instead of $task->getTags()->add($tag1);
I don't understand. Is this solution wrong?
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
foreach($task->getTags() as $tag) {
$tag->setTask($task);
}
$em->persist($task);
$em->flush();
return $this->redirect($this->generateUrl('new_task', array('id' => $task->getId())));
}
It works and it seems simpler.

Categories