Sorry before, i have a function add answer for answering question in my article, so when user add answer for a question, system will sending an email to user who wrote this question. This is my function in controller :
public function add($question_id = null) {
if ($this->request->is('post')) {
$this->loadModel('Question');
$this->Answer->set(array('question_id'=>$question_id));
$this->Answer->create();
$user = $this->Question->find('all',array('fields' => 'Useri.email',
'joins' => array(array('conditions' => array('Useri.id = Question.user_id'),
'table' => 'users',
'alias' => 'Useri',
'type' => 'INNER'))));
$email = new CakeEmail();
$email->config('server');
$email->template('answer');
$email->viewVars(array(
'to'=>$user['User']['email']
));
$email->to($user);
$email->from(array('gais#wahanaartha.com' => 'IT Sharing Knowledge Team'));
$email->subject('Sharing Knowledge Notification');
$result=$email->send();
if ($this->Answer->save($this->request->data)) {
$this->Question->updateAll(array('Question.status' => '1'),
array('Question.id' => $question_id));
$this->Session->setFlash(__('The answer has been saved.'));
return $this->redirect(array('controller' => 'questions', 'action' => 'view', $question_id));
} else {
$this->Session->setFlash(__('The answer could not be saved. Please, try again.'));
return $this->redirect(array('controller' => 'questions', 'action' => 'view', $question_id));
}
}
$questions = $this->Answer->Question->find('list');
$users = $this->Answer->User->find('list');
$this->set(compact('questions', 'users', 'tests'));
}
<?php
App::uses('AppModel', 'Model');
class Question extends AppModel {
public $validate = array(
'topic_id' => array(
'rule' => 'numeric',
'required' => true,
'message' => 'Topic must be choosen !'
),
'user_id' => array(
'rule' => 'numeric',
'required' => true,
'message' => 'User must be choosen !'
),
'question' => array(
'minLength' => array(
'rule' => array('minLength', 12),
'required' => true,
'message' => 'Question min. 12 characters !'
),
'unique' => array(
'rule' => array('checkUnique', 'question'),
'message' => 'Question don\'t be same !'
)
),
'description' => array(
'minLength' => array(
'rule' => array('minLength', 12),
'required' => true,
'message' => 'Description min. 12 characters !'
),
'unique' => array(
'rule' => array('checkUnique', 'description'),
'message' => 'Description don\'t be same !'
)
)
);
public $belongsTo = array(
'Topic' => array(
'className' => 'Topic',
'foreignKey' => 'topic_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
public $hasMany = array(
'Answer' => array(
'className' => 'Answer',
'foreignKey' => 'question_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
function checkUnique($data, $fieldName) {
$valid = false;
if(isset($fieldName) && $this->hasField($fieldName)) {
$valid = $this->isUnique(array($fieldName => $data));
}
return $valid;
}
}
But when run this code, there is error "Invalid Email 'Array'", i have been check my query, when i run my query in navicat is fine, any help will be greatly appreciated
thanks
Concording with CakeEmail :
**to( ) public
To
Parameters
mixed $email optional null
Null to get, String with email, Array with email as key, name as value or email as value (without name)
string $name optional null
Returns
mixed
mixed**
So your $user array must like : ["email1#mail.com"=>"Name User", "email2#mail.com"=>"Name User2"]
or a string : "email#mail.com" .
Try this ! and tell me more about.
(try to set $email->to(array('mail#mail.com'=>'Name User') );
If isnt work , please tell us more about your bug
Related
I have a model that has a belongsTo variable, find and a afterFind all in play. The problem is, when the afterFind is commented out find works fine, but once its in play the find only returns "true", not an array of objects. If anyone has ran into this issue please inform me thx!
Model:
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'ContactCategory' => array(
'className' => 'ContactCategory',
'foreignKey' => 'contact_category_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'State' => array(
'className' => 'State',
'foreignKey' => 'state_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
public function getContact($id)
{
if ($id) {
$contact = $this->find('first', array('conditions' => array('Contact.id' => $id), 'fields' => array('id', 'image')));
return $contact;
} else {
return false;
}
}
public function afterFind($results = array(), $primary = false)
{
foreach ($results as $key => &$val) {
if (isset($val['Contact'])) {
$this->decryptFields($val['Contact'], $this->fieldsToEncrypt());
}
}
}
I have trouble with some validation errors in my Model. I lost much of my datas when an error is occured. I see that $this->request->data change like as he will be treated in the controller. But when an error occurs, I'm redirect to the view and i don't have the good "$this->request->data to display my view.
Please do you any solution?
Edit: With code from Model file. I add //BUG HERE to notify where $this->data->request is not re-set.
class Event extends AppModel {
public $hasMany = 'CategoryOptionEventEvent';
public $hasOne = array(
'CategoryVehicleEvent' =>
array(
//'className' => 'Event',
'joinTable' => 'category_vehicle_events',
'foreignKey' => 'id',
'associationForeignKey' => 'id',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'with' => ''
),
);
public $validate = array(
'name' => array('rule' => 'notEmpty'),
'description' => array('rule' => 'notEmpty'),
//'date' => array('rule' => 'notEmpty'),
'hour' => array('rule' => 'notEmpty'),
'street_number' => array('rule' => 'notEmpty'),
'street_name' => array('rule' => 'notEmpty'),
'postal_code' => array('rule' => 'notEmpty'),
'city' => array('rule' => 'notEmpty'),
//BUG HERE
'vehicle_minimum' => array(
'rule1' => array(
'rule' => 'notEmpty'
),
'rule2' => array(
'rule' => array('comparisonWithField', '<=', 'vehicle_maximum'),
'message' => 'Le nombre de véhicule minimum doit être inférieur ou égal au nombre de véhicule max.'
)
),
'vehicle_maximum' => array('rule' => 'notEmpty'),
'vehicle_price' => array('rule' => 'notEmpty'),
'attendent_price' => array('rule' => 'notEmpty'),
'attendent_maximum' => array('rule' => 'notEmpty'),
'is_visible' => array('rule' => 'notEmpty'),
//Validation date
//BUG HERE
'date' => array(
'rule' => array('date', 'ymd'),
'message' => 'Entrez une date correcte !')
);
Edit Resolved :
I resolved my issue with Validating Data from the Controller
if($this->Event->validates()){
}
else{
$this->request->data = $this->Event->findById($id);
}
Thanks to have a look on my trouble.
So, I have this method where I save a model and its associated models. It has validation rules, but not on the fields that are causing the errors.
The data being passed to the save method is ok, the return of the save method using atomic = false is true on every field except two, that do not have any validation.
The saveAll/saveAssociated fails, and the return of $this->Model->validationErrors is the list of the fields that are not being validated as a empty array.
I already had searched for this on web and found a similar problem to mine here on StackOverflow, but the answer didn't solve my problem.
EDIT
The link to the problem similar to mine: CakePHP save failing with validation errors set but empty
EDIT 2
Here's the code. The rest of the models are ok, so I won't post it here.
**Add Method**
public function add() {
if ($this->request->is('post')) {
if(empty($this->request->data['User']['referer'])) {
$this->request->data['Partner']['status'] = 1;
$this->request->data['User']['group_id'] = 2;
$this->request->data['User']['status'] = 1;
$this->request->data['Customer']['birthday'] = implode("-", array_reverse(explode("/", $this->request->data['Customer']['birthday'])));
$this->request->data['Customer']['newsletter'] = ($this->request->data['Customer']['newsletter'] == "1") ? true : false;
$this->request->data['Customer']['accept'] = ($this->request->data['Customer']['accept'] == "1") ? true : false;
if(!$this->request->data['Customer']['accept']) {
$this->Session->setFlash(__('You must accept the terms and conditions to proceed.'), 'danger');
} else {
$this->Customer->Partner->create();
var_dump($this->Customer->Partner->saveAssociated($this->request->data, array('atomic' => false)));
debug($this->Customer->Partner->validationErrors);
exit();
if($this->Partner->saveAll($this->request->data)) {
$this->Session->setFlash(__('Your profile has been saved. Welcome to Abaixo da Tabela.'), 'success');
$this->redirect(array('controller' => 'pages', 'action' => 'display', 'home', 'admin' => false));
} else {
$this->Session->setFlash('Ocorreu um erro ao tentar salvar seu perfil. Verifique se os campos estão preenchidos corretamente e tenta novamente.', 'danger');
}
}
}
}
}
** Partner Model **
class Partner extends AppModel {
public $validate = array(
'person_type' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'status' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
);
public $hasMany = array(
'Address' => array(
'className' => 'Address',
'foreignKey' => 'partner_id',
),
'Contact' => array(
'className' => 'Contact',
'foreignKey' => 'partner_id',
),
'Customer' => array(
'className' => 'Customer',
'foreignKey' => 'partner_id',
),
'User' => array(
'className' => 'User',
'foreignKey' => 'partner_id',
),
);
}
** Address Model **
class Address extends AppModel {
public $validate = array(
'partner_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'address' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'number' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'zip' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'district' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
'city_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'uf' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
),
),
);
public $belongsTo = array(
'Partner' => array(
'className' => 'Partner',
'foreignKey' => 'partner_id',
),
'City' => array(
'className' => 'City',
'foreignKey' => 'city_id',
)
);
}
** Customer Model **
class Customer extends AppModel {
public $validate = array(
'partner_id' => array(
'numeric' => array(
'rule' => array('numeric'),
),
),
'birthday' => array(
'date' => array(
'rule' => array('date'),
),
),
);
public $belongsTo = array(
'Partner' => array(
'className' => 'Partner',
'foreignKey' => 'partner_id',
),
'City' => array(
'className' => 'City',
'foreignKey' => 'city_id',
)
);
}
** debug($this->Customer->Partner->validationErrors) **
array (size=5)
'Partner' => boolean true
'Address' =>
array (size=7)
'zip' => boolean true
'address' => boolean true
'number' => boolean true
'adjunct' => boolean false
'district' => boolean true
'uf' => boolean true
'city_id' => boolean true
'Contact' =>
array (size=3)
'email' => boolean true
'phone_1' => boolean true
'phone_2' => boolean true
'User' =>
array (size=5)
'username' => boolean true
'password' => boolean true
'password_confirm' => boolean true
'group_id' => boolean true
'status' => boolean true
'Customer' =>
array (size=4)
'genre' => boolean true
'birthday' => boolean true
'newsletter' => boolean false
'accept' => boolean true
Note the two false responses in the return of the save method.
(Answered by a question edit. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
Turned out that the error was in the view. The form fields for the associated models were like:
echo $this->Form->input('Customer.birthday')
echo $this->Form->input('Customer.newsletter')
echo $this->Form->input('Customer.accept')
When the correct way was:
echo $this->Form->input('Customer.0.birthday')
echo $this->Form->input('Customer.0.newsletter')
echo $this->Form->input('Customer.0.accept')
As in the Book, the fields for models with the hasMany association need a index, in that case, the 0.
I am using these three relations User, Movie and UsersWatchlist.. Where users_watchlists contains movie_id and user_id as attributes.. I have this structure
array(
'User' => array(
'id' => '3'
),
'UsersWatchlist' => array(
'UsersWatchlist' => array(
(int) 0 => '3'
)
)
)
public function watchlist($id = null) {
$userid = '3';
if (!$id && $userid != 3) {
$this->Session->setFlash('Invalid Movie');
$this->redirect($this->referer(array('action' => 'listing')));
}
$this->request->data['User']['User'][] = $userid;
$this->request->data['Movie']['Movie'][] = $id;
debug($this->request->data);
if ($this->User->saveAll($this->request->data)) {
debug("saved");
$this->Session->setFlash('The movie has been added to your watchlist', 'admin/flash_success');
//$this->redirect($this->referer(array('action' => 'listing')));
} else {
debug("saved bo");
$this->Session->setFlash('The movie could not be added to your watchlist. Please, try again.', 'admin/flash_error');
//$this->redirect($this->referer(array('action' => 'listing')));
}
}
I used saveAll method on User but its not saving.. Please provide me solution to save the data..
In Movie model,
public $hasAndBelongsToMany = array('User' => array(
'className' => 'User',
'joinTable' => 'users_watchlists',
'foreignKey' => 'movie_id',
'associationForeignKey' => 'user_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
In User model,
public $hasAndBelongsToMany = array(
'Movie' => array(
'className' => 'Movie',
'joinTable' => 'users_watchlists',
'foreignKey' => 'user_id',
'associationForeignKey' => 'movie_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
In UsersWatchlist model,
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Movie' => array(
'className' => 'Movie',
'foreignKey' => 'movie_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
The data array you're trying to save is wrong.
If you're saving throung the User model your structure should be:
array(
'User' => array(
'id' => '3'
),
'Movie' => array(
'Movie' => array(
(int) 0 => '3'
)
)
I have two models User and Movie.. Where those are associated with UsersWatchlist..
public $hasAndBelongsToMany = array('User' => array(
'className' => 'User',
'joinTable' => 'users_watchlists',
'foreignKey' => 'movie_id',
'associationForeignKey' => 'user_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
))
public $hasAndBelongsToMany = array(
'Movie' => array(
'className' => 'Movie',
'joinTable' => 'users_watchlists',
'foreignKey' => 'user_id',
'associationForeignKey' => 'movie_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
))
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Movie' => array(
'className' => 'Movie',
'foreignKey' => 'movie_id',
'conditions' => '',
'fields' => '',
'order' => ''
))
I created 'watchlist' action in UsersController.. The code is below
public function watchlist($id = null) {
$userid = 3;
if (!$id && $userid != 3) {
$this->Session->setFlash('Invalid Movie');
$this->redirect($this->referer(array('action' => 'listing')));
}
$this->request->data['User']['id'] = $userid;
$this->User->UsersWatchlist->create();
debug($this->User->UsersWatchlist->saveAll(array('user_id' => '2', 'movie_id' => 3)));
if ($this->User->UsersWatchlist->saveAll($this->request->data)) {
$this->Session->setFlash('The movie has been added to your watchlist', 'admin/flash_success');
$this->redirect($this->referer(array('action' => 'listing')));
} else {
$this->Session->setFlash('The movie could not be added to your watchlist. Please, try again.', 'admin/flash_error');
$this->redirect($this->referer(array('action' => 'listing')));
}
}
So i am getting an error while saving.. Please tell me the solution
Firstly your data should look like this (provided you want to save it through the user Model):
$this->request->data = array(
'User' => array(
'id' => '2',
),
'Movie' => array(
'Movie' => array(
(int) 0 => '3',
),
),
);
The main mistake I see is that you're trying to save through the Join Model, where you should be saving through the User model. So in the controller use:
$this->User->saveAll($this->request->data)
If the data is as described above it should go fine. I thought I've answered your question here.
Hope this helps.
Cheers!
Your associations seem interesting. Is there a reason you've associated the HABTM join model with the two models (user, movie)? You can achieve the same effect by putting the first $HABTM in the Movie model, and the second $HABTM in the User model. You don't need to create the intermediate join model, cake will do that for you, you only need the table.