cakephp update data - cakephp-2.1

I have 2 tables in a database: User and Profile.
In a page i want to see all user with its profile associated by user_id.
The problem is when i update the records cakephp update only the table user and don't the profile table.. Now i'm very confused but this is my code to update in the UsersController
$this->User->id = $this->request->data['User']['id'];
if (!$this->User->exists()) {
$this->Session->setFlash('Nessun utente trovato con questa corrispondenza');
}
if ($this->User->save($this->request->data)) {
$this->Session->setFlash('Modifica avvenute con successo');
$this->redirect(array('action'=>'index'));
}
else {
debug($this->User->invalidFields());
$this->Session->setFlash('Errore di salvataggio dati, prova di nuovo');
}
$this->redirect(array('action'=>'index'));
and this is my User model:
class User extends AppModel{
public $name = 'User';
public $hasOne = array(
'Profile' => array('className' => 'Profile',
'conditions' => '',
'dependant' => true,
'foreignKey' => 'user_id',
'associatedKey' => 'user_id'
)
);
public $validate = array(
'username' => array(
'non_vuoto' => array(
'rule'=> 'notEmpty',//non è vuoto metodo che eredito da appmodel
'message'=> 'Lo username non può essere vuoto'
),
'stringa_alfanumerica' => array(
'rule'=> 'alphaNumeric',//alpha numerico
'message'=> 'Lo username deve essere alfanumerica'
)
),
'password' => array(
'non_vuoto' => array(
'rule'=> 'notEmpty',//non è vuoto metodo che eredito da appmodel
'message'=> 'La password non può essere vuota'
),
'min_lunghezza' => array(
'rule' => array('minLength',5),
'message' => 'La password deve contenere almeno 5 caratteri'
),
'max_lunghezza' => array(
'rule' => array('maxLength',15),
'message' => 'La password deve contenere al massimo 15 caratteri'
),
'password_uguale' => array(
'rule' => 'matchPasswords',
'message' => 'Le password inserite non coincidono'
)
),
'password_confirm' => array(
'non_vuoto' => array(
'rule'=> 'notEmpty',//non è vuoto metodo che eredito da appmodel
'message'=> 'La password non può essere vuota'
)
),
'email' => array(
'email_non_valida' => array(
'rule' => 'email',
'message' => 'L\'email inserita non è valida'
),
'email_univoca' => array(
'rule' => 'isUnique',
'message' => 'Questa email inserita è già presente nel database'
)
),
'activation_key' => array(
'stringa_alfanumerica' => array(
'rule' => 'alphaNumeric',//alpha numerico
'message'=> 'La chiave di attivazione non è valida'
),
'lunghezza campo' => array(
'rule' => array('between',40,40),
'message'=> 'La chiave di attivazione non è valida'
)
),
'url' => array(
'url' => array(
'rule' => array('url',true), //invalida i protocolli http e https
'allowEmpty' => true, //dico che può essere anche vuoto
'message' => 'L\'url inserito non è valido'
)
),
'description' => array(
'max_lunghezza' => array(
'rule' => array('maxLenght',100),
'allowEmpty' => true,
'message' => 'La descrizione è troppo lunga'
)
)
);
//metodo mio dichiarato
public function matchPasswords($data){
//Il primo dato non è criptato se è nella variabile data se utilizzavo il this lui vede il campo password e quindi prendo il campo che ho diciharato
if ($data['password']==$this->data['User']['password_confirm']){
return true;
}
//mando l'errore se non coincidono gli dico invalidami quel campo
$this->invalidate('password_confirm','Le due password non coincidono');
return false;
}
//metodo automatico non necessario avviene sempre prima del salvataggio in questo caso
public function beforeSave(){
//se trova il campo password cripta
if (isset($this->data['User']['password'])){
$this->data['User']['password']=AuthComponent::password($this->data['User']['password']);
}
return true;
}
}
?>
I can't update my user's profile why?
i have try to create the model for the Profile like this but nothing
class Profile extends AppModel{
public $name = 'Profile';
var $belongsTo = array('User' =>
array(
'foreignKey' => 'user_id'
)
);
}
Help me please

In the topmost code block you aren't making any references to the profile, so it is only right, that you don't update anything.
At least you have to have something like this:
loadModel("Profile"); //not necessary
$this->Profile->find('first', array('conditions' => array('user_id'=>'user_id')));
$this->Profile->save($data_you_want_to_save);
If this didn't help, I recommend posting the whole function code like this and clarifying your problem:
public function update($user_id) {
*your code should be here so we know what function you are in*
}
Also you might want to reread the blog tutorial. I pointed you right to a good example of a simple edit function.

Related

CakePHP load model validation rule not working

