I'm trying to create a function that gives the opportunity for every user to send an email for another user. This is the basic controller of Swiftmailer:
public function contactAction($id)
{
$enquiry = new Enquiry();
$form = $this->createForm(new EnquiryType(), $enquiry);
$from=$this->container->get('security.context')->getToken()->getUser()->getemail();
$em=$this->getDoctrine()->getManager();
$user=$em->getRepository('PfeUserBundle:User')->findBy(array('id'=>$id));
$request = $this->getRequest();
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
$message = \Swift_Message::newInstance()
->setSubject('Intello')
->setFrom($from)
->setTo($user->getemail())
->setBody($this->renderView('PfeUserBundle:Contact:contactEmail.txt.twig', array('enquiry' => $enquiry)));
$this->get('mailer')->send($message);
$this->get('session')->getFlashBag()->add('blogger-notice','Ton message a été envoyé avec succès');
// Redirect - This is important to prevent users re-posting
// the form if they refresh the page
return $this->redirect($this->generateUrl('pfe_intello_contact_mail'));
}
}
i have this error
Error: Call to a member function getemail() on a non-object
$user isn't an object because you are getting an array.
Change:
$user=$em->getRepository('PfeUserBundle:User')->findBy(array('id'=>$id));
Into:
$user=$em->getRepository('PfeUserBundle:User')->findOneBy(array('id'=>$id));
Related
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 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
));
}
I have an error trying to use SwiftMailer with Symfony.
I'm following a tutorial from here: http://symblog.site90.net/docs/validators-and-forms.html
The error code is:
FatalErrorException: Error: Call to undefined method Swift_Message::setMessage() in C:\xampp\htdocs\TP\src\TP\MainBundle\Controller\DefaultController.php line 327
My action is:
public function newAction()
{
$contacto = new Contacto();
$form = $this->createForm(new ContactoType(), $contacto);
$request = $this->getRequest();
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
$message = \Swift_Message::newInstance()
->setFrom('enquiries#myweb.com.ar')
->setTo($this->container->getParameter('tp_main.emails.contact_email'))
//this is the line 327 related with the error
->setMessage($this->renderView('TPMainBundle:Default:contactEmail.txt.twig', array('contacto' => $contacto)));
//
$this->get('mailer')->send($message);
$this->get('session')->setFlash('blogger-notice', 'Your contact enquiry was successfully sent. Thank you!');
return $this->redirect($this->generateUrl('contacto_new'));
}
}
return $this->render('TPMainBundle:Default:contact.html.twig', array(
'form' => $form->createView(),));}
The error says it's undefined but,
my method setMessage() is defined in my class Contacto.php with getter and setter :
/**
* #var string
*
* #ORM\Column(name="message", type="text")
*/
private $message;
/**
* Set message
*
* #param string $message
* #return Contacto
*/
public function setMessage($message)
{
$this->message = $message;
return $this;
}
/**
* Get message
*
* #return string
*/
public function getMessage()
{
return $this->message;
}
According on what I read trying to solve it myself, could the problem be related to the versions of SwiftMailer ?
Thanks
The method "setMessage" refers indeed to your Contacto entity, but to set the content of a message with SwiftMailer, you have to use setBody();
Example :
$mail = \Swift_Message::newInstance();
$mail->setFrom('me#mail.com')
->setTo('you#mail.com')
->setSubject('Email subject')
->setBody('email body, can be swift template')
->setContentType('text/html');
$this->get('mailer')->send($mail);
EDIT : save the email content in database and send it to Twig template
I added a bit of code in your function, to actually save the email content in database. It's not mandatory but I imagine you'll want to retrieve this information later in your application. Anyway, I didn't test this, but it should work : your controller set the SwiftMailer message body as a Twig template. Your template should be able to parse the "contacto" entity.
public function newAction()
{
$contacto = new Contacto();
$form = $this->createForm(new ContactoType(), $contacto);
$request = $this->getRequest();
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
// set your "contacto" entity
$contacto->setMessage($form->get('message')->getData());
// do the rest of $contact->set{......}
// save the message in database (if you need to but I would do it)
$em = $this->getDoctrine()->getManager();
$em->persist($contacto);
$em->flush();
// SEND THE EMAIL
$message = \Swift_Message::newInstance();
$message->setFrom('enquiries#myweb.com.ar')
->setTo($this->container->getParameter('tp_main.emails.contact_email'))
->setSubject('YOUR SUBJECT')
->setBody($this->renderView('TPMainBundle:Default:contactEmail.txt.twig', array('contacto' => $contacto)))
->setContentType('text/html');
$this->get('mailer')->send($message);
$this->get('session')->setFlash('blogger-notice', 'Your contact enquiry was successfully sent. Thank you!');
return $this->redirect($this->generateUrl('contacto_new'));
}
}
return $this->render('TPMainBundle:Default:contact.html.twig', array('form' => $form->createView()));
}
I trying to send contact form in Symfony2, but i have the error:
Variable "form" does not exist in VputiMainBundle:Main:contact.html.twig at line 20
Here is my controller:
public function contactAction(Request $request)
{
$form = $this->createForm(new ContactType());
$formView = $form->createView();
$form->handleRequest($request);
if ($form->isValid()) {
$message = \Swift_Message::newInstance()
->setSubject($form->get('subject')->getData())
->setFrom($form->get('email')->getData())
->setTo('mail.com.deu')
->setBody(
$this->renderView(
'VputiMainBundle:Main:contact.html.twig',
array(
'ip' => $request->getClientIp(),
'name' => $form->get('name')->getData(),
'message' => $form->get('body')->getData()
)
)
);
if ($this->get('mailer')->send($message)) {
$this->get('session')->getFlashBag()->add('message_send', 'thanks!');
} else {
$this->get('session')->getFlashBag()->add('send_error', 'error!');
}
}
return $this->render('VputiMainBundle:Main:contact.html.twig', array('form' => $formView));
}
Where is my problem, what I doing wrong?
You are using the same template both for showing the form to send a contact request and the body of the mail. Notice the two VputiMainBundle:Main:contact.html.twig. If the form is valid it tries to render contact.html.twig which needs a form variable obviously.
Create a new template for the mail body which does not rely on the form view.
I have an issue where I have a form type that persists the associated entity even when the form is not valid.
I have confirmed that the form indeed has errors via $form->getErrorsAsString(). I have also confirmed that the logical if statement that checks if the form is valid or not comes out false. The entity still persists despite the fact that the form is never valid.
I'm not sure what I'm doing wrong here as I have no other spot that I can find that either persists the entity or flushes the entity manager. Here's my controller:
/**
* #Route("/settings/profile", name="settings_profile")
* #Template();
*/
public function profileAction()
{
$user = $this->getUser();
$profile = $user->getUserProfile();
if (null === $profile) {
$profile = new UserProfile();
$profile->setUser($user);
$profileDataModel = $profile;
} else {
$profileDataModel = $this->getDoctrine()->getManager()->find('MyAppBundle:UserProfile',$profile->getId());
}
$form = $this->createForm(new ProfileType(),$profileDataModel);
$request = $this->getRequest();
if ($request->getMethod() === 'POST') {
$form->bind($request);
if ($form->isValid()) {
// This logic never gets executed!
$em = $this->getDoctrine()->getManager();
$profile = $form->getData();
$em->persist($profile);
$em->flush();
$this->get('session')->setFlash('profile_saved', 'Your profile was saved.');
return $this->redirect($this->generateUrl('settings_profile'));
}
}
return array(
'form' => $form->createView(),
);
}
I must have a listener or something somewhere that is persisting the user.
My work around for this temporarily is to do:
$em = $this->getDoctrine()->getManager()
if ($form->isValid()) {
// persist
} else {
$em->clear();
}
Until I can ferret out what listener or other data transformer is causing this.