I have a template based project in Kohana. A search form is rendered as a part of common sections of template. The searching mechanism is handled by controller called calendar. I want to call controller calendar in user controller, which I could achieve by
$this->request->redirect('calendar');
But, in calendar, $_POST is empty. How can I access $_POST which was set by submitting the search form in user controller?
Request::redirect() terminates the execution and responds with a 302 Location redirect header. Of course, you can't access the previous POST on the new page.
HMVC subrequesting can be used for cases like this:
$response = Request::factory('calendar')
->method(Request::POST)
->post($this->request->post())
->execute();
Probably the best solution to your problem, if you are unable to use HMVC subrequesting, is to store the $_POST variables you need into the session:
$my_var1 = $this->request->post('my_var1');
$my_var2 = $this->request->post('my_var2');
$session = Session::instance();
$session->set('my_var1', $my_var1);
$session->set('my_var2', $my_var2);
$this->request->redirect('calendar');
Then, in your calendar controller/action you can access said variables from the session:
$session = Session::instance();
$my_var1 = $session->get('my_var1');
$my_var2 = $session->get('my_var2');
Related
I have two controllers. One is login.js and the another one is home.js. I want to redirect to home controller from login controller with a value. To redirect to home controller, i wrote,
response.redirect('/home');
But, i cannot pass value here. When rendering a view with a value,
data = {'value':'hello'};
response.render('view_login',data);
I want to do the same thing. I can pass value while rendering to the view but not when changing controller. Can i do this?
response.redirect('/home',{data: data});
you can use query parameters for this.
When you are redirecting your home page or any other controller then you can write like this
res.redirect(/<some controller>?data=<some data>)
and in that controller where you want to use this value..you can write like this
function login(req,res){
var data = req.query.data;
}
In WATIRwe use #current_page whenever we lands to page which got created at run time (during test case execution).
I am looking for similar feature in Geb.
Here I have two Pages
RegistrationPage.groovy
where I have provided
static url = "/register.html"
I also have UserProfilePage.groovy
here I can't provide any static url because it gets created once I submit the Registration Page, it changes as per user name
example https://xxxxx.com/paul.html, if two paul's are there then https://xxxxx.com/paul2.html
I want to use
static content = {
defaultprofilePic {$("#userprofilepic")}
}
declared in UserProfilePage.groovy
If I am not using to keyword it would land me back to baseURL and if I use it gives exception that element not available on this page.
But I think if I use could something like #current_page it would pass
You should use at(UserProfilePage) which sets the current page to be an instance of UserProfilePage and also verifies its at checker.
I have a JSF page contentEdit.xhtml which accepts a request parameter "code" to load the content for editing and other operations related. To provide access control, I create a filter ContentAccessFilter and applies it to contentEdit.xhtml to check whether the current user is authorized to the content which is identified by "code".
Fragment of ContentAccessFilter:
boolean isAuthorized = false;
String userId = httpReq.getRemoteUser();
String code = httpReq.getParameter("code");
if (code != null && !code.isEmpty())
{
ContentDAO dao = ContentDAO.getInstance();
isAuthorized = dao.isContentAuthorized(code, userId);
}
if (!isAuthorized)
{
httpRes.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
For the first entry of the contentEdit.xhtml, the filter works properly as the code parameter always exists during the first entry by calling such as /contentArea.xhtml?code=cnn from an anchor html tag. However, the code parameter is lost when there is subsequent operations on contentEdit.xhtml. For example, I have buttons like these.
<p:commandButton value="Download" action="#{contentView.downloadContent}"/>
<p:commandButton value="Publish" action="#{contentView.publishContent}"/>
Clicking the button will call the same URL as contentEdit.xhtml, while the parameter code is not included in the request URL. This missing parameter fails in the filter.
Is using a Servlet Filter a proper way to achieve the access control in this case? If it is, how to include a request parameter when triggers a commandButton?
Filters are a great way to implement authorization in a web app... you're on the right track.
The best way would be to use your filter but store the code parameter value in a session (javax.servlet.http.HttpSession), that way the parameter doesn't need to be passed in the query string with each request. You would set the code attribute in the session data on the first request and retrieve it whenever a new request is received.
If you must use the query string to pass the code value with each request, you'll need to use the includeViewParams parameter in the query string creation to preserve the code parameter in the generated URLs. BalusC (the JSF God) explains this better than anyone... https://stackoverflow.com/a/17745573/3858863
The MVC project that I am currently working on uses Regions so that we can localise pages etc.
I have spotted a problem with our Error page. We have turned the custom error pages on in the web.config file. If we are on a page lets say : /IT/News/Index and we get an error, when it redirects it will go to /Error and there will be no routevalue attached to it.
Is there away to ensure that the langauge routevalue is retained by the Error page?
I have searched around and cannot find a solution at the moment and was wondering if anyone else could help or point me in the right direction?
Hope that this all makes sense. Any help is much appreciated.
If you're getting physically redirected to /Error then it's not because of the MVC HandleErrorAttribute. It's probably due to your Web.Config having system.web/customErrors defined for error handling. Using the HandleErrorAttribute causes it to inject a specific view instead of the view you would have normally returned but does not redirect you to a different action by default. The problem is when redirected because of customErrors, there is no inherant information available to tell you where they came from. But using HandleErrorAttribute DOES cause some info to be populated for you. Specifically it creates a HandleErrorInfo to use as a view model and passes that to the view you specify. For example, here's one that is reigstered in the /App_Start/FilterConfig.cs file.
public class FilterConfig
{
public static void RegisterFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute {View = "Error"});
}
}
When you redirect to an error View using the HandleErrorAttribute, certain information is populated for you. The HandleErrorInfo view model will contain the ControllerName of the original controller requested, and the ActionName of the original action. Also, the ViewData and the TempData from the original request will be copied into the ViewData and Temp data for the request to the Error view. With that information it should have what you need. Be aware that not all errors happen inside of an Action however, and exceptions that don't happen in an action will not be caught by the HandleErrorAttribute. So you'll still need to use something like customErrors (or system.webServer/httpErrors if you're doing it inside of IIS7+) to handle exceptions that occur elsewhere in your app.
Here's a link to the HandleErrorAttribute file on CodePlex in case you're wondering what it does. HandleErrorAttribute.cs
I'm not sure if this solution meets you requirements. You can override in your base controller OnException and then redirect to a specific page.
protected override void OnException(ExceptionContext filterContext)
{
string controller = filterContext.RouteData.Values["controller"].ToString();
string action = filterContext.RouteData.Values["action"].ToString();
//get other stuff from routing
//here you can do redirect or other stuff
//if handled exception
//filterContext.ExceptionHandled = true;
base.OnException(filterContext);
}
It depends how you're getting to the error pages, really. If you're using an ActionFilter-based method to catch exceptions, then you can get route values from the context that gets passed into the OnException method. If you're using a redirect from a catch block, then you can push the relevant information into TempData or pass it directly as a parameter, depending on how you're doing that redirect.
You can add a custom HandleErrorAttribute or use a base controller to be inherited by all your controllers. Either way, you need to get the RouteData object, like this
var routeData = filterContext.RouteData;
with that object, you can get all the route values accordingly to your needs. Check the object definition in MSDN site for more detail
Say you have the following route
routes.MapRoute(
"Language", // Route name
"{language}/{controller}/{action}/{id}", // URL with parameters
new { language = "en", controller = "Sites", action = "Index", id = UrlParameter.Optional } // Parameter default
Then routeData.Values.Keys will tell you the name of the parameter and routeData.Values.Values the value itself
Then, wherever you handle the exception, you can store the route data in a TempData variable, like this
TempData["RouteData"]
And after that, it will be available on your error page
#model System.Web.Mvc.HandleErrorInfo
#{
ViewBag.Title = "Error";
}
<h2>
Sorry, an error occurred while processing your request.
</h2>
#TempData["RouteData"];
I am using Yii. I want to have a dynamic link on a layout. This dynamic link will be modified by controllers. Let's say that dynamic link uses a user's id given by controllers to perform a task.
I am thinking to use jQuery script to get user id returned by controllers then use the user id to modify a div that holds the dynamic link.
What do you think about this technique?
It seems like you want to dynamically change a link AFTER the page is rendered, with client-side JavaScript. But it makes more sense to dynamically render a different link the first time, during the server-size PHP rendering process. The controller generates the view, after all! I would get the user ID from the controller during the page request, pass the ID in to the view, and then build the link in the view dynamically on the initial page load.
If you are modifying a link in a layout (not a view), then the best thing to do is create a variable in the Controller, and set that variable with the view. Look at how Yii uses the $layout, $menu and $breadcrumbs variables to do this.
Assuming that the user is logged in and you want their ID, you can get the ID from the Yii::app() object as well, like so:
<?php echo CHtml::link('Edit user',array('user/edit','userId'=>Yii::app()->user->id)); ?>
But at that point, you can just request the user's ID in the controller, and don't need to build a link like this.
Assuming that you want a different user ID than the logged in user, pass that ID ($userId) from the controller into the view, and just do this (as Moyersy said):
<?php echo CHtml::link('Edit user',array('user/edit','userId'=>$userId)); ?>
This will build the following link (where $userId = 99999999):
Edit user
So when the linked is clicked, in the actionEdit() you now have access to the user's ID via the GET variable $_GET['userId'].
NOW, if what you want to do is change an already created link, then you would need to use jQuery. But you will need to explain in more detail why you are doing this and what is triggering the link change (a dropdown menu?).
I'm sorry, I can't understand what you are trying to do. Specifically I don't understand what a dynamic link is.
Edit:
<? echo CHtml::link('Edit user',array('user/edit','userId'=>$userId)); ?>