Symfony PUT method - php

I want send data via PUT method, my controller action:
public function updateTestAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$progress = $em->getRepository('CodeCatsPanelBundle:Progress')->find(5);
//$form = $this->createForm(new ProgressType(), $progress, array('method' => 'PUT'))->add('submit', 'submit');
$form = $this->createForm(new ProgressType(), $progress)->add('submit', 'submit');
$form->handleRequest($request);
return $this->render('CodeCatsPanelBundle:Progress:test.html.twig', [
'form' => $form->createView(),
'valid' => $form->isValid(),
'progress' => $progress,
'request' => $request
]);
}
the first one form works correct, but when I change method to PUT I receive validation error:
This form should not contain extra fields.
I know that Symfony2 use post and extra hidden field _method but how to valid data in this case?

just add a hidden input in your template like:
<form action='your route'>
<input type='hidden' name='_method' value='PUT'>
//do something.......
</form>
in your action:
public function updateTestAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$progress = $em->getRepository('CodeCatsPanelBundle:Progress')->find(5);
$form = $this->createForm(new ProgressType(), $progress)->add('submit', 'submit');
$form->handleRequest($request);
if ($form->isValid()){
//do something
}
return $this->render('CodeCatsPanelBundle:Progress:test.html.twig', [
'form' => $form->createView(),
'valid' => $form->isValid(),//you need this?
'progress' => $progress,
'request' => $request
]);
}
in your route config file:
yourRouteName:
path: /path
defaults: { _controller: yourBundle:XX:updateTest }
requirements:
_method: [PUT]

Most browsers do not support sending PUT and DELETE requests via the
method attribute in an HTML form.
Fortunately, Symfony provides you with a simple way of working around
this limitation.
Symfony 3
Enable http-method-override
In web/app.php:
Request::enableHttpMethodParameterOverride(); // add this line
Choose one of the following override:
In a Twig Template
{# app/Resources/views/default/new.html.twig #}
{{ form_start(form, {'action': path('target_route'), 'method': 'GET'}) }}
In a Form
form = $this->createForm(new TaskType(), $task, array(
'action' => $this->generateUrl('target_route'),
'method' => 'GET',
));
In a Controller / the lazy way
$form = $this->createFormBuilder($task)
->setAction($this->generateUrl('target_route'))
->setMethod('GET')
->add('task', 'text')
->add('dueDate', 'date')
->add('save', 'submit')
->getForm();
Post-Symfony 2.2
Same as above, just Step 2, Step 1 is done by default.
Pre-Symfony 2.2
Same as above, Step 1 and 2.
References
Faking the method with _method
Changing the action and methods in a form
Symfony configuration with http-method-override

Related

What should I pass to handleRequest class of symfony?

I am using this twig and standalone symfony form and validator component:
use Symfony\Component\Validator\Constraints as Assert;
// other use lines ommitted to shorten the code.
$defaultFormTheme = 'bootstrap_4_horizontal_layout.html.twig';
$csrfGenerator = new UriSafeTokenGenerator();
$csrfStorage = new NativeSessionTokenStorage();
$csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);
$formEngine = new TwigRendererEngine([$defaultFormTheme], $twig);
$twig->addRuntimeLoader(new FactoryRuntimeLoader([
FormRenderer::class => function () use ($formEngine, $csrfManager) {
return new FormRenderer($formEngine, $csrfManager);
},
]));
$twig->addExtension(new FormExtension());
$translator = new Translator('fr_FR');
$translator->addLoader('php', new \Symfony\Component\Translation\Loader\PhpFileLoader());
$translator->addResource('php', ROOT.'/translations/messages.fr.php', 'fr_FR');
$twig->addExtension(new TranslationExtension($translator));
$validator = Validation::createValidator();
$formFactory = Forms::createFormFactoryBuilder()
->addExtension(new CsrfExtension($csrfManager))
->addExtension(new ValidatorExtension($validator))
->getFormFactory();
$form = $formFactory->createBuilder(FormType::class, null, ['csrf_protection' => false])
->add('firstnameEn', TextType::class, [
'constraints' => [new Assert\Length(['min' => 3])]
])
->add('lastnameEn', TextType::class)
->add('email', EmailType::class)
->add('birthDate', TextType::class)
->add('password', PasswordType::class)
->add('applyCard', CheckboxType::class)
->add('showPhoto', CheckboxType::class)
->add('privacyRead', CheckboxType::class)
->getForm();
$request = Request::createFromGlobals();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$errors = $form->getErrors();
var_dump($errors);
$data = $form->getErrors();
var_dump($data);
print("debug pring");
} else {
$errors = $form->getErrors();
var_dump($errors);
$data = $form->getErrors();
var_dump($data);
print("debug pring");
}
echo $twig->render('signup.html',
['form' => $form->createView(),
'title' => 'title',
]);
I am getting
Expected argument of type "null", "Symfony\Component\HttpFoundation\Request" given
that is because of
$form->handleRequest($request);
Why am I getting this error and how to fix it? when I use just
$form->handleRequest();
it works, but of course then form validation is not working. How to fix it? What should I pass to its constructor? I I didn't want to use its isSubmitted() if clause and had no need to validate it and I wanted to use just to output the form it was working fine. The problem appeared when I wanted to use HTTFoundation to use isSubmitted if clause. What should I do?
The Form component uses request handlers (symfony docs) to handle requests in the handleRequest() method. From the linked documentation:
To process form data, you'll need to call the handleRequest() method:
$form->handleRequest();
Behind the scenes, this uses a NativeRequestHandler object to read data off of the correct PHP superglobals (i.e. $_POST or $_GET) based on the HTTP method configured on the form (POST is default).
If you want to use the Request object from the HttpFoundation, you might want to configure the Form component to us the HttpFoundationRequestHandler instead. In that case, you have to pass the $request argument to the handleRequest() method.

