Related
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
I have code working search related models using the Search Plugin, but it forces me to break the structure of my model associations. As a result, my save and edit functions do not work properly.
Here is the structure of my data.
Model:
public $belongsTo = array(
'Movie' => array(
'className' => 'Movie',
'foreignKey' => 'movie_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'MovieStarRecurrance' => array(
'className' => 'MovieStarRecurrance',
'foreignKey' => 'movie_star_recurrance_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'MovieStarType' => array(
'className' => 'MovieStarType',
'foreignKey' => 'movie_star_type_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
);
public $hasMany = array(
'MovieStarLine' => array(
'className' => 'MovieStarLine',
'foreignKey' => 'movie_star_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => 'status_date',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
);
I am searching and filtering within the related model Movie and the User that Movie belongsTo.
public $filterArgs = array(
'parent_user_id' => array('type' => 'like', 'field' => 'User.parent_user_id'),
'initials' => array('type' => 'value', 'field' => 'User.id'),
'trace' => array('type' => 'like', 'field' => 'MovieStar.trace'),
'movie' => array('type' => 'query', 'method' => 'orConditionsMovie'),
'star_type' => array('type' => 'value', 'field' => 'MovieStar.movie_star_type_id'),
'code' => array('type' => 'value', 'field' => 'MovieStar.code'),
'status' => array('type' => 'value', 'field' => 'MovieStarLine.movie_star_status_id'),
'open' => array('type' => 'value', 'field' => 'MovieStar.open'),
'from_date' => array('type' => 'query', 'method' => 'orConditionsFromDate'),
'end_date' => array('type' => 'query', 'method' => 'orConditionsEndDate'),
);
In order to access these models at the top level of my search, I unbind the Movie model belongsTo association and rebind it as hasOne. I do the same for MovieStarLine and MovieStarStatus.
Controller:
$this->MovieStar->recursive = 0;
$this->MovieStar->unbindModel( array(
'belongsTo' => array('Movie')
)
);
// MovieStarStatus to be top level json element
$this->MovieStar->bindModel( array(
'hasOne' => array(
'Movie' => array(
'foreignKey' => false,
'conditions' => array('Movie.id = MovieStar.movie_id'),
'fields' => array('Movie.id', 'Movie.movie_id', 'Movie.user_id', 'Movie.movie_mid', 'Movie.movie_dba')
),
'User' => array(
'foreignKey' => false,
'conditions' => array('Movie.user_id = User.id'),
'fields' => array('User.id', 'User.initials', 'User.user_first_name', 'User.user_last_name', 'User.name', 'User.parent_user_id', 'User.secondary_parent_user_id')
),
'MovieStarLine' => array(
'foreignKey' => false,
'conditions' => array('MovieStarLine.movie_star_id = MovieStar.id',
'MovieStarLine.id = (SELECT id FROM "public"."movie_star_lines" AS "MovieStarLine" WHERE movie_star_id = MovieStar.id ORDER BY status_date DESC NULLS LAST, id DESC LIMIT 1)' // Get only most recent line
),
'order' => array( 'MovieStarLine.status_date' => 'DESC NULLS LAST')
),
'MovieStarStatus' => array(
'foreignKey' => false,
'conditions' => array('MovieStarLine.movie_star_status_id = MovieStarStatus.id'),
),
),
));
$this->MovieStar->contain(array(
'Movie',
'MovieStarLine' => array('MovieStarStatus'),
'MovieStarType',
'MovieStarRecurrance',
'User',
'MovieStarStatus'
));
// This is where the search filter occurs
$this->Prg->commonProcess();
$this->paginate = array( 'conditions' => $this->MovieStar->parseCriteria($this->Prg->parsedParams()), 'limit' => 100);
$movieStars = $this->paginate();
$this->set(compact('movieStars'));
}
The problem is when I try to search by parent_user_id or initials, I get an ERROR: missing FROM-clause entry for table "User".
It seems like the dynamic binding doesn't work. I have to remove Movie from belongsTo
Model:
public $belongsTo = array(
//'Movie' => array(
// 'className' => 'Movie',
// 'foreignKey' => 'movie_id',
// 'conditions' => '',
// 'fields' => '',
// 'order' => ''
//),
'MovieStarRecurrance' => array(
'className' => 'MovieStarRecurrance',
'foreignKey' => 'movie_star_recurrance_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'MovieStarType' => array(
'className' => 'MovieStarType',
'foreignKey' => 'movie_star_type_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
);
and add hasOne for Movie and User for the search to work.
public $hasOne = array(
'Movie' => array(
'foreignKey' => false,
'conditions' => array('Movie.id = MovieStar.movie_id'),
'fields' => array('Movie.id', 'Movie.movie_id', 'Movie.user_id', 'Movie.movie_mid', 'Movie.movie_dba')
),
'User' => array(
'foreignKey' => false,
'conditions' => array('Movie.user_id = User.id'),
'fields' => array('User.id', 'User.initials', 'User.user_first_name', 'User.user_last_name', 'User.name', 'User.parent_user_id', 'User.secondary_parent_user_id')
),
'MovieStarLine' => array(
'foreignKey' => false,
'conditions' => array('MovieStarLine.movie_star_id = MovieStar.id',
'MovieStarLine.id = (SELECT id FROM "public"."movie_star_lines" AS "MovieStarLine" WHERE movie_star_id = MovieStar.id ORDER BY status_date DESC NULLS LAST, id DESC LIMIT 1)' // Get only most recent line
),
//'order' => array( 'MovieStarLine.status_date' => 'DESC NULLS LAST')
),
);
I can't do this though because it breaks all of my save and edit functionality. Does anyone know how to properly rebind the associations?
##################### UPDATE
I found a partial solution that seemingly gets me past the User model not showing up.
"Passing false as a second parameter of your Model::bindModel call. This will make your on-the-fly binding last the duration of the request." from this answer..
This might have fixed my bindings, still not sure because now I have an error with count and group by.
ERROR: column "MovieStarLine.status_date" must appear in the GROUP BY clause or be used in an aggregate
SQL Query: SELECT COUNT(*) AS "count"
$this->MovieStar->unbindModel( array(
'belongsTo' => array('Movie')
), false
);
// MovieStarStatus to be top level json element
$this->MovieStar->bindModel( array(
'hasOne' => array(
'Movie' => array(
'foreignKey' => false,
'conditions' => array('Movie.id = MovieStar.movie_id'),
'fields' => array('Movie.id', 'Movie.movie_id', 'Movie.user_id', 'Movie.movie_mid', 'Movie.movie_dba')
),
'User' => array(
'foreignKey' => false,
'conditions' => array('Movie.user_id = User.id'),
'fields' => array('User.id', 'User.initials', 'User.user_first_name', 'User.user_last_name', 'User.name', 'User.parent_user_id', 'User.secondary_parent_user_id')
),
'MovieStarLine' => array(
'foreignKey' => false,
'conditions' => array('MovieStarLine.movie_star_id = MovieStar.id',
'MovieStarLine.id = (SELECT id FROM "public"."movie_star_lines" AS "MovieStarLine" WHERE movie_star_id = MovieStar.id ORDER BY status_date DESC NULLS LAST, id DESC LIMIT 1)' // Get only most recent line
),
'order' => array( 'MovieStarLine.status_date' => 'DESC NULLS LAST')
),
'MovieStarStatus' => array(
'foreignKey' => false,
'conditions' => array('MovieStarLine.movie_star_status_id = MovieStarStatus.id'),
),
),
), false);
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.