i have these methods in module1/actions/actions.class.php:
public function executeMethod1(sfWebRequest $request){
$a = 10;
sfContext::getInstance()->set('a', $a);
return $this->redirect('module1/method2');
}
public function executeMethod2(sfWebRequest $request){
echo sfContext::getInstance()->get('a');
}
When i execute module1/method1 i get this error:
"The "a" object does not exist in the current context."
Any idea?
Javi
The redirect is telling the browser to load another page which terminates the current action and results in a new request that has a new context.
There are three options here:
You could use a forward if you want module1/method2 to be executed as the result of the first request.
You could use a flash attribute to pass $a to the next request.
You could use a session attribute if $a has to live beyond the next request.
EDIT: You don't need the return statement before the redirect either.
Related
I am storing full name of user in cookie after user successfully logs in with following code.
var res = await _signInManager.PasswordSignInAsync(suser.UserName, user.Password, user.Remember, false);
if (res.Succeeded)
{
Response.Cookies.Append("fullName", suser.FullName);
if (string.IsNullOrWhiteSpace(returnUrl))
return RedirectToAction("Dashboard", "User");
else
return Redirect(returnUrl);
}
I want to read this value in _Layout page so that I can display full name in master page. According to solution mention in this post. I tried following sysntax in my _Layout page.
#inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
#{
ViewBag.FullName = HttpContextAccessor.HttpContext.Request.Cookies["fullName"];
}
But I am not getting any value in ViewBag.FullName. Am I doing something wrong here? How to read stored value in cookies in Views?
I´ve done some tests to get the same result as yours.
The way I see it, you´re appending a new cookie value to the Response.Cookie and trying to access it in the Request.Cookies, so, the added value ("fullname") will only be available in the next request (after a redirect). If you try to access it in a View rendered at the same request that you set the cookie, the cookie value will be null.
I did the test with "return View()" and with "return RedirectToAction", only the second one worked.
I see that in your code you´re doing a redirect, I advice to debug it and see if the code is actualling entering in that line of code, if it is, go to that action that you are redirecting and, debugging it, see if the Request.Cookies are ok.
Regards.
My problem is that i want to preview data on index view without saving data in database. For this purpose, I want to send the list of objects in params section of redirect. And on receiving action want to use that list of objects.But when i include as below
def preview(){
//some code
redirect action: "index", params:[planId:params.planId, beamsInfoList: beamsInfoList]
}
I want something like below to happen.
def index() {
//some code
try{
planInfo.beamInfo = (params.beamsInfoList==null)?planInfo.beamInfo:params.beamsInfoList //beamInfo is also list
//some code
Object[] obj = GRMUtils.calculateTotalBeamsPower(planInfo.beamInfo)
totalPlanPower = (Float)obj[0];
beamPowerMap= (Map<Integer, String>)obj[1];
AmMapUtility utility=new AmMapUtility()
output = utility.generateAMmapFromBeams(planInfo.beamInfo, GRMConstants.POWER_MAP_PAGE);
if(null==output){
flash.error = message(code: 'beammap.noinfoerror.message')
}
}catch(Exception e){
log.error "Excepton occured while loading Power Map", e
}
respond beams, model:[centerLong:output.getCenterLongitude(),centerLat:output.getCenterLatitude(),amMapImageProperty:output.getMapImages(),
amMapLinesProperty:output.getMapLines(), planId:params.planId, planInfo:planInfo, powersControlCarrier: powersControlCarrier, powersTrafficCarrier:powersTrafficCarrier,satPower: planInfo.satellite.satelliteMaxPower, totalPlanPower: totalPlanPower, gatewayPower: planInfo.gateway.gatewayAggregateEIRP,fesOutputPowerLimit:fesOutputPowerLimit, beamPowerMap: beamPowerMap,powerRangeColorMap:output.getReuseColorMap()]
}
It does not redirect to index method and not showing any errors. Both actions are in same controller. I have used flash, but its not helping either as value reflected on second request. I have tried session too, but i am getting error
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
on some DB fetch. I am stuck. I am new to grails and groovy. Please help.
Edit: i have found my list is large, that is why its not redirecting. Please help me with another alternative like how can i use request attribute if it is possible?
I think i have solved the problem. Its working now. All i need to do is to use the request setattribute as
request.beams = beams
And no need to pass the list in params of redirect, which i was earlier used to do. Instead of using redirect, i used forward as below:
request.beams = beams
forward action: "index", params:[planId:params.planId]
This is my unit test for create function :
public function testCreate() {
$this->routeMatch->setMatchedRouteName('restful');
$this->request->setMethod('POST')
->setContent('name=A');
$result = $this->controller->dispatch($this->request);
$response = $this->controller->getResponse();
$this->assertEquals(403, $response->getStatusCode());
$this->assertArrayHasKey('id', $result);
}
And this is my function :
public function create($data) {
if (empty($data)) {
$this->response->setStatusCode(400);
return;
}
for ($i = 0; $i < count(self::$ideas); $i++) {
if (self::$ideas[$i]['name'] == $data['name']) {
$this->response->setStatusCode(404);
return;
}
}
//#todo: secure the API
self::$index++;
$tmpArray = array('id'=>self::$index, 'name'=>$data['name']);
$this->response->setStatusCode(403);
}
But it seems that the $data is always blank. Am I wrong at the part writing unit test ?
When I try to use curl POST with -d, the $data has value as what I post through curl. I'm a quite confused what is wrong here ?
Thanks for reading and looking forward to your answer :)
Answer
I've came up with my successful unit test http://pastebin.com/fwFe0Mi3
For more information, I use this module to implement restful controller
If you take a look at \Zend\Mvc\Controller\AbstractRestfulController method processPostData you will notice that the method create in your controller is given an array of the post params from the request object.
If you look at \Zend\Http\Request the $postParams property is populated by the setPost method.
Now the child class \Zend\Http\PhpEnvironment\Request (used by ZF2 when you are requesting something) that extends \Zend\Http\Request (above) on instantiation (__contruct method) calls the setPost method (above) giving it the $_POST array.
This means that eventually ZF2 internally feeds your controller's create method with the $_POST contents and not by parsing the request body.
Now to your code.
I don't think dispatch will do anything without you having set up the event framework first. Instead you can call the controllers execute method providing it with an MvcEvent. The MvcEvent needs to have the request you instantiated set.
Secondly, as described above you need to call the request's setPost and give it an array for the create method to work properly. (On the other hand PUT reads the data from the request body)
Try doing that and if you are still having trouble I will try and give you an example soon.
Hi i have the following code:
public function executeFilter(sfWebRequest $request) {
$c = new Criteria();
$c->add(NomenclatoreCodicePeer::LIST_CODE, $request->getParameter('list_code'), Criteria::LIKE);
$pager = new sfPropelPager('NomenclatoreCodice', sfConfig::get('app_max_jobs_on_category'));
$pager->setCriteria($c);
$pager->setPage($this->getRequestParameter('page', 1));
$pager->init();
$this->pager = $pager;
}
It works fine, but when i press "next page" button it loose the filtered items and page as if filter had not been set.
how can i fix it?
You should debug the queries to see if they are correct on each page.
My first guess would be that the list_code parameter is not set on subsequent requests.
Is the list_code parameter also passed to the url for the second page? And is the filter action called on the second page? Or just your default list(?) action?
Is it possible to set cookies on response when the return render type is set as json?
I can set cookies on the response object when returning with a standard render type and later on, I'm able to get it back on the subsequent request. However, if I were to set the cookies while rendering the return values as json, I can't seem to get back the cookie on the next request object. What's happening here?
These two actions work as expected with 'basicForm' performing a regular form post to the action, 'withRegularSubmit', when the user clicks submit.
// first action set the cookie and second action yields the originally set cookie
def regularAction = {
// using cookie plugin
response.setCookie("username-regular", "regularCookieUser123",604800);
return render(view: "basicForm");
}
// called by form post
def withRegularSubmit = {
def myCookie = request.getCookie("username-regular");
// returns the value 'regularCookieUser123'
return render(view: "resultView");
}
When I switch to setting the cookie just before returning from the response with json, I don't get the cookie back with the post.
The request starts by getting an html document that contains a form and when doc load event is fired, the following request is invoked via javascript with jQuery like this:
var someUrl = "http://localhost/jsonAction";
$.get(someUrl, function(jsonData) { // do some work with javascript}
The controller work:
// this action is called initially and returns an html doc with a form.
def loadJsonForm = {
return render(view: "jsonForm");
}
// called via javascript when the document load event is fired
def jsonAction = {
response.setCookie("username-json", "jsonCookieUser456",604800); // using cookie plugin
return render(contentType:'text/json') { 'pair'('myKey': "someValue") };
}
// called by form post
def withJsonSubmit = {
def myCookie = request.getCookie("username-json");
// got null value, expecting: jsonCookieUser456
return render(view: "resultView");
}
The data is returned to the server as a result of the user pressing the 'submit' button and not through a script. Prior to the submit of both 'withRegularSubmit' and 'withJsonSubmit', I see the cookies stored in the browser (Firefox) so I know they reached the client.
I realized what the problem is -- the cookie plugin doesn't set a path for the cookie so it's stored with "server/controller/action" whereas on the subsequent request when I'm asking for the cookies, the plugin returns the cookies associated with the new request's path.
Tweaking the plugin code so the cookies are stored with uniform paths helped.