Cakephp 3 : Multiple Forms per page for the same model - cakephp

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']);

Related

hard-code Form input field in cakephp so user can't edit it?

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.

Creating muliple users in a loop from array

How does one go about creating multiple new users, say in a loop, from an array in a different controller?
I have an issue where attempting to create multiple users in a form submit fails, but creating a single new user works as designed. It appears the issue may be when saving the new user and then bringing the new user_id back in the return statement. Although the new id comes back, subsequent users (2nd, 3rd, etc) all get the same id value, and it appears that the subsequent $this->save calls modify the first created user rather than create add'l ones. Any none of the new users appear in the database. (again, the problem only happens when more than one new users will be created.)
My one small clue is that if I var_dump($user) in my importPublicLDAPUser() function (user.php) just after the $user = $this->save(array('User' => array( ... ))); then for the first element I see both 'modified' and 'created', whereas I see only 'modified' for the rest. This leads me to believe there's a step missing, like the user needs to be saved or commit (??) before the next user can be be created.
I tried changing this to $user = $this->User->save(array('group_id' => 3, ... and adding a 'create' before: $this->User->create(); but these produce errors 'Call to a member function save() on a non-object' and 'Call to a member function create() on a non-object'.
My application manages documents. Each document can have many authors, so it has controllers for: docs, doc-types, users, groups, and authors.
When a new document is entered, the form allows selection of multiple users to create 'Author' records. In addition to the local users table, it also searches our LDAP server (both via auto-sugggest) and also allows input into a text field. So, Authors are selected from
the existing table of users
via the LDAP helper
free text entry.
This result is two arrays: $Authors (from local users tables), and $badAuthors (LDAP and text-input) which the app then tries to add to the local users table when the form is submitted.
The form works just fine if:
one or more authors are added from local users table;
a single author is added from LDAP (succeeds in creating a new entry in users table), and zero or more local users
a single author is added from text input (also succeeds), and zero or more local users
However if two or more non-local users are added ($badAuthors has more than one element) then the form fails. "fails" means that either the Author or User save routine failed, and so it skips the Document commit $this->Docu->commit(); and I spit out an error via ajaxResponse. Thus, the app works as designed, but only with one new User entry at a time, even though the form is designed to allow Authors/badAuthors to be >1.
What I don't understand is why when I loop through bad authors why it doesn't correctly add the users if $badAuthors has more than one element.
As the user enters each name (which is checked against the users table and LDAP via ajax helpers, etc) and then selected, an author_name_list array is built. And then:
foreach($this->params['form']['author_name_list'] as $author_name){
$user_id = $this->Docu->User->field('id',array('User.name' => $author_name));
if($user_id){
$Authors['Author'][]=array(
'docu_id'=>$this->Docu->id
,'user_id'=>$user_id
);
}else{
$badAuthors[] = array('name'=>$author_name);
}
}
So $badAuthors is now those found in LDAP or entered manually.
So now I try to create/save all badAuthors...
docu controller (docu_controller.php):
if(count($badAuthors)){
foreach($badAuthors as $key => $author){
$this->Memo->User->create(); // ** <-- this was missing!! **
if($ldap_author = $this->Docu->User->importPublicLDAPUser($author['name'])){
unset($badAuthors[$key]);
$Authors['Author'] []= array(
'docu_id'=>$this->Docu->id
,'user_id'=>$ldap_author['User']['id']
,'precedence' => $author['precedence']
);
} elseif ($new_author = $this->Docu->User->newReadonlyUser($author['name'])) {
unset($badAuthors[$key]);
$Authors['Author'] []= array(
'docu_id'=>$this->Docu->id
,'user_id'=>$new_author['User']['id']
,'precedence' => $author['precedence']
);
}
}
}
if(!count($badAuthors)){
$authors_saved = true;
foreach($Authors['Author'] as $author_arr){
$this->Docu->Author->create();
if(!$this->Docu->Author->save(array('Author' => $author_arr))){
$authors_saved = false;
break;
}
}
}
user model (user.php)
function afterSave($created) {
if (!$created) {
$parent = $this->parentNode();
$parent = $this->node($parent);
$node = $this->node();
$aro = $node[0];
$aro['Aro']['parent_id'] = $parent[0]['Aro']['id'];
$this->Aro->save($aro);
}
}
function importPublicLDAPUser($cn){
App::import('Vendor','adLDAP',array('file'=>'adLDAP.php'));
$oLDAP = new adLDAP(Configure::read('LDAP_options.email'));
$oLDAP->authenticate(NULL, NULL);
$filter = '(&(cn='.$oLDAP->ldap_escape($cn).'))';
$ldap_res = #$oLDAP->search($filter, array('cn', 'uid','profitcenter'),1);
if(isset($ldap_res['count']) && ($ldap_res['count'] > 0)){//found it
$user = $this->save(array('User' => array(
'group_id' => 3,
'name' => $ldap_res[0]['cn'][0],
'username' => $ldap_res[0]['uid'][0],
'grpnum' => pc2grpnum($ldap_res[0]['profitcenter'][0])
)));
if($user){
$user['User']['id'] = $this->id;
}
return ($user ? $user : false);
}else{
return false;
}
}
Any suggestions? Thanks!!
It turns out that in my docu_controller.php I was missing a create() call. It seems that without a create, an object can still be saved/created when the other controller does a commit(). So before adding the create(), prior to the commit, in later loop iterations I was still modifying the original object, not any new ones. By adding a create in the controller, the save in the method function acts on the new user for each loop iteration.
in controller:
if(count($badAuthors)){
foreach($badAuthors as $key => $author){
$this->Memo->User->create();
if($ldap_author = $this->Memo->User->importPublicLDAPUser($author['name'])){
in method:
function importPublicLDAPUser($cn){
....
$user = $this->save(array('User' => array(...

cakePHP pre-populates password field and breaks on update

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));

CakePHP controller name in behavior

I created relation Post hasMany Photos, Photos actsAs ImageBehavior.
How put to $data['Photo']['model'] = 'Post'? Automated?
I'm not sure what you are asking about but when you have a form, you can simply add to your $this->data['Photo']['model'] any value you want with hidden fields.
// photo/add.ctp:
$this->Form->create('Photo');
$this->Form->input('model', array('type' => 'hidden', 'value' =>'yourvalue'));
$this->Form->end('Submit');
Update
You can set this value after the form was submitted, so even if someone will replace the hidden field value you can just check it.
function add(){
if(!empty($this->data['Photo']['model']){
$this->data['Photo']['model'] = "yourvalue";
$this->Photo->save($this->data));
}
else
rest of the code...
}
rest of the code

Cakephp Validation

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!

Resources