Cakephp Validation - cakephp

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!

Related

cakephp getLastInsertId not working

Here I have used cakephp js helper to send data,After insert One data I need this last id for farther work.Here I have tried bellow code in Addcontroller
if ($this->Patient->save($this->request->data)) {
$lastid=$this->Patient->getLastInsertId();
$patient=$this->Patient->find('all',array(
'conditions'=>array('Patient.id'=>$lastid ),
'recursive' => -1
));
$this->set('patient', $patient);
}
In add.ctp I have tried bellow code but I haven't get last id here.
<?php foreach ($patient as $patient): ?>
<?php echo h($patient['Patient']['id']); ?>
<?php endforeach; ?>
Method getLastInsertId() return id of just saved records.
If you need this id in your view just after save, you must first set that variable in your controller like $this->set(compact('lastid','patient'); and then use in view <?php echo $lastid; ?>
use
if ($this->Patient->save($this->request->data)) {
$id = $this->Patient->id;
$patient=$this->Patient->find('all',array('conditions'=>array('Patient.id'=>$id),'recursive' => -1));
$this->set->('patient', $patient);
//If you are saving the record with ajax which it looks like you
//might be from your question you will need the following instead
//of $this->set->('patient', $patient); try:
return json_encode($patient);
You will then also need to update your js ajax call, you will have a json array to decode so parse it with jquery and append it back into your view.
Cake will always give you the id of record you have just saved, by simply adding $id = $this->MyModel->id; You can use the id to query for the record.
Try below code:
In controller:
$lastid=$this->Patient->getLastInsertId();
$this->set(compact('lastid','patient');
Then use $lastid in View file.
In controller:
$lastid=$this->Patient->getLastInsertId();
$patient['Patient']['last_id'] = $lastid;
then use $patient['Patient']['last_id'] in your view file.

blackhole cakephp 2 associated entities

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

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

how to create form in cake php

I am very new in cake php, i want to know how to create form in cake php,please describe,when we go to create a form then what i have to do,like create model and controller everything
In the view file, something like this would work:
<?php
echo $this->Form->create();
echo $this->Form->input('firstname', array('label' => 'Enter your first name:'));
echo $this->Form->input('email', array('label' => 'Enter your email address:'));
echo $this->Form->input('password', array('label' => 'Enter your password:'));
echo $this->Form->end('Save');
?>
In your controller:
if($this->request->is('post')){
$this->User->save( $this->request->data );
}
You can apply some sort of validation in your model, look in the documentation for that.
Best option to learn about cakephp is it's own doc book
But I'm providing you some basic code to create form :
$this->Form->create('ModelName');
$this->Form->input('ModelName.fieldname', array('type'=>'text', 'label'=>'Modified-Name'));
$this->Form->end(__('Submit'));
Here array('type'=>'text'...): type shows which type of input field you want.
(...'label'=>'Modified-Name'): By default it shows field text as fieldname but by using 'label' you can modify your field text.
$this->form->create('controlpage',
array(
'action'=>'controll',
'class'=>'class',
'enctype' => 'multipart/form-data',
'onsubmit'=>'return valid()'
));
Block quote
Create form in html save it as ctp
Block quote
And call it in view. enter code hereUse cake php book to read further.

cakePHP basic ajax form problem

i am trying to do a simple form that adds a new comment using ajax to a blog post (actually this is a part of a cakePHP tutorial)
but the problem is that the submit button do nothing at all
here is the part of code that generates the form in the view.ctp file
<?php echo $ajax->form('/comments/add', 'post', array('url' => '/comments/add', 'update' => 'PostsComments', 'indicator' => 'commentSaved'));?>
<fieldset>
<legend><?php __('Add Comment');?></legend>
<?php
echo $form->hidden('Comment.post_id', array('value' => $post['Post']['id']));
echo $form->input('Comment.name');
echo $form->input('Comment.content');
?>
</fieldset>
<?php echo $form->end('Submit');?>
and here is the add comment action in the comments_controller.php
if (!empty($this->data)) {
$this->Comment->create();
if ($this->Comment->save($this->data)) {
$comments = $this->Comment->find('all',array('conditions'=>array('post_id'=>$this->data['Comment']['post_id']),'recursive'=>-1));
$this->set(compact('comments'));
$this->render('add_success','ajax');
} else {
$this->render('add_failure','ajax');
}
}
the problem is that the action add isnt called from the view ... when i viewed the generated html source code i found something like that
<form id="form304217296" onsubmit="event.returnValue = false; return false;" method="post" action="/php-cake/blog/comments/add"><fieldset style="display:none;">
if i removed the on submit tag manually then the action is called but the add_success.ctp is generated as a new page not as an ajax call.
so what could be the problem ?
finally i have discovered the problem
there was more than one mistake in the tutorial (chapter 8 in CakePHP from novice to professional) after fixing those errors i found another problem is that cakephp v1.2.6 is not compatible with the latest version of prototype (v1.6.1)
as it gives the following error in firebug
Event.observe is not a function
so i used version 1.6.0.3 of prototype and the problem was solved.
for a list of mistakes in this chapter see this
Do you include prototype and scriptaculus in your View/Layout (both are needed for the Ajax-helper)? Also there might be an interference with jquery if you use that too

Resources