How do I pass parameters after setting the content of a template? - kohana

My problem is that I lose the parameters (i.e. I can't use the id variable) when I get inside the if condition because this occurs after I press the submit button in the view (i.e. after I set the post array)
public function action_resetpassword()
{
$this->template->content = View::factory('user/password/reset')
->bind('message', $message)
->bind('errors', $errors);
if (HTTP_Request::POST == $this->request->method())
{
$id = $this->request->param('id');

If I understand you correctly you wish to pass parameters to the view which are set in the if. This can be done easily by 'binding' these variables to the view (i.e. pass by reference)
public function action_resetpassword()
{
$this->template->content = View::factory('user/password/reset')
->bind('message', $message)
->bind('errors', $errors)
->bind('id', $id); // Empty variable is defined here ...
if (HTTP_Request::POST == $this->request->method())
{
// ... and set here
$id = $this->request->param('id');
Inside the view the $id will now have the value of whatever comes from the Request parameter.
If this is not what you mean, you should read a bit about variable scope in PHP and this question is not necessarily related to Kohana
http://php.net/manual/en/language.variables.scope.php

Related

How to map undefined amount of path parameters to request parameters in Ocpsoft Rewrite?

Currently I´m trying the following JSF - Lib:
https://www.ocpsoft.org/rewrite/examples/
I have the following issue:
I have a page:
/page.jsf
In my page I have more then only one parameter.
E.g. I have:
- parameter1
- parameter2
String parameter1 = FacesContext.getCurrentInstance().getExternalContext()
.getRequestParameterMap().get("parameter1");
String parameter2 = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap()
.get("parameter2");
Currently I understood I can add this in my UrlConfigProvider class:
.addRule(Join.path("/page/{parameter1}").to("/portal/mypage.jsf")
.withInboundCorrection())
This is working for one parameter.
But how can I do this for multiple parameter, so the URL is then:
/page/{parameter1}/{parameter2}
....
Any ideas?
The rewrite API doesn't bring a native solution for this problem.
Kick-Off Example
.addRule()
.when(/* your condition */)
.perform(new HttpOperation() {
#Override
public void performHttp(HttpServletRewrite httpServletRewrite, EvaluationContext evaluationContext) {
// this is the default wrapper
HttpRewriteWrappedRequest request = ((HttpRewriteWrappedRequest) httpServletRewrite.getRequest());
// get the uri (example: '/index/p1/p2')
String uri = httpServletRewrite.getRequest().getRequestURI();
// split by slash
String[] split = uri.split("/");
// this is example specific
// split value 0 is empty and split value 1 is the page (e.g. 'index')
// for every folder increment the index
// for '/pages/index' the start index should 3
for (int i = 2; i < split.length; i++) {
String s = split[i];
// the request parameter is by default an immutable map
// but this returns a modifiable
request.getModifiableParameters().put("prefix" + (i - 1), new String[]{s});
}
}
});
Explanation
The only important piece is the HttpOperation. By default the ServletRequest is wrapped in a HttpRewriteWrappedRequest.
The default HttpServletRequest doesn't allow to change the parameters once they were initialized. The method getParameterMap() returns an immutable map.
getParameterMap() of the HttpRewriteWrappedRequest also returns an immutable map. But getModifiableMap() returns obviously a modifiable map.
The rest should be self-explanatory.
See Also
Ocpsoft: How to modify parameters
Modify request parameter with servlet filter

change the expression in lwc component while iterating

We can use variables in aura components to concatenate some expression, we have to use variable name itself in lwc components, while looping how to change the lwc comp variable in js file.
I tried to access the dom using this.template.querySelector(); but this one is only giving the value if I use a rendered callback.
<template for:each={documentLinks} for:item="item">
//here I need to pass the item.ContentDocument.LatestPublishedVersionId to the end of a URL string
<img src={item.srcUrl} alt="PDF"/>
we can modify the returned data from apex but the data is proxy we cannot modify it.
One of the possible solutions to change the URL on the dom when it loads is to change the returned data from the server. here, In lightning web components the returned data is a proxy object, only readable. so we have to clone it(there are multiple ways to clone it), to make any changes. but here what I did.
therefore, overrides array is going to be the new data.
let overrides = [];
let newData = {
contentDocs: data[i],
srcUrl: '/sfc/servlet.shepherd/version/renditionDownloadrendition=thumb120by90&versionId=' + data[i]['ContentDocument']['LatestPublishedVersionId']
};
makeLoggable(newData);
overrides.push(newData);
function makeLoggable(target) {
return new Proxy(target, {
get(target, property) {
return target[property];
},
set(target, property, value) {
Reflect.set(target, property, value);
},
});
}

How to keep particular sessionScope variable(s) in use and remove the other sessionScope variable(s)?

The application allows the user to search and the result displays in the other page
For example search.xsp is for user to fill information to search and searchresult.xsp is for display the search result.
In search.xsp and searchresult.xsp, I use sessionScope variable to perform search function.
The search function is something like this:
var qstring= "";
if ((sessionScope.ItemSearch != null && sessionScope.ItemSearch != "")||(sessionScope.CategorySearch != null && sessionScope.CategorySearch != "")|| (sessionScope.LocationSearch != null && sessionScope.LocationSearch !=""))
{
qstring = " FIELD Item contains " + sessionScope.ItemSearch +
" | FIELD Category contains " + sessionScope.CategorySearch +
" | FIELD Location contains " + sessionScope.LocationSearch
}
return qstring;
In the searchresult.xsp, I add a back button that will return to the search.xsp.
I read the user requirement, when the user clicks the back button, it will redirect the user to the search.xsp but the previous selection should be cleared.
To clear the sessionScope variable, I found this code from this website
https://openntf.org/XSnippets.nsf/snippet.xsp?id=clear-session-current-nsf
clearMap(sessionScope);
//facesContext.getExternalContext().redirect("./?logout");
// Clear Map function
function clearMap( map:Map ){ // Get iterator for the keys
var iterator = map.keySet().iterator(); // Remove all items
while( iterator.hasNext() ){
map.remove( iterator.next() );
}
}
I applied the code in search.xsp in afterPageLoad event so when I click the back button, the search.xsp will remove my previous search selection.
Here is my question.
On top of every page, there is a computed field which shows the user's login role. The reason needs to show the user's role is the user will have multiple roles in the application and I created another page to let user to choose the role that the user wants to login as.
Here is the code of that computed field
var selectrole =sessionScope.role;
if(selectrole == "Common User")
{
return "You logged in as Common User role";
}
else if(selectrole == "Senior User")
{
return "You logged in as Senior User role";
}
else if(selectrole == "Manager")
{
return "You logged in as Manager role";
}
else if(selectrole == "Administrator")
{
return "You logged in as Administrator role";
}
else
{
}
Due to I use sessionScope variable to show user role, so if the user goes to the search.xsp and perform the search function, when the user the clicks the back button in searchresult.xsp. The clear sessionScope function will also remove sessionScope.role's value.
I searched on the internet about clear specific sessionScope variable but it seems not much information on this issue
Since the clear sessionScope variable works fine, I tried to remove specific sessionScope variable.
clearMap(sessionScope.ItemSearch);
//facesContext.getExternalContext().redirect("./?logout");
// Clear Map function
function clearMap( map:Map ){ // Get iterator for the keys
var iterator = map.keySet().iterator(); // Remove all items
while( iterator.hasNext() ){
map.remove( iterator.next() );
}
}
At the beginning, I think it is hard to remove specific sessionScope variable, and the result comes as no surprise for me that I get the error.
So is there any possible method that I can keep particular sessionScope variable(s) in use and clears the other sessionScope variable(s)?
Or any better approach for this case?
Grateful for your advice please. Thank you
Please bear in mind what the code you link to is doing. The first line is logging the user out of HTTP completely. The rest is going through sessionScope and, for every key, removing that variable from the sessionScope map of variables.
I added that snippet to replace a simple logout button, because if a user just logs out of HTTP, then logs in as a different user, they (by default) retain the same sessionScope variables, because sessionScope is browser session, not user session.
It sounds like you don't want that snippet. Instead you just want to clear a specific sessionScope variable. sessionScope.remove("myKey") will do that, where myKey is the sessionScope variable key.
Simply set search's sessionScope variables to an empty string
sessionScope.ItemSearch = "";
sessionScope.CategorySearch = "";
sessionScope.LocationSearch = "";
This keeps the other sessionScope variables alive and your search form is cleared.

Kohana 3: How can I pass full control to another action within my controller?

In my controller, I have a before() function that calls parent::before() and then does some additional processing once the parent returns. based on a specific condition, I want to "save" the original request and pass execution to a specific action. Here is my before() function.
public function before() {
parent::before();
$this->uri = Request::Instance()->uri;
$match = ORM::factory('survey_tester')
->where('eid','=',$this->template->user->samaccountname)
->find();
if (!$match->loaded()) {
self::action_tester("add",$this->template->user);
}
}
And the action that is being called..
public function action_tester($op=null,$user=null) {
$testers = ORM::factory('survey_tester')->find_all();
$tester = array();
$this->template->title = 'Some new title';
$this->template->styles = array('assets/css/survey/survey.css' => 'screen');
$this->template->scripts = array('assets/js/survey/tester.js');
$tester['title'] = $this->template->title;
$tester['user'] = $this->template->user;
switch ($op) {
case "add":
$tester = ORM::factory('survey_tester');
$tester->name = $user->displayname;
$tester->email = $user->mail;
$tester->division = $user->division;
$tester->eid = $user->samaccountname;
if ($tester->save()) {
$this->template->content = new View('pages/survey/tester_add', $admin);
} else {
$this->template->content = new View('pages/survey/tester_error', $admin);
}
break;
default:
break;
}
}
This all seems to work fine. This is designed to prompt the user for a specific piece of information that is not provided by $user (populated by LDAP) if this is the first time they are hitting the controller for any reason.
The problem is the views are not rendering. Instead control passes back to whatever action was originally requested. This controller is called survey. If i browse to http://my.site.com/survey and login with new user info, the record gets written and i get the action_index views instead of my action_tester views.
I cannot figure out what I am doing wrong here. Any ideas will be appreciated. Thank you.
EDIT: I managed to get this working (sort-of) by using $this->request->action = 'tester'; but I'm not sure how to add/set new params for the request yet.
The issue is that you are calling your method (action_tester), but then Kohana is still going to call the original action after the before method is called, which is going to change the response content overwriting the changed made in action_tester().
You can change the action being called (after before is called) inside your before() method:
$this->request->action('action_tester');
After the before method is called, it should then call the new Action (action_tester) rather than the old one, but then you need to do something about the way you are passing your parameters then.
Or you could just redirect the request upon some condition:
if($something) {
$this->request->redirect('controller/tester');
}
This doesn't seem like a nice way to do it anyway.

Appending Text to the body field in Drupal

I am trying to append a string to the body field of a CCK node after it has been submitted or edited. However, I'm having trouble working with the body field in the form alter. My initial attempt was to modify the body field in the submit handler by using the .operator to append a string to the body field.
//Calling this submit function to add string to body.
function appendToBody_submit_function($form, &$form_state) {
$form_state['values']['body'] = array('0' => array('value' => $form['#body'])) . $stringToAppend;
}
However, I can't get this to work, and I'm not sure it's the right way. I am new to Drupal, Can someone point me in the right direction? Should I be using node_api for this?
I assume that you add your custom submit callback to the forms #submit array via hook_form_alter().
If you add it before any other entry in that array (as opposed to just appending it), your callback should be called before the standard submit function. That way, all you need to do is adjust the $form_state['values']['body'] content 'in place', and it will be picked up (and subsequently saved) on further processing by the standard submit callback implicitly:
/**
* Implementation of hook_form_alter()
*/
function yourModule_form_alter(&$form, $form_state, $form_id) {
// Is this a node edit form?
if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] .'_node_form' == $form_id) {
// Yes, add custom submit handler *before* already existing ones
array_unshift($form['#submit'], 'appendToBody_submit_function');
}
}
// Custom submit function to add string to body.
function appendToBody_submit_function($form, &$form_state) {
$form_state['values']['body'] = $form_state['values']['body'] . $stringToAppend;
}
I recommend installing the Devel module so you can easily print out the contents of $form_state by placing dpm($form_state); in your method body. I usually start with that to make sure the values are where/what I expect.
// Replace "hook" in the function name with the name of your module.
function hook_submit($form, &$form_state) {
// dpm($form_state); // Debug code to view the contents of $form_state.
$body = $form_state['values']['body'] . ' new string to append';
// Place code to save this data to your database here.
}

Resources