CakePHP 4 - setting request data - php

We have a CakePHP 3.x app which we've updated to the latest CakePHP 4.x. As part of this work we've also changed from PHP 7 to PHP 8.
Whilst testing the app we noticed a feature that had stopped working.
The app is a searchable database and is integrated with Redis for caching. One of the features means that the users search is retained between page reloads. This works by writing serialized form data to Redis, and then re-populating that back into the input fields in the template. This means the user sees the search criteria they entered; they do not need to re-enter their search criteria when the page is refreshed.
The code in the CakePHP 3.x app which re-populated the input form fields looked like this:
$form_fields = ['f1', 'f2', 'f3'];
The $form_fields array contains the names of the form input's in the template. As an example:
<input type="text" name="f1">
The next part of the code re-populates the form. In this case $user_search is an array of data that has been obtained and unserialized from Redis. As an example we might have $user_search['f1'] and $user_search['f3'] containing Redis data; f2 is unpopulated because the user didn't search using that field.
foreach ($form_fields as $form_field) {
$this->request->getData()[$form_field] = (isset($user_search[$form_field])) ? $user_search[$form_field] : '';
}
In the Cake 3.x app the above works fine. When the page is reloaded the form fields are set due to setting the request data, e.g. in the loop above, it evalulates to:
$this->request->getData()['f1'] = 'foo';
$this->request->getData()['f3'] = 'bar';
This means the request data has "foo" as f1 and "bar" as f3. There is nothing in f2 so it gets set to an empty string as per the : ''; condition.
In the CakePHP 4.x app this does not work; all form fields are unpopulated on page reload. I've confirmed that they are not being set to empty strings by modifying the : ''; condition mentioned above to : 'test'; and ensured the string "test" is not being shown in the fields.
The data exists in Redis and I've confirmed that $user_search contains what's shown above - in other words the data is not missing so we've ruled that out.
When I read over https://book.cakephp.org/4/en/controllers/request-response.html I can't see an example of setting request data. There is a method getData() which does what you'd expect - it reads the request data.
Is there a way to set the request data in Cake 4.x such that the above code would work?
In vanilla PHP what we're doing is equivalent to
$_POST['f1'] = 'foo';
$_POST['f2'] = ''; // empty string as no value set by user
$_POST['f3'] = 'bar';
AFAIK this was - and still is - valid in PHP; you can set/overwrite request data with anything in your code. If this is wrong please advise what I should be doing instead.
For clarity the reason we are setting request data in this manner is because the search for works via an ajax call. When the user enters their search criteria initially, the page has not been reloaded so the form fields appear to be populated correctly. This issue occurs on page reload. In that instance we want to repopulate the form with the values they entered prior to the page being reloaded.

The function you're looking for is withData. Remember that the request object is immutable, so you need to assign the result of that function call back into the request object, e.g. with $this->setRequest($this->getRequest()->withData('f1', 'foo')->withData('f3', 'bar')).

Related

Laravel store session in cookie

