issues with saveAll() cakePHP - php

I am having issues saving my data and the associated data. below is my error.
Model
<?php
class Project extends AppModel {
var $name = 'Project';
var $displayField = 'project_title';
var $validate = array(
'user_id' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'project_title' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
'required' => true,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'description' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
'required' => true,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'status' => array(
'boolean' => array(
'rule' => array('boolean'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'approval_status' => array(
'boolean' => array(
'rule' => array('boolean'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'budget' => array(
'money' => array(
'rule' => array('money'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
'required' => true,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'bidding_type_id' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
'required' => true,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'project_type_id' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
'required' => true,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'esl' => array(
'boolean' => array(
'rule' => array('boolean'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'Country' => array(
'required' => true,
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'secrecy' => array(
'boolean' => array(
'rule' => array('boolean'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'Os' => array(
'alphanumeric' => array(
'rule' => array('alphanumeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
'required' => true,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'performance' => array(
'required' => false,
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'cme' => array(
'required' => false,
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'delivery' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'delivery_days' => array(
'alphanumeric' => array(
'rule' => array('alphanumeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'delivery_due' => array(
'alphanumeric' => array(
'rule' => array('alphanumeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'close' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'agree' => array(
'boolean' => array(
'rule' => array('boolean'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'created' => array(
'date' => array(
'rule' => array('date'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'favorite' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'top_employer' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'view_counter' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
);
var $belongsTo = array(
'User' => array(
'className' => 'User',
'conditions' => '',
'fields' => '',
'order' => ''
),
'ProjectType' => array(
'className' => 'ProjectType',
'foreignKey' => 'project_type_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'BiddingType' => array(
'className' => 'BiddingType',
'foreignKey' => 'bidding_type_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
var $hasMany = array(
'Bid' => array(
'className'=> 'Bid',
'order'=>'',
),
'Comment' => array(
'className'=> 'Comment',
'order'=>'',
)
);
var $hasAndBelongsToMany = array(
'Os' =>
array(
'className' => 'OperatingSystem',
'joinTable' => 'project_operating_systems',
'foreignKey' => 'project_id',
'associationForeignKey' => 'os_id',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
),
'Country' =>
array(
'className' => 'Country',
'joinTable' => 'project_countries',
'foreignKey' => 'project_id',
'associationForeignKey' => 'country_id',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
),
'Category' => array(
'className' => 'Category',
'joinTable' => 'project_categories',
'foreignKey' => 'project_id',
'associationForeignKey' => 'category_id',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
),
);
//Gets the Minimum and Maximum Bid of a particular project
public function getMinMaxBid($projectId)
{
$minMax = array(
'conditions'=>array(
'Bid.project_id'=>$projectId
),
'fields'=>array(
'MIN(Bid.bid_amount) as minBid',
'MAX(Bid.bid_amount) as maxBid'
),
'group'=>array('Bid.bid_amount')
);
$minMaxBids = $this->Bid->find('all',$minMax);
return $minMaxBids[0][0];
}
//Gets Project, Project Owner, The Bidder Logged In, And All his comments
public function getProjectSummaryData($ProjectId = null, $replyToId = null,$loggedInId = null)
{
$this->Behaviors->attach('Containable');
$user = array('fields'=>array('id','username'));
$projectOwnerId = $this->field('user_id',array('Project.id'=>$ProjectId));
$commentConditions = array(
'AND'=>array(
array(
'Comment.to_id'=>array(
"$replyToId","$projectOwnerId"
)
),
array(
'Comment.from_id'=>array(
"$replyToId","$projectOwnerId"
)
)
));
if($ProjectId)
{
$params = array(
'conditions'=>array(
'Project.id'=>$ProjectId
),
'contain'=>array(
//Gets the User Who owns the Project
'User'=>$user,
'Bid'=>array(
'conditions'=>array('Bid.user_id'=>$loggedInId),
'order' => array('id' => 'desc'),
//The User Who owns the Bid
'User'=>$user),
//Gets All Comments that belong to project. Filters Only Comments Between Owner and Logged In Users
'Comment'=>array(
'conditions'=>$commentConditions,
'To'=>$user,
'From'=>$user
),
)
);
$project = $this->find('first',$params);
$userProjectCount = $this->find('count',array('conditions'=>array('Project.user_id'=>$project['Project']['user_id'])));
if($replyToId != $project['Project']['user_id'])
$project['Project']['replyTo'] = $replyToId;
else
$project['Project']['replyTo'] = $project['Project']['user_id'];
if($loggedInId == $project['Project']['user_id'])
$project['Project']['is_owner'] = true;
else
$project['Project']['is_owner'] = false;
$project['Project']['numMessages'] = count($project['Comment']);
$project['Project']['totalProjects'] = $userProjectCount;
//debug($project);
return $project;
}
else
{
return false;
}
}//END FUNCTION
public function tick($prodID)
{
//xdebug_break();
$project = $this->findById($prodID);
$project['Project']['view_counter'] += 1;
$this->data = $project;
if(!$this->save($this->data,false))
{
echo 'ticker issue';
}
}
public function getProjectDataView($ProjectId, $userID)
{
$this->Behaviors->attach('Containable',array('autoFields'=>false));
$user = array('fields'=>array('id','username'));
$projectOwnerId = $this->field('user_id',array('Project.id'=>$ProjectId));
$order = array('Comment.from_id');
if($ProjectId)
{
$params = array(
'conditions'=>array(
'Project.id'=>$ProjectId
),
'contain'=>array(
//Gets the User Who owns the Project
'User'=>$user,
'Bid'=>array(
//The User Who owns the Bid
'User'=>$user),
'ProjectType',
'Os',
'Comment'=>array(
'To'=>$user,
'From'=>$user,
),
),
);
//debug($params);
$comments = $this->Comment->find('all',array(
'conditions'=>array(
'AND'=>array(
'Comment.to_id'=>$userID,
'Comment.project_id'=>$ProjectId)
),
'fields'=>array(
'To.username',
'To.id',
'From.username',
'From.id',
'Comment.comment'
),
'group'=>array(
'From.id'
)
)
);
$minMaxBid = $this->getMinMaxBid($ProjectId);
$project = $this->find('first',$params);
$project['bid_count'] = $this->Bid->find('count',array('conditions'=>array('Bid.project_id'=>$ProjectId)));
$project['Comment'] = $comments;
$project['Project'] = array_merge($project['Project'],$minMaxBid);
return $project;
}
else
{
return false;
}
}
//checks to see if the user has already bid on the project
public function hasBid($project, $userID)
{
if(!$project)
return false;
foreach($project['Bid'] as $bid)
{
if($bid['User']['id'] == $userID)
return true;
}
return false;
}
//returns total projects availible
public function getTotalProjectCount()
{
return $this->find('count',array("order"=> array('Project.created desc')));
}
//returns total open project amount
public function getTotalBidAmount()
{
$this->recursive = 0;
$amounts = $this->find('all',array(
'conditions'=>array(
'approval_status'=>1
),
'fields'=>'budget'
));
$amt = 0;
foreach ($amounts as $amount)
{
$amt += $amount['Project']['budget'];
}
return $amt;
}
}
OUTPUT
2011-12-19 12:47:50 Warning: Warning (2): preg_match() [function.preg-match]:
Empty regular expression in
[C:\wamp\www\hrw2\cake\libs\model\model.php, line 2614] 2011-12-19
> 12:47:51 Error: Array (
> [description] => notempt
> [Os] => This field cannot bePU
> [cme] => required
> [delivery] => numeric )
>
> 2011-12-19 12:47:51 Error: Array (
> [Project] => Array
> (
> [project_title] => New Project
> [project_type_id] => 5
> [budget] => 20000
> [bidding_type_id] => 2
> [esl] => 1
> [secrecy] => 1
> [user_id] => 9
> [approval_date] => Array
> (
> [month] => 12
> [day] => 19
> [year] => 2011
> [hour] => 12
> [min] => 47
> [meridian] => pm
> )
>
> [categories] => Array
> (
> [0] => 2
> [1] => 3
> )
>
> [description] =>
> [performance] => 1
> [cme] => 1
> [project_deadline] => 1
> [delivery] =>
> [bidding_deadline] =>
> [agree] => 0
> )
>
> [Country] => Array
> (
> [Country] => Array
> (
> [0] => 1
> [1] => 4
> )
>
> )
>
> [Os] => Array
> (
> [Os] => Array
> (
> [0] => 3
> [1] => 5
> )
>
> )
>
> )

Related

issue in cakephp data validation on model

I am working on cakephp v2.3. While I am validation data by $this->User->validates it will always return false even if values are there.
Here is my validation rule
public $validate = array(
'first_name' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.',
'last' => true,
'required' => true,
),
'size' => array(
'rule' => array('maxLength', 50),
'message' => 'This field must be no larger than 50 characters long.'
),
),
'last_name' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.',
'last' => true,
'required' => true,
),
'size' => array(
'rule' => array('maxLength', 50),
'message' => 'This field must be no larger than 50 characters long.',
'allowEmpty' => true,
),
),
'email' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.',
'last' => true,
'required' => true,
),
'checkMail' => array(
'rule' => 'checkMail',
'message' => 'Please provide a valid email address.',
'last' => true,
),
'isUnique' => array(
'rule' => 'isUnique',
'message' => 'Email address already in use.',
'last' => true,
),
),
'password' => array(
'rule1' => array(
'rule' => array('minLength', 6),
'message' => 'Passwords must be at least 6 characters long.',
'required' => true,
),
),
'verify_password' => array(
'rule' => 'validIdentical',
),
'current_pass' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.',
'last' => true,
),
'match' => array(
'rule' => 'validICurrent',
)
),
'gender' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.',
'last' => true,
),
),
'mobile' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'This field cannot be left blank.',
'last' => true,
'required' => true,
),
'numeric' => array(
'rule' => 'numeric',
'message' => 'Please enter valid phone numbers.',
)
),
'image' => array(
'SizeLimit' => array(
'rule' => array('isUnderPhpSizeLimit', false),
'message' => 'File exceeds upload filesize limit',
),
'FormSizeLimit' => array(
'rule' => array('isUnderFormSizeLimit', false),
'allowEmpty' => true,
'message' => 'File exceeds form upload filesize limit'
),
'CompletedUpload' => array(
'rule' => array('isCompletedUpload', false),
'message' => 'File was not successfully uploaded'
),
'ValidExtension' => array(
'allowEmpty' => true,
'rule' => array('isValidExtension', array('gif', 'png', 'jpg', 'jpeg'), false),
'message' => 'File does not have a gif, png, ,jpg and jpeg extension'
)
),
);
and this is how I am validating
if ($this->request->is("post")) {
if (!empty($this->request->data)) {
if (!$this->User->validates($this->request->data)) {
$this->Session->setFlash(__('The Information could not be saved. Please, try again.'), 'message', array('class' => 'danger'));
$this->redirect(Router::url('/', true) . 'sign-up/');
}
}
When I try
die(debug($this->User->invalidFields()));
it will return
array(
'password' => '*****',
'last_name' => array(
(int) 0 => 'This field cannot be left blank.',
(int) 1 => 'This field cannot be left blank.'
),
'email' => array(
(int) 0 => 'This field cannot be left blank.',
(int) 1 => 'This field cannot be left blank.'
),
'mobile' => array(
(int) 0 => 'This field cannot be left blank.',
(int) 1 => 'This field cannot be left blank.'
)
)
This is the data I am passing
Array
(
[User] => Array
(
[role_id] => 2
[first_name] => kapil
[last_name] => sharma
[email] => kapiltest#mailinator.com
[password] => abc#123
[verify_password] => abc#123
[mobile] => 1234567890
[gender] => Male
[image] => Array
(
[name] => Screenshot_61.png
[type] => image/png
[tmp_name] => /tmp/phppYBJQF
[error] => 0
[size] => 50611
)
)
)
Your Validations seems fine to me But if we don't set the data in model some time that will cause this kind of issue.
Add below line before validating.
$this->User->set($this->request->data);
So code should look like
$this->User->set($this->request->data); //set data in model
if (!$this->User->validates()) {
$this->Session->setFlash(__('The Information could not be saved. Please, try again.'), 'message', array('class' => 'danger'));
$this->redirect(Router::url('/', true) . 'sign-up/');
}

Add PHP function in CakePHP model array

I have an array of behaviour $actas.Problem is when I adding date() function on the array string,it's return an error:
Example:
public $actas = array(
'Uploader.Attachment'=>array(
'books' => array(
'maxWidth' => 1200,
'maxHeight' => 1200,
'extension' => array('pdf'),
'nameCallback' => '',
'append' => '',
'prepend' => '',
'tempDir' => TMP,
'uploadDir' => '/var/www/html/apps/webroot/files/uploads/books' . date('d-m-Y'),//this is where I want to add the function.
'transportDir' => ''
)
)
);
however it's not working. I also do like this:
public $actas = array(
'Uploader.Attachment'=>array(
'books' => array(
'maxWidth' => 1200,
'maxHeight' => 1200,
'extension' => array('pdf'),
'nameCallback' => '',
'append' => '',
'prepend' => '',
'tempDir' => TMP,
'uploadDir' => "/var/www/html/apps/webroot/files/uploads/books'".date('d-m-Y')."'",//this is where I want to add the function.
'transportDir' => ''
)
)
);
also not worked.
So my question is how to do that? If I have a lot of mistaken,please tell me so I can learn more about the matter.
Thanks in advance.
This is the full source code of Post.php model
<?php
App::uses('AppModel', 'Model');
/**
* Post Model
*
* #property Tier $Tier
* #property Category $Category
* #property Comment $Comment
*/
class Post extends AppModel {
//var $now = 'CURDATE()';
/**
* Validation rules
*
* #var array
*/
public $validate = array(
'title' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'content' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
);
//The Associations below have been created with all possible keys, those that are not needed can be removed
/**
* belongsTo associations
*
* #var array
*/
public $belongsTo = array(
'Tier' => array(
'className' => 'Tier',
'foreignKey' => 'tier_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Category' => array(
'className' => 'Category',
'foreignKey' => 'category_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
/**
* hasMany associations
*
* #var array
*/
public $hasMany = array(
'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'post_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
public $actsAs = array(
//'Containable',
'Uploader.Attachment' => array(
// Do not copy all these settings, it's merely an example
'banner' => array(
'maxWidth' => 1200,
'maxHeight' => 1200,
'extension' => array('gif', 'jpg', 'png', 'jpeg'),
'nameCallback' => '',
'append' => '',
'prepend' => '',
'tempDir' => TMP,
'uploadDir' => "/var/www/html/apps/webroot/img/banners/",
'transportDir' => '',
'finalPath' => '/img/banners/',
'dbColumn' => '',
'metaColumns' => array(),
'defaultPath' => '',
'overwrite' => true,
'transforms' => array(),
'stopSave' => true,
'allowEmpty' => true,
'transformers' => array(),
'transport' => array(),
'transporters' => array(),
'curl' => array()
),
'feature' => array(
'maxWidth' => 1200,
'maxHeight' => 1200,
'extension' => array('gif', 'jpg', 'png', 'jpeg'),
'nameCallback' => '',
'append' => '',
'prepend' => '',
'tempDir' => TMP,
'uploadDir' => '/var/www/html/apps/webroot/img/features/',
'transportDir' => '',
'finalPath' => '/img/features/',
'dbColumn' => '',
'metaColumns' => array(),
'defaultPath' => '',
'overwrite' => true,
'transforms' => array(),
'stopSave' => true,
'allowEmpty' => true,
'transformers' => array(),
'transport' => array(),
'transporters' => array(),
'curl' => array()
),
'books' => array(
'maxWidth' => 1200,
'maxHeight' => 1200,
'extension' => array('pdf'),
'nameCallback' => '',
'append' => '',
'prepend' => '',
'tempDir' => TMP,
'uploadDir' => '/var/www/html/apps/webroot/files/uploads/books' . date('d-m-Y'),
'transportDir' => '',
'finalPath' => '/files/uploads/books/',
'dbColumn' => '',
'metaColumns' => array(),
'defaultPath' => '',
'overwrite' => true,
'transforms' => array(),
'stopSave' => true,
'allowEmpty' => true,
'transformers' => array(),
'transport' => array(),
'transporters' => array(),
'curl' => array()
)
)
);
}
ahh ok I was not looking at it with my OO hat on. you can't do this because:
Properties
Class member variables are called "properties". You may also see them
referred to using other terms such as "attributes" or "fields", but
for the purposes of this reference we will use "properties". They are
defined by using one of the keywords public, protected, or private,
followed by a normal variable declaration. This declaration may
include an initialization, but this initialization must be a
constant value--that is, it must be able to be evaluated at compile
time and must not depend on run-time information in order to be
evaluated.
you need to use the __construct() method

CakePHP bake all unknown issue

I'm new to Cake php.
I have a problem using bake
I set up a migration with user table
public $migration = array(
'up' => array(
'create_table' => array(
'users' => array(
'user_id' => array('type' => 'integer', 'null' => false, 'key' => 'primary'),
'username' => array('type' => 'string', 'null' => false, 'length' => 250),
'password' => array('type' => 'text', 'null' => false),
'created' => array('type' => 'string', 'null' => false, 'length' => 14),
'modified' => array('type' => 'string', 'null' => true, 'default' => null, 'length' => 14),
'indexes' => array(
'PRIMARY' => array('column' => 'user_id', 'unique' => 1)
)
)
)
),
'down' => array(
'drop_table' => array(
'users'
)
)
);
and migrate this file on the db then I tried to do the command "cake bake all"
the problem is that User made a reference to itself with belongsTo and hasMany
is that the default of using bake?
class User extends AppModel {
/**
* Validation rules
*
* #var array
*/
public $validate = array(
'user_id' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'username' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'date_created' => array(
'notEmpty' => array(
'rule' => array('notEmpty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
);
//The Associations below have been created with all possible keys, those that are not needed can be removed
/**
* belongsTo associations
*
* #var array
*/
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
/**
* hasMany associations
*
* #var array
*/
public $hasMany = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
is there something I missing here?
Should I leave that and modify it manually or there's a config that I missed.
There are three easy solutions, as the last answer stated cake bake all is following default cake conventions and creating associations by the fact that you have a user_id in the table
Either rename the database field from user_id to id and run the shell again.
Run cake bake and manually select model and configure the database associations manually with the shell helper
Manually remove the associations in the model, and the references in the controller and views.
It's correct.
When you use the cake bake all it automatically adds references to your table by convention. As your table refers to herself he identified the 'hasMany' and 'belongsTo' relationships. You should remove the link that doesn't exist or change that is generated by default. Reference: baking custom projects

CSV Export including row from other table

I am trying to export to a CSV in CakePHP.
Basically the problem that I am having is, the database is split down into multiple tables.
One for a product, one for artists and one for users.
It is all working well apart from the fact that the Email addresses for the artists are stored in the users table, I would like these to be included in the export. I have tried adding in the appropriate header for the column (csv) and then adding the
$result['Users']['username'],
Row that can be seen in my full function below, however it leaves the Email fields blank. Please help!
function export($event_id)
{
$this->layout = 'blank_layout';
ini_set('max_execution_time', 600); //increase max_execution_time to 10 min if data set is very large
//create a file
$filename = "export_".date("Y.m.d").".csv";
$csv_file = fopen('php://output', 'w');
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="'.$filename.'"');
$results = $this->Sculpture->find('all', array('conditions' => array('event_id' => $event_id), 'order' => 'artist_id'));
// The column headings of your .csv file
$header_row = array(
"Artist",
"Email",
"Sculpture",
"Materials",
"Description",
"Price",
"Notes"
);
fputcsv($csv_file,$header_row,',','"');
// Each iteration of this while loop will be a row in your .csv file where each field corresponds to the heading of the column
foreach($results as $result)
{
// Array indexes correspond to the field names in your db table(s)
$row = array(
$result['Artist']['name'],
$result['Users']['username'],
$result['Sculpture']['title'],
$result['Sculpture']['materials'],
$result['Sculpture']['description'],
$result['Sculpture']['price'],
$result['Sculpture']['notes'],
);
fputcsv($csv_file,$row,',','"');
}
fclose($csv_file);
}
Sculpture Model
<?php
App::uses('AppModel', 'Model');
/**
* Sculpture Model
*
* #property Artist $Artist
* #property Event $Event
*/
class Sculpture extends AppModel {
/**
* Validation rules
*
* #var array
*/
public $validate = array(
'artist_id' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'event_id' => array(
'numeric' => array(
'rule' => array('numeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'title' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please tell us the name of your sculpture',
'allowEmpty' => true,
'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'materials' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Please tell us the materials used in this sculpture',
'allowEmpty' => true,
'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'price' => array(
'money' => array(
'rule' => array('numeric'),
'message' => 'Please include the price of your sculpture.'
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
)
);
public function beforeValidate()
{
//$p = $this->data['Sculpture']['price'];
// Get decimal place if available
//$dec = substr(, $start)
$this->data['Sculpture']['price'] = preg_replace("/[^0-9.]/", '', $this->data['Sculpture']['price']);
return true;
}
//The Associations below have been created with all possible keys, those that are not needed can be removed
/**
* belongsTo associations
*
* #var array
*/
public $belongsTo = array(
'Artist' => array(
'className' => 'Artist',
'foreignKey' => 'artist_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Event' => array(
'className' => 'Event',
'foreignKey' => 'event_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
/**
* hasAndBelongsToMany associations
*
* #var array
*/
public $hasAndBelongsToMany = array(
'MediaFile' => array(
'className' => 'MediaFile',
'joinTable' => 'sculptures_media_files',
'foreignKey' => 'sculpture_id',
'associationForeignKey' => 'media_file_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
}
NEW Error report
$this->loadModel('Artist');
$artist = $this->Artist->find('first', array('conditions' => array('Artist.user_id' => $this->Auth->user('id'))));
$this->set('artist_id', $artist['Artist']['id']);
EventsController::view() - APP/Controller/EventsController.php, line 78
ReflectionMethod::invokeArgs() - [internal], line ??
Controller::invokeAction() - CORE/Cake/Controller/Controller.php, line 486
Dispatcher::_invoke() - CORE/Cake/Routing/Dispatcher.php, line 187
Dispatcher::dispatch() - CORE/Cake/Routing/Dispatcher.php, line 162
[main] - APP/webroot/index.php, line 92
NEW NEW ERROR From Sculpture Model
$results = $this->Sculpture->find('all', array('conditions' => array('event_id' => $event_id), 'order' => 'artist_id', 'recursive' => 2));
debug($results); die();
The New error
$this->loadModel('Artist');
$artist = $this->Artist->find('first', array('conditions' => array('Artist.user_id' => $this->Auth->user('id'))));
$this->set('artist_id', $artist['Artist']['id']);
EventsController::view() - APP/Controller/EventsController.php, line 78
ReflectionMethod::invokeArgs() - [internal], line ??
Controller::invokeAction() - CORE/Cake/Controller/Controller.php, line 486
Dispatcher::_invoke() - CORE/Cake/Routing/Dispatcher.php, line 187
Dispatcher::dispatch() - CORE/Cake/Routing/Dispatcher.php, line 162
[main] - APP/webroot/index.php, line 92
<div class="cake-debug-output">
<span><strong>/app/Controller/SculpturesController.php</strong> (line <strong>70</strong>)</span>
<pre class="cake-debug">
array(
(int) 0 => array(
'Sculpture' => array(
'id' => '462',
'artist_id' => '1',
'event_id' => '1',
'title' => '',
'materials' => '',
'description' => '',
'edition' => '',
'price' => '0.00',
'vat' => false,
'media_file_id' => '0',
'delivery' => '2013-12-16',
'notes' => '',
'created' => '2013-12-16 12:52:14',
'modified' => '2013-12-16 12:52:14'
),
'Artist' => array(
'id' => '1',
'name' => 'Amanda Noble',
'website' => 'www.thefusedgarden.co.uk',
'materials' => 'Glass and stainless steel',
'location' => 'Northants',
'created' => '2013-04-30 14:53:25',
'modified' => '2013-07-09 15:21:53',
'user_id' => '11',
'User' => array(
'password' => '*****',
'id' => '11',
'username' => 'noblept#aol.co.uk',
'role_id' => '4',
'created' => '2013-07-01 15:26:40',
'modified' => '2013-07-01 15:26:40'
),
'Sculpture' => array(
(int) 0 => array(
'id' => '138',
'artist_id' => '1',
'event_id' => '2',
'title' => 'Midsummer Blue',
'materials' => 'Glass & Stainless Steel',
'description' => 'One of 3 fused glass panels. sold either as a single panel or as a set of 3',
'edition' => '',
'price' => '144.00',
'vat' => false,
'media_file_id' => '0',
'delivery' => '2013-07-28',
'notes' => 'When sold as a set of three the price is 10% lower.
We will arrive AM, but will not require assistance to install our sculptures',
'created' => '2013-07-09 15:06:56',
'modified' => '2013-07-09 15:21:07'
),
(int) 1 => array(
'id' => '159',
'artist_id' => '1',
'event_id' => '2',
'title' => 'Blue evening',
'materials' => 'Glass and Stainless Seel',
'description' => 'One of 3 fused glass panels sold either as a single panel or as a set of 3 ( the other 2 are Midsummer Blue and Blue Haze )',
'edition' => '',
'price' => '128.00',
'vat' => false,
'media_file_id' => '0',
'delivery' => '2013-07-29',
'notes' => 'Each panel is unique as no piece of fused glass will ever be identical, but it is possible to create a similar, but not exact replica of any panel.
The images shown are of a similar sets, but the actual exhibits are still in the process of creation and an image is not available.',
'created' => '2013-07-09 15:30:53',
'modified' => '2013-07-09 16:31:17'
),
if you are following cake namning convention it should be
$result['User']['username'],
(Model name must be singular and not plural)
edited after seeing Scuplure model file:
Because User is related to Artist Model (and not directly to Sculpture Model) you have to set 'recursive' parameter in your find call:
$results = $this->Sculpture->find(
'all',
array(
'conditions' => array('event_id' => $event_id),
'order' => 'artist_id',
'recursive' => 2
)
);

can not filter values within cakephp model

I created a categories model. I also created a project model. The project model belongs to the categories model so when you create a new project, you recieve a category drop down to pick which category you want.
One of the categories is "Root" and I do not want this showing in the drop down list. I created my belongsTo method like so
project.php MODEL
var $belongsTo = array(
'User' => array(
'className' => 'User',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Category' => array(
'className' => 'Category',
'conditions' => array('Category.id '=>'1'),
'fields' => '',
'order' => ''
),
);
For my controller I have scaffolding turned on.
Here is my categories model
Category model
class Category extends AppModel {
var $name = 'Category';
var $displayField = 'name';
var $actsAs = array('Tree');
var $validate = array(
'name' => array(
'alphanumeric' => array(
'rule' => array('alphanumeric'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'parent_id' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'url' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
);
var $belongsTo = array(
'ParentCategory' => array(
'className' => 'Category',
'conditions' => '',
'foreignKey' => 'parent_id',
'fields' => '',
'order' => ''
),
);
}
I assume you mean remove Root from the drop down menu cake produces with associations? In which case, try this:
$categories = $this->Category->find('list',
array('conditions' => array('Category.name !=' => 'Root')));
$this->set(compact('categories'));
Use 'conditions' => array('Categories !=' =>'1'),, instead.
Validation is used in the saving of data, not in finding.

Categories