I've got problem with Symfony and I hope you would help me :)
I created a Form, which takes data from user (email, name, message) and then it saves data in database. Everything works fine but i also want to send e-mail with this data.
I want to use mail function mail(to,subject,message,headers,parameters);.
My Controller class looks like:
public function ContactFormAction(Request $request){
$post = new ContactForm();
$form = $this->createFormBuilder($post)
->setMethod('POST')
->add('email','text',['label' => 'Adres e-mail'])
->add('name','text', ['label' => 'Imię'])
->add('message','text', ['label' => 'Wiadomość'])
->add('save','submit', ['label' => 'Wyślij'])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted()) {
$post = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
$message=''; //thats my problem
mail('example#example.pl', 'Subject', $message);
return $this->redirectToRoute('onas');
}
return $this->render('default/aboutus.html.twig', ['form' => $form->createView()]);
}
My Problem is: how should the $message variable looks like if I want to get this data from user (from a form on my webpage).
Thanks a lot for all your answers :)
Not sure that I follow, but, you want to send plain text using user's input just do $message = $post->getMessage(); and pass it on to mail. Is that the issue?
E-mail are, by default, sent in text/plain encoding, so you won't be able to use HTML. Personally, I prefer to format it a little better than old-plain-text. To achieve this, I usually create a Twig template, pass the input data to it and render what I need. That template could contain some HTML which could enhance the email's visual look.
Related
Since 3 weeks i try to learn php with the symfony framework.
I want to build an application with which i can track my expanses.
I made good progress but since 2 days i have a little logic problem so maybe someone can help me here.
I want to make a dashboard.(the main side of the project) There the user can monitor the expenditures.
This works. Now i want also a form at the dashboard, so the user can add new expenditures. I already implement a form but with a extra route. So in my ExpenditureController i have the functions dashboard and the function addExpenditure which generate different twig.html templates.
So the user can monitor his expenditures with ...budgetapp/expenditure/dashboard
and he can add new Expenditure with ...budgetapp/expenditure/addexpenditure
My Dashboard-Function
#[Route('/dashboard/', name: 'dashboard')]
public function dashboard(ExpenditureRepository $ar)
{
$user = $this->getUser();
$expenditures = $ar-> findexpendituresOfUser($user);
return $this->render('expenditure/dashboard.html.twig', [
'expenditures' => $expenditures,
]);
}
The expenditure/dashboard.html.twig shows the Expentiures of the current user in a table
My addExpenditure-Function
public function addExpenditure (ManagerRegistry $doctrine, Request $request){
$em = $doctrine->getManager();
$expenditure = new Expenditure();
$form = $this->createForm(ExpenditureType::class, $Expenditure);
$form->handleRequest($request);
if($form->isSubmitted()){
$em->persist($expenditure);
$em->flush();
}
return $this->render('expenditure/addexpenditure.html.twig', [
'addexpenditureForm' => $form->createView()
]);
}
The expenditure/addexpenditure.html.twig looks like this:
{% block body %}
<div class="container">
{{form(eintragenForm)}}
</div>
{% endblock %}
My problem /mistake in thinking:
How can i implement the form to the dashboard? So of course i can take the code from the addexpenditure function and put it 1:1 in the dashboard-funciton. but i dont think this is the right way? I also tried to including template fragments with the offical Embedding Controllers Documentation of Symfony, but this also dont work.
So someone can help me with a suggestion how you would handle this in your project?
Best regards
Markus
There are two possible solutions: put both view and add logic inside one controller's action, or separate them. Since you probably have some validation, it's reasonable to have both add and view code inside one action (otherwise, you'll have to pass errors via sessions, which is not very pretty). So basically, your dashboard/add action will look like this:
#[Route('/dashboard/', name: 'dashboard')]
public function dashboard(Request $request, ExpenditureRepository $ar, ManagerRegistry $doctrine)
{
$expenditure = new Expenditure();
$form = $this->createForm(ExpenditureType::class, $expenditure);
if ($request->isMethod('POST')) {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $doctrine->getManager();
$em->persist($expenditure);
$em->flush();
return $this->redirectToRoute('dashboard');
}
}
$user = $this->getUser();
$expenditures = $ar-> findexpendituresOfUser($user);
return $this->render(
'expenditure/dashboard.html.twig',
[
'expenditures' => $expenditures,
'addexpenditureForm' => $form->createView(),
]
);
}
What's happening here:
First you check if POST http method was used, if it was - it means
that form has been submitted and you can handle it. There is an alternative solution without checking request method, see comments for more.
If this is a GET request, just show ordinary dashboard
If the form is submitted and it's valid - save data and redirect to
the same page. Otherwise, you'll need to empty all submitted data
from the form, etc. (it's not the right way to do it)
If the form is invalid, do not redirect, just render the page
normally, and all errors will be shown.
Finally, you of course have to render the form on your dashboard.html.twig like you did: {{form(eintragenForm)}}
I have simple html form and controller to handle it. Notice I'm not using Symfony's forms in html.twig like {{form_start(form)}} .... So I want to handle from simple html forms in Controller.
My request body is contains below
+request: Symfony\Component\HttpFoundation\ParameterBag {#10
#parameters: array:2 [
"name" => "name"
"amount" => "name"
]
}
and in Controller.php I have $form
$defaultData = ['message' => 'Type your message here'];
$form = $this->createFormBuilder($defaultData)
->add('name')
->add('amount')
->getForm();
//here I can't handle the request;
$form->handleRequest($request);
// only 'message' is contain
dd($form->getData());
How to Use a Form without a Data Class From documentation I tried to handle request from html form without using $data = $request->request->get('data')
After all my tried to handle and asking in every Symfony forums, I founded this problem,
My mistake was just specify my requests parameters.
First I need to find out what is the name of my $form To solve this I dumped my $form that just created
dd($form);
[![enter image description here][1]][1]
After that my request should look like below
And after that I can handleRequest()!
I have few cases where I need to ugly customizing of my FormType classes.
First one is that I need to check if the state of user is active in this case disable possibility to edit username. But just adding disabled atribute is not protecting input to be not submitted. So I decided not to show username input field. I achieved it by passing boolean through options.
Controller:
$userForm = $this->createForm(UserType::class, $user, array(
'is_active' => ($user->getState() == 'active')
));
And then in UserType class:
if ($options['is_active']) {
$builder
->add('username', EmailType::class);
}
$builder
->add('firstName', TextType::class),
...
Second case is that I need to remove NotBlank() constraint and add 'required' => false attribute from FileType field when profile photo is uploaded. I achieved it in similar way by passing boolean through options.
Controller:
$userForm = $this->createForm(UserType::class, $user, array(
'is_uploaded' => !empty($photo)
));
UserType class:
// achieved same way as previous problem
My questions would be:
What recommendations would be dealing with these kind of cases?
Is what I did correct and acceptable?
Is there a documentation or examples dealing with any of these cases?
You can move all this form configuration's logic into the form class.
Since you pass $user entity into the form with:
$userForm = $this->createForm(UserType::class, $user, array( // <- $user is passed
'is_uploaded' => !empty($photo)
));
You can access it in builForm method with:
$user = $builder->getData();
Then you can verify all the condifions inside the form and there's no need for making mess in controller.
I'm having a problem when trying to compare a data database, with data input by form.
I have a "pedido", this has many "items". I need compare "item" by "item" if this is modifies in the form.
Then I need get original data from database and data modified from form.
The problem is when i try get original data from database.
Always get the data modified by form.
How Can i get the original data from database after the submit the form?
NOTE: i have tried get PedidoAuxiliar before and after HandleRequest.This doesn´t work!
UPDATE CODE: Input how compare the items
This is my controller editAction:
public function editarAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$pedido = $em->getRepository('PedidosBundle:Pedido')->find($id);
//$pedidoAuxiliar = $em->getRepository('PedidosBundle:Pedido')->find($id);
$formulario = $this->createForm(new PedidoType(), $pedido, array(
'action' => $this->generateUrl('my_routing', array('id' => $id)),
'attr' => array(
'novalidate' => 'novalidate'
),
'method' => 'POST',
));
$formulario->handleRequest($request);
if($formulario->isValid()){
$pedidoAuxiliar = $em->getRepository('PedidosBundle:Pedido')->find($id);
foreach($pedido->getArticulos() as $articulo){
foreach($pedidoAuxiliar->getArticulos() as $articuloAuxiliar){
if($articuloAuxiliar->getId() == $articulo->getId()){
if($articuloAuxiliar->getCantidad() == $articulo->getCantidad()){
//Some code...
To get data from db u can use EntityManager::refresh($entity) its overwrite entity data using db. So u must use data from form, not entity to compare.
But u always can ust Doctrine to check changes eg: http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/change-tracking-policies.html
because Doctrine hold info about old and new value, but is not so easy to get (outside listeners)
I have found a solution. I have created a new connection entity manager in my config.yml.
Now I call my entity data from my new entity manager and i get datas from database! Thanks!
In my Symfony2 project, I have a rather classic 1:* relationship with some of my entities (let's call them BlogPost and Comments, even though a NDC prevents me from saying what they really are). I've been tasked with modifying the form that currently exists to edit existing Comments so it can modify certain aspects of the BlogPost as well. I'm not entirely sure how to go about it, specifically with how Symfony2 and Doctrine handle their data binding.
Right now, I populate and bind to the form with (pseudo-code to protect the innocent):
Grab the BlogPost based on the incoming request ID
Grab all Comments related to BlogPost
$form = $this->createForm(new CommentsType(), array('comments' => $comments));
if ($request->getMethod() == "POST")
{
$form->bind($request);
foreach($comments as $comment) {
$doctrine->persist($comment);
}
}
return $this->render('blah.html.twig', array('blog' => $blogPost, 'comments' => $comments, 'form' => $form->createView());
As you can see, I already send the BlogPost to the view. And I know I can add it to the form by including it in my CommentsType class. I'm just not sure how to data bind it all properly.
If you have the $blogPost, just persist it, the same as the comments. Also flush at the end:
$form = $this->createForm(new CommentsType(), array('comments' => $comments));
if ($request->getMethod() == "POST")
{
$form->bind($request);
foreach($comments as $comment) {
$doctrine->persist($comment);
}
$doctrine->persist($blogPost);
$doctrine->flush();
}
return $this->render('blah.html.twig', array('blog' => $blogPost, 'comments' => $comments, 'form' => $form->createView());