send in link id of username symfony2 - symfony

want to send an email from my Symfony2 application, this email must contain a link of confirmation and when the user clicks on this link the state of a field in DB to change.
i have this in my controller:
$message = \Swift_Message::newInstance()
->setSubject('demande de conge ')
->setFrom($col->getEmailCollaborateur())
->setTo($form->get("emailcdp")->getData())
->setBody($this->render('AcmeBundle:Conge:demandeCongeNormal.html.twig', array('conge' => $conge, 'id'=> $this->getUser()->getId())))
;
$this->get('mailer')->send($message);
in the twig :
id de collab: {{ id }}
pour confirmer la demande :
{{ url('confirmer_conge' ,{'username': ' id '}) }}
but in the Email i have this :
http://local.symfony2.com/app_dev.php/confirm/?username=+id+
i want to get the id of user that send the message in another controller for update my DB
in my routing.yml:
confirmer_conge:
pattern: /confirm/{username}
defaults: { _controller: acmeBundle:Conge:confirme }
and in the controller i have this function:
public function confirmeAction()
{return $this->render('acmeBundle:Conge:confirmer.html.twig');
}

Remove the quotes from around id, it is a variable.
{{ url('confirmer_conge', {'username': id}) }}
As for accessing the ID in your controller it should work like this:
public function confirmeAction($username)
//...
}

Related

symfony form handling subcontroller

I have a working contactform, which allows the user to send a e-mail to me and additionally gets a confirmation mail.
I would like to add a confirmation message to the page, so the user is sure the message was sent.
default.html.twig
<div>
{% include 'includes/overview.html.twig' %}
{% include 'includes/service.html.twig' %}
{% include 'includes/offer.html.twig' %}
{% include 'includes/aboutus.html.twig' %}
{% include 'Advanced/contactForm.html.twig' %}
</div>
contactForm.html.twig
<div class="col-lg-6 col-md-6 contactfrom nopadding">
{# request has to go further to the contactCormController -> {'request' : app.request} #}
{{ render(controller('AppBundle\\Controller\\ContactFormController::contactForm', {'request' : app.request})) }}
</div>
ContactController.php
public function contactForm(Request $request, \Swift_Mailer $mailer)
{
$contactForm = new ContactForm();
$form = $this->createForm(ContactFormType::class, $contactForm);
$form->handleRequest($request);
if ($form->isSubmitted()){ //&& $form->isValid()
$message = (new \Swift_Message)
->setFrom($contactForm->getEmail())
->setTo('mail')
->setSubject("Kontaktformular - ". $contactForm->getFirstname() ." ". $contactForm->getLastname())
->setBody($contactForm->getMessage())
;
if ($contactForm->getHonigtopfRoboter() == "") {
try {
// Sending message to the Host
// Sending confirmation message to the user
$mailer->send($message);
$this->confirmationMail($mailer, $contactForm->getEmail());
// empty ContactForm
unset($contactForm);
unset($form);
$contactForm = new ContactForm();
$form = $this->createForm(ContactFormType::class, $contactForm);
// add succes flashmessage
// $this->addFlash('success', 'message');
}
catch (\Swift_TransportException $Ste){
//TODO: Exception Handling
//echo $Ste->getMessage();
// add error flashmessage
// $this->addFlash('danger', 'message');
}
}
else{
}
}
$contactFormEntity = $form->getData();
return $this->render('form/contactForm.html.twig',
['contactform' => $form->createView()
]);
}
The most common solution I found was to use "flash message", sadly flash messages only work, if you redirect to a new page. Due to the fact, that my contact form stays on the same page it does not work.
My form is embedded and rendered in a sub-html.twig page, so I have the problem to get the information to my ContentController.php and further to the page.
I am really stuck and don't really know the best workflow for this scenario. How do i handle the submit and:
Success -> empty contact form -> success message on page
Error -> leave contact form -> error message on page
Thanks for your help.
If your form is valid, you should redirect the user after the form submission
public function contactForm(Request $request, \Swift_Mailer $mailer)
{
$form = ...
if ($form->isSubmitted() && $form->isValid()) {
$message = ...
$mailer->send($message);
$this->addFlash('success', 'Wohoo, we got it!');
return $this->redirectToRoute('app_contact_form');
}
return $this->render('form/contactForm.html.twig', ['contactform' => $form->createView()]);
}
Doing this, you don't need to empty the form like you do and then re-create it. And as the user is redirected, he will see the flash message.
Also, always check if the form is valid !

How to generate right route in twig with dynamic sub-domain?

I have a multi-tenant APP based on sub-domain that's working properly but I have an issue with generated link in Twig templates.
All the generated link are on the default sub-domain and not the current one
routes.yaml
app_customer:
resource: '../src/Controller/Customer/'
host: "{subdomain}.domain.com"
defaults:
subdomain: tenant1
requirements:
subdomain: tenant1|tenant2
SecurityController.php
class SecurityController extends AbstractController
{
/**
* #Route("/login", name="app_login", methods={"GET","POST"})
*/
public function login(AuthenticationUtils $authenticationUtils)
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
]);
}
}
login.html.twig
<form action="{{ path('app_login') }}" method="post">...</form>
will always generate https://tenant1.domain.com/login however the current url is tenant2.domain.com
I believe it is always generating https://tenant1.domain.com/login because you have "tenant1" set as the default value for subdomain and you do not pass a different value when you call path()
Try this :
{% set currsubdomain = app.request.getHttpHost()|split('.')|first %}
<form action="{{ path('app_login', {subdomain: currsubdomain }) }}" method="post">...</form>
Or maybe just pass the whole host:
<form action="{{ path('app_login', {host: app.request.getHttpHost}) }}" method="post">...</form>