I am loading a model in different controller.
Controller name in which I am loading different model is - "MembersController" and I am loading "Usermgmt" Model of "UsermgmtController".
"Usermgmt" Model has validation as following-
public $validate = array(
'email' => array(
'valid' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for email.'
),
'duplicate' => array(
'rule' => 'isUnique',
'on' => 'create',
'message' => 'This email is already exist.'
),
'duplicate1' => array(
'rule' => 'email',
'message' => 'Please enter valid email.'
)
),
'firstname' => array(
'valid' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for first name.'
)
),
'username' => array(
'valid' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for user name.'
),
'duplicate' => array(
'rule' => 'isUnique',
'on' => 'create',
'message' => 'This user is already exist.'
)
),
'password' => array(
'valid' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for password.'
)
),
'confirm_password' => array(
'valid' => array(
'rule' => 'notEmpty',
'required' => true,
'allowEmpty' => false,
'message' => 'Please enter a value for confirm password.'
),
'duplicate2' => array(
'rule' => 'matchpassword',
'on' => 'create',
'message' => 'Password must be same.'
)
)
);
And now I am applying and loading model in following way.
$this->loadModel('Usermgmt');
$this->Usermgmt->set($this->data);
if ($this->Usermgmt->validates()) {
if ($this->Usermgmt->save($data, true)) {
$userid = $this->Usermgmt->id;
$this->Session->setFlash('User has been added', 'success');
}
}
But validation are not working and it is inserting empty values.
try uses to load model
Example :
public $uses = array('Usermgmt');
You are using two different instances of $data. namely $this->data and $data
You should be validating the same set of data you want to save, like either of the two following examples, whichever holds your data.
$this->loadModel('Usermgmt');
$this->Usermgmt->set($data);
if ($this->Usermgmt->validates()) {
if ($this->Usermgmt->save($data, true)) {
$userid = $this->Usermgmt->id;
$this->Session->setFlash('User has been added', 'success');
}
}
Or
$this->loadModel('Usermgmt');
$this->Usermgmt->set($this->data);
if ($this->Usermgmt->validates()) {
if ($this->Usermgmt->save($this->data, true)) {
$userid = $this->Usermgmt->id;
$this->Session->setFlash('User has been added', 'success');
}
}
Unless you are requiring to do some other logic after validation and before saving you could do away with explicitly calling validates() and just save the data as save() will automatically validate the data for you. Also, I've noticed you are using $this->data, it looks like you are using CakePHP 2 in which case you need to use $this->request->data instead:-
$this->loadModel('Usermgmt');
if ($this->Usermgmt->save($this->request->data) !== false) {
$this->Session->setFlash('User has been added', 'success');
}
If this still fails then make sure you are not overriding beforeValidate() in your model in a way that would cause validation to break.

cakephp not validating select field

I just downloaded a fresh copy of cakephp version 2.3.0 and I am trying to validate a select field of a form that I have just created:
echo $this->Form->input('province_id', array('empty' => '- select -', 'options' => $options));
echo $this->Form->input('username');
And the validation:
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'province_id' => array(
'rule' => 'notEmpty',
'message' => 'Select something'
)
);
The username field is being validated correctly, but the province_id is being ignored. What can it be?
You should write like this:
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'province_id' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'Select something'
)
)
);
It looks like your form helper declarations are fine.
My experience with Cake shows that the validation is screwy when you start to mix the syntax (one of your fields has a nested array, while the other doesn't). I am sure there is some rhyme or reason to what is going on, but I haven't really dived that deep and usually just do trial and error.
Try this:
public $validate = array(
'username' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'A username is required'
),
'province_id' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'Select something'
)
);
Better late then never, try this:
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notEmpty'),
'message' => 'A username is required'
)
),
'province_id' => array(
'required' => array(
'rule' => array('myOwnValidationRule'),
'message' => 'Select something'
)
)
);
function myOwnValidationRule($data)
{
if($data["province_id"] != 'empty')
{
return true;
}
}

cakephp notempty and unique validation on field

I am working with cakephp. I need to add three validation on email field. First validation if email not given, second for valid email address, third if email address is given then it should be unique. Because its a signup form.
How I have add three validations on one field I try with the following code but it did not work for me.
public $validate = array(
'email' => array(
'email' => array(
'rule' => array('email'),
'message' => 'Invalid email address',
'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
)
),
'email' => array(
'rule' => 'isUnique',
'message' => 'Email already registered'
)
);
You have two identical indexes 'email' which PHP won't allow you. Change to something like:-
array(
'email' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Provide an email address'
),
'validEmailRule' => array(
'rule' => array('email'),
'message' => 'Invalid email address'
),
'uniqueEmailRule' => array(
'rule' => 'isUnique',
'message' => 'Email already registered'
)
)
);
Otherwise only one of your rules will be used.
As of cakephp 3.0 in the entities table it should look something like this
namespace App\Model\Table;
public function validationDefault($validator)
{
$validator
->email('email')
->add('email', 'email', [
'rule' => [$this, 'isUnique'],
'message' => __('Email already registered')
])
->requirePresence('email', 'create')
->notEmpty('email', 'Email is Required', function( $context ){
if(isset($context['data']['role_id']) && $context['data']['role_id'] != 4){
return true;
}
return false;
});
return $validator;
}
}
function isUnique($email){
$user = $this->find('all')
->where([
'Users.email' => $email,
])
->first();
if($user){
return false;
}
return true;
}
What version of Cakephp do you use?
Because I think if you use 2.3, it should be:
public $validate = array( 'email' => 'email' );
with the field email in your SQL table set as a primary key.