Symfony 3.4 - how are forms whose actions point to a different controller handled?

I want to process a form in a separate controller. While the Symfony docs show how to change a form's action and method, they don't show how the controller selected in $form->setAction() is actually supposed to handle the form. Is it present in Request? Do we make another Form object so we can check $form->isSubmitted() and $form->isValid()?
It's a pretty glaring omission.
Here is a quick example:
Controller for displaying the form
/**
* #route("/form", name="form_route")
*/
public function formAction()
{
$form = $this->createFormBuilder()
->setAction($this->generateUrl('task_route'))
->setMethod('POST')
->add('task', TextType::class)
->add('dueDate', DateType::class)
->add('save', SubmitType::class)
->getForm();
return $this->render('form.html.twig', [
'form' => $form->createView(),
]);
}
Controller to handle submission
Is it present in Request?
Yes, the form data is in the request.
Do we make another Form object so we can check $form->isSubmitted() and $form->isValid()?
The form has to be recreated so that you can handle and validate the request.
/**
* #route("/task", name="task_route")
*/
public function postAction(Request $request)
{
$form = $this->createFormBuilder()
->add('task', TextType::class)
->add('dueDate', DateType::class)
->add('save', SubmitType::class)
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()){
$task = $form->getData();
/* ... */
}
//render task to view submission
return $this->render('task.html.twig', [
'task' => $task,
]);
}
This does have some duplicate code even when using entities and Symfony's Form Classes, which is why Symfony Docs recommends using the same controller for processing forms.

How to get user ID (FOSUserBundle) in form builder in Symfony2?

I'm quite new here, be patient, please.
I'm trying to make notice board project in Symfony2 using FOSUserBundle.
I try to get logged user id to put it into form created with form builder (and then to MySQL database).
One of attempts is:
public function createNoticeAction(Request $request)
{
$notice = new Notice();
$form = $this->createFormBuilder($notice)
->add("content", "text")
->add("user_id","entity",
array("class"=>"FOS/UserBundle/FOSUserBundle:", "choice_label"=>"id"))
->add("isActive", "true")
->add("category", "entity",
array("class" => "AppBundle:Category", "choice_label" => "name"))
->add("save", "submit", array("label" => "Save"))
->getForm();
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
$em->persist($notice);
$em->flush();
return $this->redirectToRoute('app_user_showuserpage');
}
I tried many solutions again and again and I get some error.
You already have the user object Symfony > 2.1.x
In you Controller like this:
$userId = $this->getUser()->getId();
...
$notice->setUserId($userId);
$em->persist($notice);
Don't ->add field in you FormBuilder, its not safely. Set this value in you Controller and don't ->add this field in FormBuilder
for symfony 3.2.13
have excelent solution (just because is working, but is dangerous if someone discover it in pure HTML)
1) first build YourFormType class.
add normal field in Forms/YourFormType.php (if not, formbuilder tell you that you passing smth not quite right (too many fields) ; -) )
$builder
->add(
'MyModelAddedById',
HiddenType::class,
[
'label' => 'echhh', //somehow it has to be here
'attr' => ['style' => 'display:none'], //somehow it has to be here
]
);
2) in your controller
public function addSomethingAction(Request $request){
$form = $this->createForm(MyModelFormType::class);
//set field value
$request->request->set("prodModelAddedById", $this->getUser()->getId());
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$product = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($product);
$em->flush();
$this->addFlash('success', 'record was added');
return $this->redirectToRoute('products');
}
return $this->render(
'default.add.form.html.twig',
[
'newprod' => $form->createView(),
]
);
}
explenation:
you are passing a field and variable to formbuilder (settig it already to default value!)
and important thing, becose of BUG in my opinion - you can't in your form type set method:
public function getBlockPrefix()
{
//return 'app_bundle_my_form_type';
}
because
$request->request->set
can't work properly if your POST data from form are in bag (parameterbag)
no entity managers, no services, no listeners...
hope it helps.

