I have a user profile update page, which pre-populates the text fields with the users information gathered from $this->request->data. Everything works fine, except the password field is pre-populated with what appears to be the encrypted password from the database, so on save, it fails the validation as the password exceeds the number of characters allowed, and even if it stores, it will then replace the users actual password with the encrypted same password, if that makes sense.
What would be the best work-around for this?
Controller:
public function profile() {
if($this->request->is('post') || $this->request->is('put')) {
if($this->Auth->user("id") == $this->request->data['User']['id']) {
$this->request->data['User']['user_status_id'] = $this->Auth->user("user_status_id");
$this->request->data['User']['user_type_id'] = $this->Auth->user("user_type_id");
if($this->User->save($this->request->data)) {
$this->Session->setFlash('Your profile has been updated','default',array('class'=>'success'));
} else {
$this->Session->setFlash("An error has occured updating your profile.");
}
} else {
$this->Session->setFlash("Unable to save this result as there is an ID mismatch.");
}
} else {
$this->request->data = $this->User->read(null,$this->Auth->user("id"));
}
}
View:
<h1>Profile</h1>
<h3>Update your profile</h3>
<div class="left">
<div class="formContainer">
<?php
echo $this->Form->create('User');
echo $this->Form->input('username',array("id" => "profileUsername"));
echo $this->Form->input('password',array("id" => "profilePassword"));
echo $this->Form->input('company');
echo $this->Form->input('first_name');
echo $this->Form->input('last_name');
echo $this->Form->input('telephone');
echo $this->Form->input('fax');
echo $this->Form->input('id',array('type' => 'hidden'));
echo $this->Form->end(__('Update'));
?>
</div>
</div>
The problem you have is, if you have stored your password as you should (with a one way hash), you can't reverse it to show the plain text version so you could simply set the password data to null (leaving the password field empty):
$this->request->data['User']['password'] = NULL;
You then have two options:
Require the users password to update their data (a nice little security measure)
Only update the users password when the user has entered a new password
The 2nd option may break your validation if you have set password validation rules to allowEmpty => false, in this case you could use multiple validation sets which you can do by following either of these (all work in cakephp 2.x) multivalidateable behaviour, multiple validation sets
read this and use this behavior:
http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp
the password is a one-way ticket - due to the technical details of hashs.
basically you never pass the password hash back into the view. always display empty fields (like you should have seen on pretty much every other website in the www).
you then ignore and posted field which is empty. only if the password field is freshly set you actually trigger the validation.
<?php echo $this->Form->input('password', array('label' => false,'type'=>'password','required'=>'false')); ?>
Output
<input name="data[User][password]" type="password" id="UserPassword">
Be careful! use this only on the edit part
$this->Form->input('password',array('value'=>null));
Related
I have a page where there are multiples forms generated with the FormHelper that aim at modifying the same entity. The problem is: validation errors will show up on both forms.
With cakephp 2, this problem was solved by extending Models (see : http://bakery.cakephp.org/articles/RabidFire/2010/06/26/multiple-forms-per-page-for-the-same-model ).
However I don't see how to do this with cakephp 3.
EDIT: i'm gonna describe more precisely what I'm trying to do.
I have two forms on the same page. The first one enables a user to change his email address, the other one to change his password.
Both forms are created with the Form helper and the same user entity.
In both forms, there is a field where the user should enter his current password (as a security measure). A validator will check if the password entered is correct before letting the email or the password to be changed.
Problem: let's say the user tries to change his email but typed a wrong password, the "wrong password" message will appear on both forms.
This is sort of an edge case that the FormHelper is not ready to handle graciously. But this is a solution, you will need 2 entities:
$user = $this->Users->get($id);
$user->unsetProperty('password');
$clonedUser = clone $user;
$this->set(compact('user', 'clonedUser'));
In your view, you build your forms in a way that you can detect which entity you should pass:
echo $this->Form->create($this->request->data('_form1') ? $user : $clonedUser);
... fields here
echo $this->Form->hidden('_form1', ['value' => 1]);
echo $this->Form->create($this->request->data('_form2') ? $user : $clonedUser);
... fields here
echo $this->Form->hidden('_form2', ['value' => 1]);
What the above code does is detecting which of the forms was previously submitted and render the form with either the empty cloned entity or the entity having the errors.
Stumbled upon this because I had the same requirement. I would go with José but move the logic to the Controller instead:
$callback = $this->Inquiries->newEntity();
$inquiry = $this->Inquiries->newEntity();
if ($this->request->is('post')) {
if ($this->request->data('_type') === 'callback') {
$callback = $this->Inquiries->patchEntity($callback, $this->request->data, ['validate' => 'callback']);
$entity = &$callback;
} elseif ($this->request->data('_type') === 'inquiry') {
$inquiry = $this->Inquiries->patchEntity($inquiry, $this->request->data);
$entity = &$inquiry;
}
if (!$entity->errors()) {
// do stuff here
}
}
$this->set(compact('callback', 'inquiry'));
Pass the type of the form:
echo $this->Form->input('_type', ['type' => 'hidden', 'value' => 'inquiry']);
I have following form field in a registration form in cakephp. I want to make it 'hard-coded', so user can't edit it
echo $form->input('name', array('label' => __('Name *', true)));
Then don't add it to the form.
Those fields should be added in the controller (or even beforeValidate/beforeSave model layer) then right before saving:
if ($this->request->is('post')) {
$this->User->create();
// add the content before passing it on to the model
$this->request->data['User']['status'] = 1;
if ($this->User->save($this->request->data)) {
...
}
}
See "default values - hidden" here.
You can set the readonly property:
echo $form->input('name', array('label' => __('Name *', true), 'readonly' => true));
However, this only affects the UI, and so you still have to apply mark's answer to ensure the value doesn't get changed by the user.
Two options:
hard code the value before the save
use white list
If you want the field to be a read-only, from the moment it is set. use white list. this way - it doesn't matter if the user will submit the field or not. cake won't save it.
$white_list = array('title', 'category');
$this->Model->save($data,$validate,$white_list);
The other solution is as mark coded it:
$this->request->data['User']['status'] = 1;
if ($this->User->save($this->request->data)) {
...
}
Any solution should mix a UI indication that the field will not be changed. tho a good UX will not allow it in the first-place.
My Goal:
Reuse of a contact form to be related to several different entities I call "Parents" ie Group has contact information, Member has contact info etc....
The way I tried doing it was:
1. Creating a view file for contact, named "form.ctp" which doesn`t create a new form, nor submits, just echo's the contact's fields.
2. Calling this file using requestAction
My Problem:
The form's _Token get crumbled.
Parent add.ctp example
<?php echo $this->Form->create('Group');?>
<fieldset>
echo $this->Form->input($field_prefix.'contact_id',array('type'=>'hidden'));
<?php echo $this->requestAction(array('controller' => 'contacts', 'action' => 'form'), array('named' => array('index'=>'0','parent'=>'Group',
'fields'=>array(
'email'=>array('value'=>'xx#yy.com','hidden'=>1)
))));
inside the form.ctp I have:
//Associated Model
echo $this->Form->input('Contact.0.city',array('type'=>'hidden'));
echo $this->Form->input('Contact.0.postcode');
echo $this->Form->input('Contact.0.phone');
echo $this->Form->input('Contact.0.cellphone');
echo $this->Form->input('Contact.0.email',array('value'=>""));
echo $this->Form->input('Contact.0.id',array('type'=>'hidden'));
?>
Looking at the HTML source code that is generated, I see that whether I use the request action or just copy the contect of the form.ctp into the "Parent's" add file, I get the same HTML result.
HOWEVER!!! when I use the form.ctp Action Request, I get the blackhole, the tokens are being messed up!!!
Any Ideas?
Thanks in advance
Orly
If your problem is solely reusing a form, you can use the form as a Element, and then you could call it multiple times, substituting in the exact values you need.
As for SecurityComponent, I would recommend (at least as a temporary fix) disabling SecurityComponent for that specific action by using $this->Security->unlockedActions(); in your controller's beforeFilter()
I have a view file that looks like this:
<?php
echo $this->Form->create('ModelName');
echo $this->Form->input('ModelName.0.firstField');
echo $this->Form->input('ModelName.0.secondField');
echo $this->Form->input('ModelName.1.firstField');
echo $this->Form->input('ModelName.1.secondField');
echo $this->Form->end();
?>
My question is, how do I validate this data? I'm not saving, so it seems pointless to me to call the save or saveAll methods. I just want to validate the data before I process it and display the results to the user.
What happens currently using:
<?php
if ($this->request->is('post')) {
$this->ModelName->set($this->request->data);
if ($this->ModelName->validates()) {
echo $this->Session->setFlash('Success');
} else {
echo $this->Session->setFlash('Failure');
}
}
?>
Is it succeeds all the time even when I'm putting in data that should definitely fail.
I have also tried:
<?php
if ($this->request->is('post')) {
if ($this->ModelName->validateMany($this->request->data)) {
echo $this->Session->setFlash('Success');
} else {
echo $this->Session->setFlash('Failure');
}
}
?>
And that return success all the time as well, but that may be due to the fact that I don't know how to properly use validateMany.
Model::set is used for assigning a single set/record of data to the current instance of the Model. So it may be possible that you are only validating the first set of data in your POST data. You would have to iterate through each record in the POST data, Model::set it to the Model data, and then call Model::validates.
Instead of the above method or Model::validateMany, try using Model::saveAll without actually saving.
http://api20.cakephp.org/class/model#method-ModelsaveAll
validate: Set to false to disable validation, true to validate each record before saving, 'first' to validate all records before any are saved (default), or 'only' to only validate the records, but not save them.
<?php
if ($this->request->is('post')) {
if ($this->ModelName->saveAll($this->request->data, array('validate' => 'only'))) {
echo $this->Session->setFlash('Success');
} else {
echo $this->Session->setFlash('Failure');
}
}
?>
I am using an Account Controller which doesnt have its own table but uses User Model.
All works fine except - when I validate any form. It says validation fails (when I try to fail the validation to check) but doesnt throw the error below the field
View
<?php echo $this->Form->input('id'); ?>
<label for="UserPassword">New Password:</label>
<?php echo $this->Form->text('password', array('type' => 'password', 'value' => 'harsha')); ?><em>Password must be min 6 characters.</em> <?php echo $form->error('password'); ?>
Controller Action
if($this->User->saveField('password', $this->data['User']['password'], array('validate' => 'first'))) {
$this->Session->setFlash('Password has been changed.', 'flash-success');
} else {
$this->Session->setFlash('There was some problem with our system. Please try after some time.', 'flash-warning');
}
Try debug()ing the contents of $this->validationErrors in your view, as well as $this->data in your controller just after a form submission. This should give you a lot more information to work from.
I suspect that your problem is Cake is building form inputs based on the wrong model -- building form fields for Account.id and Account.password instead of User.id and User.password. This is because FormHelper takes its default model from the controller/view it's invoked from, which in your case appears AccountsController.
In order to generate the User.id and User.password fields your controller's submission handling expects, you'll need to prepend User. in your FormHelper calls. Thus:
$this->Form->input('User.id');
$this->Form->text('User.password');
Have you tried:
echo $session->flash();
Note that whatever the manual says, it returns, not echoes. I logged this a while back and it has been changed in the 1.3 manual, but not the 1.2.
Hi you who's asking If you want to show error-message that return from UserModel's validate So you can add line code bellow after input form password
<?php
if ($this->Form->isFieldError('password')) {
echo $this->Form->error('password', array('class' => 'error'));
?>
and if you want to show error-message that set by method setFlash
you must redirect page and then use $this->Session->flash('flash-name') in page you want to show it
<?php
//in UsersController
$this->Session->setFlash('message here', 'flash-name');
//in view
echo $this->Session->flash('flash-name');
?>
Good luck!