I have a website where the front page contains a search form with several fields.
When the user performs a search, I make an ajax call to a function in a controller.
Basically, when the user clicks on the submit button, I send an ajax call via post to:
Route::post('/search', 'SearchController#general');
Then, in the SearchController class, in the function general, I store the values received in a session variable which is an object:
Session::get("search")->language = Input::get("language");
Session::get("search")->category = Input::get("category");
//I'm using examples, not the real variables names
After updating the session variable, in fact, right after the code snippet shown above, I create (or override) a cookie storing the session values:
Cookie::queue("mysite_search", json_encode(Session::get("search")));
And after that operation, I perform the search query and send the results, etc.
All that work fine, but I'm not getting back the values in the cookie. Let me explain myself.
As soon as the front page of my website is opened, I perform an action like this:
if (!Session::has("search")) {
//check for a cookie
$search = Cookie::get('mysite_search');
if($search) Session::put("search", json_decode($search));
else {
$search = new stdClass();
$search->language = "any";
$search->category = "any";
Session::put("search", $search);
}
}
That seems to be always failing if($search) is always returning false, and as a result, my session variable search has always its properties language and category populated with the value any. (Again: I'm using examples, not the real variables names).
So, I would like to know what is happening here and how I could achieve what I'm intending to do.
I tried to put Session::put("search", json_decode($search)); right after $search = Cookie::get('mysite_search'); removing all the if else block, and that throws an error (the ajax call returns an error) so the whole thing is failling at some point, when storing the object in the cookie or when retieving it.
Or could also be something else. I don't know. That's why I'm here. Thanks for reading such a long question.
Ok. This is what was going on.
The problem was this:
Cookie::queue("mysite_search", json_encode(Session::get("search")));
Before having it that way I had this:
Cookie::forever("mysite_search", json_encode(Session::get("search")));
But for some reason, that approach with forever wasn't creating any cookie, so I swichted to queue (this is Laravel 4.2). But queue needs a third parameter with the expiration time. So, what was really going on is that the cookie was being deleted after closing the browser (I also have the session.php in app/config folder set to 'lifetime' => 0 and 'expire_on_close' => true which is exactly what I want).
In simple words, I set the expiration time to forever (5 years) this way:
Cookie::queue("mysite_search", json_encode(Session::get("search")), 2592000);
And now it seems to be working fine after testing it.

Cannot initialize variable using beforeValidate

I have a custom behavior, specified in AppModel.php, that automatically creates a field based on the selected language. Thus, depending on the chosen language, name_eng -> name or name_fra -> name.
...
$virtualField = sprintf($model->name.'.'.$name.'_%s', Configure::read('Config.language'));
$virtualFields[$name] = $virtualField;
$model->virtualFields = $virtualFields;
...
This part works.
The issue arises when I submit the edit form, get a validation error and the field isn't available when the edit view is displayed with error prompts. I believe this is due to either my behavior not being called in this process or $this->request->data being created using form data?
I figured that I would initialize the values using beforeValidate. However, it's not working out: the field still doesn't exist once I've submitted the form which gives me this error:
In AppModel.php:
function beforeValidate(array $options = array()){
//hard coded for test purposes
$this->data['CertificateType']['name'] = $this->data['CertificateType']['name_'.Configure::read('Config.language')]
return true;
}
In the view (edit.ctp):
echo $this->request->data['CertificateType']['name'];
Essentially, how can I replicate the functionality of my custom behavior and initialize my field after a form has been submitted but doesn't validate?
The needed logic was eventually put in AppController.php. Everything works fine now.

Zend Framework POST data is not displayed or processed

This is my form: Profile form
It has two elements password and passwordConf
$this->password= new Zend_Form_Element_Password("password",array("label"=>"Password","required"=>true));
$this->passwordConf= new Zend_Form_Element_Password("confpassword",array("label"=>"Retype","required"=>true));
$this->passwordConf->addValidator("Identical",array("token"=>"password"));
$this->save=new Zend_Form_Element_Submit("save",array("label"=>"Change Password","class"=>"btn btn-primary"));
So I have an instance of this in controller and pass it POST data
$profileForm= new Application_Form_Profile();
if($_POST)
if($profileForm->isValid($_POST))
{
$membersTable= new Application_Model_DbTable_Members();
$member=$membersTable->find($this->user->id)->current();
$member->password=sha1($profileForm->getValue("password").$member->salt);
$this->_helper->flashMessenger(array("type"=>"success","content"=>"Password Changed!"));
$this->_redirect("");
$member->save();
}
$this->view->profileForm=$profileForm;
}
but for some reason, I get the Zend Empty Error message. I've also noticed that the Form fields are not populated.
I checked the response in Chrome and it appears post data is passed to the page just fine. Even did a print_r(POST) and even that looks fine and dandy with all the data. I did that before and after the block of code above, but doesn't work. It just does not populate the form despite the data being passed.
PS: The error message is only for password confirm field. The password field works fine
The problem here was that the nae of the class variable and the name of the element must match
$this->passwordConf= new Zend_Form_Element_Password("confpassword",array("label"=>"Retype","required"=>true));
i.e $this->passwordConf and confpassword should not be different otherwise this error will happen

Symfony forms question (restoring selected value of a dynamically populated sfWidgetFormSelect widget)