Symfony Twig: send a set parameter with a form submit request

I have a form in my twig, i want that by clicking on its submit button, another parameter (that i've set in the twig) get sent to the same action that handles the form :
this is the variable i've set
{% set idprof = profil.id %}
I want to send it with the submit request : ( i know this code is false)
{{ form_widget(form.id),{'idprof': idprof} }}
and the action will look like this :
public function gestProfAction(Request $request, $idprof)
{
}
I'm sorry i know this is a stupid question, but I'm still new in symfony, I couldn't find a solution by myself.
Just pass it in the form start line
{{ form_start(form, {'action': path('idprof', { 'idprof': idprof })}) }}
Remember to add the annotation or yaml for the routing
/**
* #Route("/idprof/{idprof}", name="idprof")
*/
public function gestProfAction(Request $request, $idprof)
{
}
For reference:
http://symfony.com/doc/current/forms.html#rendering-the-form
http://symfony.com/doc/current/form/action_method.html
http://symfony.com/doc/current/templating.html#linking-to-pages

Getting value from a twig to a controller

I'm using Symfony2 and my view is a twig/php. Can I get a value from a view? I tried like this:
listcurrency.twig.html:
{% for currency in liste %}
<TR>
<TH> <a href="{{ path('devises_disable', { 'id': currency.id }) }}"> {{currency.id}} </TH>
<TD> {{ currency.Name}} </TD>
<TD> {{currency.Enabled}}</TD>
</TR>
{% endfor %}
I call a route 'devises_disable' and pass a parameter currency.id.
EDIT:this is what i do with the value:
controller:
public function disableAction($id)
{
$em = $this->getDoctrine()->getManager();
$currency = $em->getRepository('DevisesBundle:Currency')->findOneById($id);
if (!$currency) {
throw $this->createNotFoundException(
'Aucun currency trouvée pour cet id : '.$id
);
}
$i=$currency->getEnabled();
if($i==0){$i=1;}else if($i==1){$i=0;}
$currency->setEnabled($i);
$em->flush();
$em->refresh($currency);
}
the route:
devises_disable:
path: /webmaster/listcurrency
defaults: {_controller: DevisesBundle:Default:disable}
the entity i'm trying to update doesn't change.No error message too!!
Try changing your route into :
devises_disable:
path: /webmaster/listcurrency/{id}
defaults: {_controller: DevisesBundle:Default:disable}
For checking the variable success or not passed into your controller put this in top of your controller :
echo 'This is the variable : '.$id;

Swiftmailer//Twig email not rendering correctly

I'm experimenting with symfony2 framework and i'm trying to send emails using swiftmailer and twig. The problem is, with my current implementation, the email is sent in html (you can see the tags, everything).
Here is the controller i'm using:
public function formularioAction()
{
$enquiry = new Enquiry();
$form = $this->createForm(new EnquiryType(), $enquiry);
$request = $this->getRequest();
if($request->getMethod() == 'POST'){
$form->bindRequest($request);
if($form->isValid()){
$message = \Swift_Message::newInstance()
->setSubject('Mail from the App')
->setFrom('no-reply#app.com')
->setTo('******#gmail.com')
->setBody($this->render( 'AcmeDemoBundle:Demo:email.html.twig' ));
$this->get('mailer')->send($message);
//end of mail sending
//redirect - it's important to prevent users from reposting the form if
//they refresh the page
return $this->redirect($this->generateUrl( '_formulario'));
}
}
return $this->render('AcmeDemoBundle:Demo:formulario.html.twig', array('form' => $form->createView()));
}
And the twig template the email is using:
{% extends "AcmeDemoBundle::layout.html.twig" %}
{% block title "Email de teste" %}
{% block content%}
<H1>Este é um render de um email de teste!</H1>
{% endblock%}
What am i doing wrong?
You have to specify the Content-type of the body, by calling the setBody() method like this.
$message->setBody($messageBody, 'text/html');
For more information, see: http://swiftmailer.org/docs/messages.html#setting-the-body-content

Resources