How do I validate multiple fields from a single location in CakePHP?

I wanna validate multiple fields at one place. So in a form I have included 4 fields
as follows
facebook_link
twitter_link
google_plus_link
linked_in_link
The user atleast type any one field of above. Please help me to get the solution like, the user types anyone of the links in the form.
you may add your own Validation Methods.
public $validate = array(
'facebook_link' => array(
'rule' => array('validateLink'),
'message' => '...'
),
'twitter_link' => array(
'rule' => array('validateLink'),
'message' => '...'
),
'google_plus_link' => array(
'rule' => array('validateLink'),
'message' => '...'
),
'linked_in_link' => array(
'rule' => array('validateLink'),
'message' => '...'
),
);
public function validateLink($link) {
$allFieldsAreEmpty = (
empty($this->data[$this->alias]['facebook_link']) &&
empty($this->data[$this->alias]['twitter_link']) &&
empty($this->data[$this->alias]['google_plus_link']) &&
empty($this->data[$this->alias]['linked_in_link'])
);
return !$allFieldsAreEmpty;
}
Hope this will work for you.
public $validate = array(
'facebook_link' => array(
'rule' => array('customValidation','facebook_link'),
'message' => 'Please enter facebook link.'
),
'twitter_link' => array(
'rule' => array('customValidation','twitter_link'),
'message' => 'Please enter twitter link.'
),
'google_plus_link' => array(
'rule' => array('customValidation'),
'message' => 'Please enter google plus link.'
),
'linked_in_link' => array(
'rule' => array('customValidation'),
'message' => 'Please enter linkedin link.'
),
);
function customValidation($data , $filed) {
if(empty($data[$filed])) {
return false;
}
return true;
}

CakePHP JSON Post validation not working?

I'm using CakePHP 2.1.1 and whilst my methods which use the form helper, for example my add method in my Users Controller validates correctly, I can't get my mobile_register method in the controller to validate, it saves even when data is missing.
This is my mobile_register method:
public function mobile_register() {
if ($this->request->is('post')) {
$jsonData = file_get_contents("php://input");
if(isset($jsonData) && !empty($jsonData)){
$data = json_decode($jsonData,true);
$data = $this->User->configureUser($data);
$this->User->create();
if($this->User->save($data)){
$jsonResponse = array('status' => 'OK', 'token' => $data['User']['token'], 'message' =>'SUCCESS');
}else{
$errors = $this->User->validationErrors;
$this->log($errors,'errors');
$jsonResponse = array('status' => 'ERROR','message' => $errors);
}
}
}else{
$jsonResponse = array('status' => 'ERROR','message' => 'API method expects POST data');
}
$this->set('response' , $jsonResponse);
}
I've been using curl to test my method and it always saves despite post the following data:
[User] => Array
(
[firstname] => Andy
[token] => cc42030bbb49faf2cf0393418036e44f
[role] => user
)
curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"User":{"firstname":"Andy"}}' url/users/mobile_register
My validation rules in my model are:
public $validate = array(
'username' => array(
'username-1' => array(
'rule' => array('notempty'),
'message' => 'Username is required',
),
'username-2' => array(
'rule' => 'alphaNumeric',
'message' => 'Usernames must only contain letters and numbers.',
),
),
'password' => array(
'password-1' => array(
'rule' => array('notempty'),
'message' => 'Password is required',
),
'password-2' => array(
'rule' => array('between', 5, 15),
'message' => 'Passwords must be between 5 and 15 characters long.',
),
),
'firstname' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Forename is required'
),
),
'surname' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Surname is required',
),
),
'email' => array(
'email-1' => array(
'rule' => 'notempty',
'message' => 'Email is required',
),
'email-1' => array(
'rule' => 'email',
'message' => 'Please enter a valid email',
)
)
);
Am I missing something?
Perhaps a better approach to this solution would be to make a good use of the "required" and "allowEmpty" validation options:
CakePhp's data validation
This is what solved my problem, I thought it was related with the way I was requesting the action, but instead it was that I wasn't even setting the fields I wanted to validate.
I figured it out. Basically I learnt that if you don't pass the fields then they will not be validated.

Resources