I have made a method called by an Ajax request when a button is clicked.
/**
* #param Request $request
*
* #Route("/add", name="rapid_access_add", options={"expose"=true})
* #Method({"GET"})
*
* #return Response
*/
public function addRouteAction(Request $request)
{
$title = $request->query->get('title');
$user = $this->getUser();
$url = $this->get('request_stack')->getMasterRequest()->getUri();
$rapidAccess = new RapidAccess();
$rapidAccess->setUrl($url)
->setTitle($title)
->setUser($user);
$em = $this->getDoctrine()->getManager();
$em->persist($rapidAccess);
$em->flush();
$this->addFlash('success', $this->get('translator')->trans('user.flash.rapid_access_added', ['%title%' => $title], 'front'));
return new Response('OK');
}
I'm trying to get the URL of the current page, render by another controller (this method is in a fragment controller).
But when I use $this->get('request_stack')->getMasterRequest()->getUri(); this give me the URL of the addRouteAction method.
This should give me the master request URL but I don't understand why this send me this method URL. How can I get the current page URL instead of this method URL ?
Maybe I should get the URL with JS instead ?
Thanks
Why do use request stack ?
You can use directly Request from Controller :
$request->getUri();
Related
I'm new with Symfony4 so maybe this is a noob question. But can't figure
it out.
I'm trying to register a user with an ajax call:
this.form.post('/register').then((response) => {
console.log(response);
});
Then in symfony my controller method looks like this:
/**
* #Route("/register", name="register", methods={"POST"})
* #param Request $request
* #param UserPasswordEncoderInterface $passwordEncoder
* #return JsonResponse
*/
public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$user = new User();
// encode the plain password
$user->setPassword(
$passwordEncoder->encodePassword(
$user,
$request->request->get('password')
)
);
$user->setEmail($request->request->get('email'));
$user->setName($request->request->get('name'));
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
return $this->json(['success' => 'User created']);
}
The problem is that the data is always empty. The data is send correctly. When I dd the response in my controller I see this:
My headers etc. look like this:
Request payload looks like this:
When I try it with postman I get the same result. What could I be doing wrong?
You need to create a form type on the back-end side to validate your new registrated user, check this documentation. Don't forget to update your controller also.
In your twig, you must define
<script>
let registerPath = "{{ app.request.getSchemeAndHttpHost() ~ path('register') }}";
</script>
And in your js you can use your ajax post like that :
this.form.post(registerPath).then((response) => {
console.log(response);
});
Hope that can help :)
In a symfony projects, I'm trying to persist a line of an association table (profil_role) composed of two objects (profil and role).
First, I developed The create action in the ProfilRoleController of the second project this way:
/** #var Roles $role */
$em = $this->getDoctrine()->getManager('main_project');
$role = $em->getRepository("MyBundle\Entity\Roles")->find($roleId);
$profil = $em->getRepository("MyBundle\Entity\Profil")->find($profilId);
$profilRole = new ProfilRoles();
$profilRole->setRoleId($role->getId());
$profilRole->setProfilId($profil->getId());
$em->persist($profilRole);
$em->flush();
This part of code, call then the post entity action present in the main project:
/**
* #Rest\View(statusCode=Response::HTTP_CREATED)
* #Rest\Post("/profil_roles")
*/
public function postEntityAction(ProfilRoles $profilRole)
{
$em = $this->getDoctrine()->getManager();
$em->persist($profilRole);
$em->flush();
return $profilRole;
}
When I try to execute my code i'm getting this king of error:
Execution failed for request: POST /api/profil_roles? HTTP/1.1 {"profil":{"id":"12"},"role":{"id":"3"}}: HTTPCode 500, body {"code":500,"message":"Unable to guess how to get a Doctrine instance from the request information."}
I've tried to use the #ParamConverter annotation, but I don't how to use it my case.
try this:
public function postEntityAction() {
$postData = $request->request->all();
$profileRole = $postData['profile_role']
Instead of this:
public function postEntityAction(ProfilRoles $profilRole)
#AlessandroMinoccheri I've tried to be inspired by your reply to do this and i'ts workin, i don't know if it's the correct way.
/**
* #param ProfilRoles $profilRole
* #param Request $request
* #return ProfilRoles
* #Rest\View(statusCode=Response::HTTP_CREATED)
* #Rest\Post("/profil_roles")
*/
public function postEntityAction(Request $request)
{
$profilRole = new ProfilRoles();
$em = $this->getDoctrine()->getManager();
$requete = $request->request->all();
$profilRole->setProfilId($requete['profil']['id']);
$profilRole->setRoleId($requete['role']['id']);
$em->persist($profilRole);
$em->flush();
return $profilRole;
}
I have a page with a form and want to know if it is possible to access it using GET, but only allow logged in users to POST to it.
I know this can be done in security.yml, but am not sure how to do it with annotations.
/**
* #param Request $request
* #return Response
* #Security("has_role('ROLE_USER')")
* #Method(methods={"POST"})
*/
public function calculatorAction(Request $request)
{
$form=$this->createForm(new CallRequestType(),$callReq=new CallRequest());
$form->handleRequest($request);
if($form->isValid()){
//blabla
}
return $this->render('MyBundle:Pages:calculator.html.twig', array('form' => $form));
}
This will secure the whole function, but I want to access it, just not POST to it without being logged in. An alternative would be to check if there is a logged in user in the $form->isValid() bracket. But I'm still wondering if it can be done with annotations.
You could do something like this.
You can allow both method types anonymously, and check just inside the controller to see if the user is authenticated and is POSTing.
(You don't state which version of symfony you're using, so you might have to substitute the authorization_checker (2.8) for the older security.context service)
/**
* #param Request $request
* #return Response
*
* #Route("/someroute", name="something")
* #Method(methods={"POST", "GET"})
*/
public function calculatorAction(Request $request)
{
if ( !$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY') && $request->getMethod() == 'POST') {
throw new AccessDeniedHttpException();
}
$form=$this->createForm(new CallRequestType(),$callReq=new CallRequest());
$form->handleRequest($request);
// you also need to check submitted or youll fire the validation on every run through.
if($form->isSubmitted() && $form->isValid()){
//blabla
}
return $this->render('MyBundle:Pages:calculator.html.twig', array('form' => $form));
}
I have indexAction and contactAction
contactAction is a simple form with no mapped fields (FormType) like below:
/**
* #Route("/contact", name="contact")
* #Template()
* #param Request $request
* #return array
*/
public function contactAction(Request $request)
{
$form = $this->createForm(new ContactType());
$form->handleRequest($request);
if ($form->isValid()) {
$firstName = $form->get('first_name')->getData();
$lastName = $form->get('last_name')->getData();
$email = $form->get('email')->getData();
$message = $form->get('message')->getData();
}
return array(
'form' => $form->createView()
);
}
and i render this form in my indexAction with this TWIG command:
{{ render(controller('RusselBundle:Default:contact')) }}
Everything is okey, if page is not reloaded, HTML5 validators works fine, but if form have some errors like: firstName length, error's not show at all, how can i do, so that errors showed up in the form indexAction? Any help would be appreciated. I'm just curious it's possible, and if - how ? Sorry for my english....
Rather than using the request passed into the action you should get the master request from the request stack. As #DebreczeniAndrás says, when you use the render(controller()) you are using a newly created sub-request rather than the request that was actually passed to the page on load (the master request).
public function contactAction(Request $request)
{
$request = $this->get('request_stack')->getMasterRequest();
$form = $this->createForm(new ContactType());
//...
}
On symfony3 use render function like this
{{ render(controller('RusselBundle:Default:contact', {'request':app.request})) }}
If you use the render function in your twig, then that creates a subrequest, thus your original posted (i.e. in your main request) values get lost.
You can pass your main request to your form render action as follows:
{{ render(controller('RusselBundle:Default:contact'), 'request' : app.request ) }}
This will pass all the main request parameters appropriately to your subrequest.
Using Laravel 4 to create a "Read-it-Later" application just for testing purposes.
I'm able to successfully store a URL and Description into my application using the following curl command:
curl -d 'url=http://testsite.com&description=For Testing' readitlater.local/api/v1/url
I'm interested in using GET to accomplish the same thing but by passing my variables in a URL (e.g. readitlater.local/api/v1/url?url=testsite.com?description=For%20Testing)
Here is my UrlController segment:
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
$url = new Url;
$url->url = Request::get('url');
$url->description = Request::get('description');
$url->save();
return Response::json(array(
'error' => false,
'urls' => $urls->toArray()),
200
);
}
Here is my Url model:
<?php
class Url extends Eloquent {
protected $table = 'urls';
}
I read through the Laravel docs on input types but I'm not certain how to apply that to my current controller: http://laravel.com/docs/requests#basic-input
Any tips?
You didn't apply what you correctly linked to...Use Input::get() to fetch anything from GET or POST, and the Request class to get info on the current request. Are you looking for something like this?
public function store()
{
$url = new Url; // I guess this is your Model
$url->url = Request::url();
$url->description = Input::get('description');
$url->save();
return Response::json(array(
'error' => false,
'urls' => Url::find($url->id)->toArray(),
/* Not sure about this. You want info for the current url?
(you already have them...no need to query the DB) or you want ALL the urls?
In this case, use Url::all()->toArray()
*/
200
);
}