I am using Symfony 1.3.2 with Propel ORM on Ubuntu 9.10.
I have developed a form that dynamically populates a select widget with cities in a selected country, using AJAX.
Before the data entered on the form is saved, I validate the form. If validation fails, the form is presented back to the user for correction. However, because the country list is dynamically generated, the form that is presented for correction does not have a valid city selected (it is empty, since the country widget has not changed yet).
This is inconvenient for the user, because it means they have to select ANOTHER country (so the change event is fired), and then change back to the original country they selected, then FINALLY select the city which they had last selected.
All of this is forced on the user because another (possibly unrelated) field did not vaildate.
I tried $form->getValue('widget_name'), called immediately after $form->bind(), but it seems (infact, IIRC, if form fails to validate, all the values are reset to null) - so that does not work.
I am currently trying a nasty hack which involves the use of directly accesing the input (i.e. tainted) data via $_POST, and setting them into a flash variable - but I feel its a very nasty hack)
What I'm trying to do is a common use case scenario - is there a better way to do this, than hacking around with $_POST etc?
What I do for this exact issue is that I post the form to the same action that generated it, and in that action, I grab any selected countries/regions/cities as POST variables and pass them back to the template (regardless of validation). In the template, I then use JQuery to set the select values to what they were. When validation passes, they get used. When not, they get passed back to template.
If you can tolerate a little PHP in your JQuery, you could do this in the template:
$(document).ready(function()
{
$("#country-select").val('<?php echo $posted_country; ?>');
});
If you use this approach, don't forget to initialise $this->posted_country in your template the first time around or Jquery will get confused.
I guess you could also use $this->form->setWidget(...)->setDefault(...) or something similar, but I havent found a way around using $_POST as accessing the elements seems to need binding the form otherwise.
UPDATED CODE IN RESPONSE TO COMMENTS BELOW:
if($_POST['profile']['country_id'] != '')
{
$this->posted_country = $_POST['profile']['country_id'];
$q = Doctrine_Query::create()
->select('c.city_id, c.city_name')
->from('City c')
->where('c.country_id = ?', $this->posted_country);
$cities = $q->execute(array(), Doctrine_Core::HYDRATE_NONE);
foreach($cities as $city) $list[$city[0]] = $city[1];
$this->form->setWidget('city_id', new sfWidgetFormChoice(array('choices' => array('' => 'Please select') + $list)));
}
So... I get the country from the post, I query db with that, get cities, and craft cities back into a dropdown. Then in the template, you can set a default selected city with something like $this->posted_city (which would be a POST variable too, if exists).

Drupal 6 Validation for Form Callback Function

I have a simple form with a select menu on the node display page. Is there an easy way to validate the form in my callback function? By validation I don't mean anything advanced, just to check that the values actually existed in the form array. For example, without ajax, if my select menu has 3 items and I add a 4th item and try to submit the form, drupal will give an error saying something similar to "an illegal choice was made, please contact the admin."
With ajax this 4th item you created would get saved into the database. So do I have to write validation like
if ($select_item > 0 && $select_item <= 3) {
//insert into db
}
Or is there an easier way that will check that the item actually existed in the form array? I'm hoping there is since without ajax, drupal will not submit the form if it was manipulated. Thanks.
EDIT:
So I basically need this in my callback function?
$form_state = array('storage' => NULL, 'submitted' => FALSE);
$form_build_id = $_POST['form_build_id'];
$form = form_get_cache($form_build_id, $form_state);
$args = $form['#parameters'];
$form_id = array_shift($args);
$form_state['post'] = $form['#post'] = $_POST;
$form['#programmed'] = $form['#redirect'] = FALSE;
drupal_process_form($form_id, $form, $form_state);
To get $_POST['form_build_id'], I sent it as a data param, is that right? Where I use form_get_cache, looks like there is no data. Kind of lost now.
Since you're already using AJAX, why not just write a bit of jQuery to only allow form submission if the choice is within the list of legal choices? This can be done within the custom module it already looks like you're working on (using drupal_add_js()).
It is not especially 'easy', but the standard way to do it would be to use Drupals Forms API for the callback submission as well - that way, you'll get the same validation that would happen on a non js submit.
Take a look at Adding dynamic form elements using AHAH. While it does not match your scenario exactly (they rebuild the form on the callback to add new elements, not to save data), the explanation of the processing workflow is pretty helpful.
Then there are several modules that try to offer AJAX form submission in a generic way - you could check their code on how to do it (or maybe just use them ;)
Ajax submit (only has a dev version)
Ajax (has an 'official' release)
Finally, there are efforts to put better support this functionality into core in Drupal 7 - the related discussions might also help.

Categories