My idea at the moment is to perform the following in my Symfony controller:
dump($request);
/* Some code to handle the request manually */
$form->handleRequest($request);
Will my handleRequest call actually function properly (meaning, populate my User entity as expected), or is dumping a subtractive action that would somehow make the contents of the request no more accessible for the handleRequest function?
Related
I'm pretty new to Laravel. I'm trying to create a form to post to a function in my controller. It works fine, exactly as expected, until I try to add in a custom request validation. As soon as I've added it, if I run the form again I get a MethodNotAllowed error. Can someone tell me what is going wrong?
edit** sorry I forgot to post the code.
The request I made is pretty simple. The authorize is set to return true.
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'campaign_name'=>'required',
'campaign_message'=>'required_without:campaign_link',
];
}
In the controller I'm calling the namespace for the request at the top and have the function using that request. The function works just fine when the regular laravel request is called rather than my custom one.
public function store(CreateCampaignRequest $request)
{
//do code here
}
My form is using this action to send the request.
{!! Form::open(['method'=>'POST',
'action'=>'OrganizationCampaignController#store'])!!}
and the route is set to this
Route::post('dashboard/campaigns/send','OrganizationCampaignController#store');
Like I said everything works when the normal Request is called, it only throws the method not allowed when I try using my custom request.
Thank you!
Problem
It seems like my API-handling controller cannot process an injected Request object. Details below.
I have a route in my api.php routes file:
Route::namespace('Mailing')->prefix('mailing/webhook')->group(function () {
Route::post('open', 'WebhookController#getOpened');
});
In the WebhookController.php, there's a constructor with the injected Request object:
use Illuminate\Http\Request;
public function __construct(Request $request) {
// Log it in the database
Logger::info('constructor called...');
// Filter the input in the injected Request
$this->input = $this->getFilteredInput($request);
}
Now, when I deploy this code to the server and make the API call against my endpoint, the log message at the beginning of the __construct() method is not even fired. I also get no data stored in the database (which should happen if the webhook is correctly processed).
What I tested
However, when I create a dummy route in web.php routes file:
Route::post('open', 'WebhookController#getOpened');
and then create a form and make a POST call to the getOpened() method - all works as expected: I have the Request injected and can manipulate it.
I checked that:
The API endpoint is correct and available
There are no obsolete use statements at the top of the
WebhookController
Questions
Why does the api.php route fail on me? Doesn't Laravel's dependency injection work for API-handling controllers?
I have a form made in Twig and I want to pass the values of this form to my database, so how do I pass the Twig values to the controller?
In the first photo is the form that I created in twig
Formulario twing
In the second picture is the controller (the entities, and the connection with the database with doctrine orm is complete too), it is only necessary to know how to take the form data and to pass to the controller
Controller
When form submits you will get a POST request to the same URL that it was built in.
Stick to this tutorial:
http://symfony.com/doc/current/forms.html
If you create a form with html and not symfony form you must manually handle form and other step.
you must submit your form to you controller route that seems is cadastrarAction().
Don't forget to declare route with POST method for cadastrarAction().
In controller you can access posted data from request argument like this.
use Symfony\Component\HttpFoundation\Request;
class FooController extends Controller {
cadastrarAction(Request $request)
{
// Find what you exactly want. if you want to get query use this
$request->getQueryString()
}
}
This is bad practice that declare form manually. you must use FormType for easily handle and persist form to database. use symfony official site for more information about form and entity.
In official documentation you can find flow, how create entity, form, twig template and set data in database.
If you need get data from form use this:
if ($form->isSubmitted() && $form->isValid()) {
// -------- Hear you take data --------
$ideda = $form->get('ideda')->getData();
$email = $form->get('email')->getData();
$telemovel = $form->get('telemovel')->getData();
// ---------- Hear you set data's ---------
$usuario -> setIdeda($ideda);
$usuario -> setEmail ($email );
$usuario -> setTelemovel($telemovel);
}):
I'm making an Ajax call from a default Blade layout, shared by all the pages. The Ajax call is handled in AjaxController and the controller needs to know "what" is calling it.
Normally, I would do the following to check the current route:
$request->route()->getActionName(); // => e.g. "AjaxController#index"
But how do I retrieve the action name of a page from which the ajax call was made? So:
Ajax call is made from page A to controller X
Controller X checks what the route name of page A is
In the end, I can always pass the caller route name with the Ajax call, but I'm wondering if there's a way to know the caller from within the AjaxController.
I have a cached site which have a form in it which should not be cached. I use ESI for it. When the form is submit I need to get the POST Parameter in my controller. Symfony let me get the Request Parameter 'form' not the real POST Data or is there a good way to get them.
{{ render_esi(controller('MyBundle:Form:staticForm', {'form': 'sidebar'}))}}
Setting them in twig will not work because of Parent Page Cache.
{{ render_esi(controller('MyBundle:Form:staticForm', {'form': 'sidebar', 'request': }))}}
So how to get the post parameter in my controller currently the code shown here only gets me the ESI data:
public function staticFormAction(Request $request) {
// ..
$form->handleRequest($request);// will not work because:
$request->get('firstName'); // is empty when called by ESI
How I can get the Parameters from the Parent Request?
Hacky solution
Currently the only solution I found is for me too hacky
TWIG:
{{ render_esi(controller('ClientWebsiteBundle:Form:staticForm', app.request.request.all|merge({'form': 'sidebar'}), app.request.query.all)) }}
PHP:
$data = ($request->get('myFormName'));
if (count($data)) {
// Forms uses $request->request
$request->request->set('myFormName', $data);
$request->setMethod('POST');
}
Additional
After a little research and look into symfony core code I need to change the ESI to Post so my question is know "How to call ESI as POST method not GET?"
Solution
Using requestStack like Chris Tickner posted seems the post solution.
ESI is an edge-side include, which means it is not designed to handle POST data. By default, reverse proxies like Varnish or Symfony's HttpCache kernel, see the ESI as a URL ("/_proxy?_controller=x¶ms=etc") which they include by GET-ing it from your app. This is why you are finding this difficult.
However, no proxy is going to cache a POST request, so you could, during a POST request, access the master request using the request_stack service.
// if POST
$master_request = $this->get('request_stack')->getMasterRequest();
$form->handleRequest($master_request);
This should do the trick if you are using the Symfony HttpCache.
http://api.symfony.com/2.7/Symfony/Component/HttpFoundation/RequestStack.html
You can get the full form data using
$data = $form->getData();
Or, for single fields:
$var = $form->get('yourformfieldname')->getData();
Watch out: this is for Symfony >= 2.3, and it would get you two different things:
the entity with values populated by the form, if your form have the data-class option enabled (so it's binded to an entity); this will exclude any field with the 'mapping' => false option
otherwise, an array with all the form's fields