Zend Framework POST data is not displayed or processed - php

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

Related

CakePHP 4 - setting request data

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')).

Symfony2: doing form validation before the form is posted

Going to try my best to explain this...
In my app I have the need to display the validation errors on a form when the user loads the form initially. In short, they've entered data and saved it, but now the data has been checked and we've detect errors they need to correct before they can fully submit the form. (It's multi step form that can be filled out over multiple sessions...think big.)
Previously I was doing something like:
THIS DOESN'T WORK IN SYMFONY >=2.8.10 See this answer
$entity // passed in as param on action method
$form = $this->createForm(..., $entity);
$csrfToken = 'random_string'; // retrieved from FormConfigInterface
// perform the submit but don't clear missing
$form->submit(['_token' => $csrfToken], false);
This was working, but seems to have broken in Symfony 2.8.10+, but works in 2.8.9. In 2.8.10+ there are no validation errors (the form is considered valid).
I'm able to retrieve the validation errors in a ConstraintViolationListInterface, but I can't find a way to "merge" that with the form (which I think would be the prefered way). Since I couldn't, I tried the above which "fake" submits the form...which seems like a bad idea.
Is there a better/proper way?
(Note: the form is much more complicated and includes validation groups...but I'm not concerned about that or the error in 2.8.10+ at this point.)

Getting data from a database in a datetimelocal form element on Zend framework2

I've a form set up using Zend Framework 2 with an element type 'DateTimeLocal'
When I add a new record using the form all works well.
When I edit a record the form appears to fill out correctly: I've formatted the data to pass to the form using:
$this->startDate = (!empty($data['startDate'])) ? date("Y-m-d\TH:i:s",strtotime($data['startDate'])) : null;
and in the view add using:
echo $this->formRow($form->get('startDate'));
However when I go to submit the form having made edits, I get the message 'The input does not appear to be a valid date'. Using the chrome I re-enter the date, and it appears identical to what was pre-filled, but then submits fine.
html source rendered by zendframework is:
<label><span>Start Date</span><input type="datetime" name="startDate" value="2014-12-21T00:00:00"></label>
I'd have thought this was a common action but seam to be struggling to find examples.
I am not totally sure and a bit surprised by this issue. But the value 2014-12-21T00:00:00 seems to be an html encoded version of 2014-12-21T00:00:00 and it might be that submitting this is resulting in an invalid response.
I don't know exactly how this value got there, but you should try to get a not encoded value set for startDate, then your form might work as expected.
I eventually stumbled across https://stackoverflow.com/a/32003481/1836257
My date format was incorrect. I should have used
$this->startDate = (!empty($data['startDate'])) ? date("Y-m-d\TH:i",strtotime($data['startDate'])) : null;

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.

HttpWebRequest POST and retrieve data from php script after login

Hello guys i am newbie to this stuff so i'll try to explain my problem.I am building application that retrieve data after login to php script that looks like this:
https://zamger.etf.unsa.ba/getrssid.php
(see the page source for php scirpt definition)
and definition(source) here:
Korisničko ime (UID):
Šifra:
After i login it shows me data that i must collect like this:
RSSID: 1321B312 (this is only data that it shows and nothing else)
I must do this with httpwebrequest but don't know how i tried to do it with POST(data) but it always give me the defnition of php script as response.But i need response to be like "RSSID: 1321B312" not as script definition mentioned above...please heeelp ASAP....
Define a form action to begin. So if the same page, getrssid.php, will be processing the form, use:
<form action="getrssid.php" method="POST">
After that, you must code getrssid.php to accept the incoming data via POST. POST data is stored in the PHP variables $_POST['inputname']. So if you have the input name as "login", the value entered will be stored in $_POST['login']. Same thing applies for the password.
So, here's a sample of what a basic POST data handling script should look like. Note that this script does not verify the login credentials, sanitize the inputs, or anything of the sort. It is just to show you how to handle POST DATA.
<?php
if (isset($_POST['login']) && isset($_POST['pass'])){
// Form is submitted.
echo 'RSSID: 1321B312';
} else {
// Form is not submitted.
// Display Form.
echo 'Form HTML here';
}
?>
If you are really server conscious, you should put the if ... else statement in the opposite order so the most likely outcome (form not submitted) is evaluated first.
Merry Christmas!

Categories