Form Symfony 2.3 subscription

I am doing a form with Symfony 2.3 to suscribe to a newsletter.
The form is working good in is own template (newsletter.html.twig).
My controller action:
public function newsletterAction(Request $request)
{
$newsletter = new Newsletter();
$form = $this->createFormBuilder($newsletter)
->add('email', 'email')
->add('submit', 'submit')
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($newsletter);
$em->flush();
$request->getSession()->getFlashBag()->add('notice', 'Vous venez de vous enregistré à la Newsletter d\'Emoovio.');
}
return $this->render('MyBundle:Global:newsletter.html.twig', array(
'form' => $form->createView(),
));
}
My template where it's working (newsletter.html.twig) :
{{ form(form) }}
My template where it does not work (index.html.twig):
////
{% render (controller("EmooviofrontBundle:Global:newsletter")) %}
////
The form is display but it's not working. May be is miss something. Has anyone had the same problem and could explain me. Thank you.
I think that when you submit your form, the POST data arrives in the indexAction. This action does not validate your form and renders the normal page. While rendering it will call the Global:newsletterAction but just as a sub request in the GET method without form data.
You could try to apply an action to your formdata
$form = $this->createFormBuilder($newsletter, array(
'action' => $this->generateUrl('global_newsletter'),
'method' => 'POST',
))
->add('email', 'email')
->add('submit', 'submit')
->getForm();

Symfony 2 - Layout embed "no entity/class form" validation isn't working

I'm developing a blog in symfony and i'm stuck with forms that are embed inside the layout. In my case a simple search form.
<div class="b-header-block m-search">
{{ render(controller('YagoQuinoySimpleBlogBundle:Blog:searchArticles')) }}
</div>
To render the form i'm using an embed controller inside the layout twig file.
public function searchArticlesAction(Request $request)
{
$form = $this->createForm(new SearchArticlesType());
$form->handleRequest($request);
if ($form->isValid()) {
// Do stuff here
}
return $this->render('YagoQuinoySimpleBlogBundle:Blog:searchArticles.html.twig', array(
'form' => $form->createView()
));
}
The indexAction is the one that retrieves the form data and filters a list of articles.
public function indexAction(Request $request)
{
$form = $this->createForm(new SearchArticlesType());
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
$criteria = array(
'title' => $data['search']
);
} else {
$criteria = array();
}
$articles = $this->getDoctrine()->getRepository('YagoQuinoySimpleBlogBundle:Article')->findBy($criteria, array(
'createDateTime' => 'DESC'
), 5);
return $this->render('YagoQuinoySimpleBlogBundle:Blog:index.html.twig', array('articles' => $articles));
}
SearchArticlesType is a form class
class SearchArticlesType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('search', 'text', array(
'constraints' => new NotBlank()
))
->add('submit', 'submit', array(
'label' => 'Buscar'
));
}
public function getName()
{
return 'searchArticles';
}
}
The problem comes when i submit this form. The indexAction do his part, validating the form and filtering the articles but when the embed controller tries to validate data (just for displaying info or whatever)
$form->handleRequest($request);
if ($form->isValid()) {
// Do stuff here
}
I feel like i'm missing something.
Thank you for your help!
When you call render(controller('your_route')) you are actually making a sub request which means the parameters bags are emptied so your request isn't "handled" by the form.
If you are using 2.4+ you could get the master request from the request stack using ..
/** #var \Symfony\Component\HttpFoundation\RequestStack $requestStack */
$requestStack = $this->get('request_stack');
$masterRequest = $requestStack->getMasterRequest();
And then you could handle that request in your rendered controller as opposed to the current (sub) request like..
$form->handleRequest($masterRequest);
In your: public function searchArticlesAction(Request $request) you're missing second argument on create form
$searchArticle = new SearchArticle(); // I assume this is how you named the Entity, if not just change the entity name
$form = $this->createForm(new SearchArticlesType(), $article);

Categories