This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
CakePHP: Call to a member function find() on a non-object
I have three Models: Product, Prodpage, Field.
I did the cake console to bake all models based on my local mysql db on my pc. I then created a simple controller for each model utilizing the public $scaffold. Here is the ProductsController example:
<?php
// app/Controller/ProductsController.php
class ProductsController extends AppController {
public $scaffold;
}
went into my app (localhost/cake/products) and everything worked fine. I could add products, delete products, edit products. I could then add prodpages, and I could also add the fields. I decided to go ahead and use the cake console to bake the controllers and views. It was my understanding that it should do the same thing as the $scaffold, but this time the controllers should have more of the code in it. Thus allowing me to start to customize it a bit more.
I go back to localhost/cake/products and it was working fine. Then when I try to go to localhost/cake/prodpages/add and I get this error:
Fatal error: Call to a member function find() on a non-object in C:\wamp\www\cake\app\Controller\ProdpagesController.php on line 50
Here is the ProdpagesController all they way through line 53(the add function):
<?php
App::uses('AppController', 'Controller');
/**
* Prodpages Controller
*
* #property Prodpage $Prodpage
*/
class ProdpagesController extends AppController {
/**
* index method
*
* #return void
*/
public function index() {
$this->Prodpage->recursive = 0;
$this->set('prodpages', $this->paginate());
}
/**
* view method
*
* #param string $id
* #return void
*/
public function view($id = null) {
$this->Prodpage->id = $id;
if (!$this->Prodpage->exists()) {
throw new NotFoundException(__('Invalid prodpage'));
}
$this->set('prodpage', $this->Prodpage->read(null, $id));
}
/**
* add method
*
* #return void
*/
public function add() {
if ($this->request->is('post')) {
$this->Prodpage->create();
if ($this->Prodpage->save($this->request->data)) {
$this->Session->setFlash(__('The prodpage has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The prodpage could not be saved. Please, try again.'));
}
}
$products = $this->Prodpage->Product->find('list');
$this->set(compact('products'));
}
and this is line 50,
$products = $this->Prodpage->Product->find('list');
Anybody know what I am doing wrong here or elaborate on what the error is telling me? I'm new to cakephp so I am walking through tutorials. This has me stumped though.
Update: Model/Product.php
<?php
App::uses('AppModel', 'Model');
/**
* Product Model
*
* #property Prodpages $Prodpages
*/
class Product extends AppModel {
/**
* Display field
*
* #var string
*/
public $displayField = 'product_name';
/**
* Validation rules
*
* #var array
*/
public $validate = array(
'product_name' => 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
),
),
's7_location' => 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
),
),
'created' => array(
'datetime' => array(
'rule' => array('datetime'),
//'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
),
),
'modified' => array(
'datetime' => array(
'rule' => array('datetime'),
//'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
/**
* hasMany associations
*
* #var array
*/
public $hasMany = array(
'Prodpages' => array(
'className' => 'Prodpages',
'foreignKey' => 'id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
Here is Model/Prodpage.php
<?php
App::uses('AppModel', 'Model');
/**
* Prodpage Model
*
* #property Products $Products
* #property Fields $Fields
*/
class Prodpage extends AppModel {
/**
* Display field
*
* #var string
*/
public $displayField = 'page_name';
/**
* Validation rules
*
* #var array
*/
public $validate = array(
'is_blank' => 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
),
),
'page_order' => 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
),
),
's7_page' => 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
),
),
'created' => array(
'datetime' => array(
'rule' => array('datetime'),
//'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
),
),
'modified' => array(
'datetime' => array(
'rule' => array('datetime'),
//'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(
'Products' => array(
'className' => 'Products',
'foreignKey' => 'products_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
/**
* hasMany associations
*
* #var array
*/
public $hasMany = array(
'Fields' => array(
'className' => 'Fields',
'foreignKey' => 'id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
I did the cake console to bake these models, so I did the associations within there. I thought I had Prodpage and Product related correctly. One product can have many Prodpages. One Prodpage belongs to one product.
UPDATE W/ QUERY ERROR
So when I go to localhost/cake/prodpages/add and fill out the info, selecting a Product from the product dropdown list I get this error
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`builder_cake`.`prodpages`, CONSTRAINT `fk_prodpages_products` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
SQL Query: INSERT INTO `builder_cake`.`prodpages` (`page_name`, `is_blank`, `page_order`, `s7_page`, `modified`, `created`) VALUES ('Page 2', '0', 2, 2, '2012-06-13 16:51:35', '2012-06-13 16:51:35')
I looked into to it and it is not passing the product_id associated with the dropdown list selection to add into into the product_id column in my Prodpages table.. any thoughts why?
It looks like your model names are plural, when they should be singular. For example:
public $belongsTo = array(
// Product, not Products
'Product' => array(
'className' => 'Product',
'foreignKey' => 'products_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Related
my controller class
class BlistsController extends AppController{
public $components = array('session');
public function index(){
$data = $this->Blist->find('all');
$this->set('var_Blist', $data);
}
public function add(){
print_r($this->request->data);
if($this->request->is(array ('post', 'put'))){
$this->Blist->create();
if($this->Blist->save($this->request->data)){
$this->session->setFlash("book added successfully");
$this->reirect('index');
}
else{
$this->session->setFlash("Unable to add book");
}
}
}
}
I used this code in my home pc. its working fine. but the same code is not working in my workplace. is there any enable need in the wamp.
when i print the print_r($this->request->data)
it shows
Array ( [Blist] => Array ( [F_bookId] => [F_name] => sadfasdf [F_author] => asdfasdf ) )
the field "F_bookId" is auto increment at the database table.
Therefore it not showing at the display page.
App::uses('AppModel', 'Model');
/**
* Blist Model
*
*/
class Blist extends AppModel {
/**
* Primary key field
*
* #var string
*/
public $primaryKey = 'F_bookId';
/**
* Display field
*
* #var string
*/
public $displayField = 'F_name';
/**
* Validation rules
*
* #var array
*/
public $validate = array(
'F_bookId' => 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
),
),
'F_name' => 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
),
),
'F_author' => 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
),
),
);
}
Add.ctp
<h1> Add Book Details </h1>
<?php
echo $this->Form->create('Blist');
echo $this->Form->input('F_bookId');
echo $this->Form->input('F_name');
echo $this->Form->input('F_author');
echo $this->Form->end('Add Book');
?>
the final code which is working fine..
public function add(){
$data = $this->request->data;//getting the values from the input fields
//get the last record
$lastRecordId = $this->Blist->find('first', array('order' =>array('F_bookId' => 'DESC')));
//Split the book id, to generate a new book id
$temp = str_split($lastRecordId['Blist']['F_bookId'], '4');
$data['Blist']['F_bookId'] = ($temp[0]. ((String)((int)$temp[1]+1)));
if($this->request->is(array ('post', 'put'))){
$this->Blist->create();
if($this->Blist->save($data)){
$this->session->setFlash("book added successfully");
$this->redirect('add');
}
else{
debug($this->Blist->validationErrors);
$this->session->setFlash("Unable to add book");
}
}
}
Your id is auto-created by the auto increment feature of your database. There is no need to validate the user input for F_BookId since there is none and if you set the rule notEmpty on that field validation will trigger an error.
remove this part from your $validate array:
'F_bookId' => 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
),
),
This should let your save your books.
On a sidenote: You might want to read about naming conventions concerning CakePHP to make your life easier: http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html
I know there are many questions on this issue, but I've tried to add all resolutions but still no luck so far, so I am sharing my code to see if anyone can give me a solution. Thanks.
I've successfully hashed my password, I already added text field in the password database so I won't have any problem with character amount. But every time I try to login, it says Invalid username/password, and it doesn't redirect or anything. I am a newbie in programming and PHP. Please help.
Here is my code:
AppController.php
App::uses('Controller', 'Controller');
class AppController extends Controller {
public $helpers = array('Html', 'Session', 'Form' );
public $components = array(
'DebugKit.Toolbar',
'Session',
'Auth'=>array(
'loginRedirect'=>array('Controller'=>'user', 'action'=>'index'),
'logoutRedirect'=>array('Controller'=>'user', 'action'=>'index'),
'authError'=>"you are not allowed to access that page",
'authorize'=>array('Controller')
)
);
public function isAuthorized($user){
return TRUE;
}
public function beforeFilter() {
$this->Auth->allow('index', 'add');
}
}
login.ctp
<h1> Login Form</h1>
<?php
echo $this->Form->create('User');
echo $this->Form->input('user_name');
echo $this->Form->input('password');
echo $this->Form->end(__('Login'));
?>
User.php
// hash password before saving It
/*
public function beforeSave($options = array()) {
$this->data['User']['password'] =
AuthComponent::password($this->data['User']['password']);
return TRUE;
}
*/
public function beforeSave($options = array()) {
if (isset($this->data['User']['password'])) {
$this->data['User']['password'] = AuthComponent::password($this->data['User'] ['password']);
}
return TRUE;
}
/**
* Primary key field
*
* #var string
*/
public $primaryKey = 'user_id';
/**
* Display field
*
* #var string
*/
public $displayField = 'user_name';
/**
* Validation rules
*
* #var array
*/
public $validate = array(
//USERNAME VALIDATION
'username' => array(
'required' => array(
'rule' => array('minLength', 1),
'allowEmpty' => false,
'message' => 'Please enter a title.'
)
),
'user_name' => array(
'required' => array(
'rule' => array( 'isUnique' ),
'message' => 'Username already exist. Please try again',
//'allowEmpty' => false,
//'required' => TRUE,
//'last' => TRUE, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
//EMAIL ADDRESS VALIDATION
'email_address' => array(
'required' => array(
'rule' => array('minLength', 1),
'allowEmpty' => false,
'message' => 'Please add an email'
)
),
'email_address' => array(
'required' => array(
'rule' => array( 'isUnique' ),
'message' => 'Email already exist in our database. Please try again',
//'allowEmpty' => false,
//'required' => TRUE,
//'last' => TRUE, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'password'=>array(
'not empty' => array(
'rule'=>'notEmpty',
'Message'=>'Password is empty'
),
'Match Passwords'=> array(
'rule'=>'matchPasswords',
'message'=>'Password do not match'
)
),
'password_confirmation'=>array(
'not empty' => array(
'rule'=>'notEmpty',
'Message'=>'verify password'
)
)
);
// PASSWORD CONFIRMATION VALIDATION FUNCTION
public function matchPasswords($data){
if ($data['password'] == $this->data['User']['password_confirmation']) {
return True;
}
$this->invalidate('password_confirmation', 'Your password do not match');
return FALSE;
}
}
I'm struggeling with my cakePHP validation
Scenario:
In my DB I have one table "alliances" and one "federations". In "federations" connections between alliances are stored. "alliances" has got stupid cols like id, name, etc.. federations is like this:
id, request_alliance, accept_alliance, type, requested_at, accepted_at
where request_alliance and accept_alliance are FK to alliances, type is 1 or 2.
So my model looks like this:
class Federation extends AppModel
{
// Bundarten:
// 1 - NAP
// 2 - Bund
public $displayField;
var $belongsTo = array('Alliance_requesting' => array('className' => 'Alliance', 'foreignKey' => 'request_alliance'),
'Alliance_accepting' => array('className' => 'Alliance', 'foreignKey' => 'accept_alliance'));
public $validate = array(
'request_alliance' => array('required' => true, 'allowEmpty' => false),
'accept_alliance' => array('required' => true, 'allowEmpty' => false),
'type' => array('required' => true, 'allowEmpty' => false, 'rule' => array('between', 1, 2))
);
}
Alliance (created by an former partner, I only added the $hasMany)
class Alliance extends AppModel{
var $hasMany = array(
'Federation_requesting' => array('className' => 'Federation', 'foreignKey' => 'request_alliance', 'dependent' => true),
'Federation_accepting' => array('className' => 'Federation', 'foreignKey' => 'accept_alliance', 'dependent' => true)
);
public $validationDomain = 'alliance';
public $validate = array(
'tag' => array(
'uniqueTag' => array(
'rule' => 'isUnique',
'message' => 'Alliance tag already in use'),
'between' => array(
'rule' => array('between', 2, 15),
'message' => 'Alliance tag must betwenn %d to %d characters')),
'name' => array(
'rule' => array('between', 3, 30),
'message' => 'Alliance name must between %d to %d characters'),
'image_url' => array(
'rule' => 'url',
'message' => 'Alliance picture must be a valid URL',
'allowEmpty' => true),
'homepage' => array(
'rule' => 'url',
'message' => 'Homepage must be a valid URL',
'allowEmpty' => true));
}
So far I've written a view to add a new federation between two alliances. The controller for this
class FederationsController extends AppController
{
var $name = 'Federations';
var $components = array('Message');
var $uses = array('Alliance', 'Federation');
// Requesting new federation
function add()
{
if(empty($this->data['Federation'])) {
$message = __d('federation', "Invalid Request");
$this->notice($message);
return $this->redirect(Path::overall_highscore_alliances_path());
}
$requesting_alliance_id = $this->data['Federation']['req_alliance_id'];
$req_alliance = $this->Alliance->get($requesting_alliance_id);
if(!$req_alliance) {
return $this->redirect(Path::overall_highscore_alliances_path());
}
if(!$this->Alliance->isCurrentUserDiplomat($req_alliance)) {
$message = __d('federation', "Only the diplomat is allowed to modify federations.");
$this->notice($message);
return $this->redirect(Path::alliance_path($requesting_alliance_id));
}
$accepting_alliance_id = $this->data['Federation']['acc_alliance_id'];
$acc_alliance = $this->Alliance->get($accepting_alliance_id);
if(!$acc_alliance) {
$message = __d('federation', "The target alliance for this federation doesn't exists.");
$this->notice($message);
return $this->redirect(Path::alliance_path($requesting_alliance_id));
}
$type = $this->data['Federation']['type'];
$requested_at = time();
$this->Federation->create();
$values = array('request_alliance' => $requesting_alliance_id,
'accept_alliance' => $accepting_alliance_id,
'type' => $type,
'requested_at' => $requested_at);
$saved = $this->Federation->save($values, true, array('request_alliance', 'accept_alliance', 'type', 'requested_at'));
$name = h($acc_alliance['name']);
$message = $saved ? __d('federation', "Federation with '%s' successfully requested.", $name) : '';
$this->notice($message);
$this->errors($this->Federation->validationErrors);
$this->redirect(Path::alliance_path($requesting_alliance_id));
}
}
When I try to add a new federation it the above function is called and a new row is stored inside the DB with the correct values. But the page still shows me the following errors
Could not find validation handler 1 for request_alliance
Could not find validation handler for request_alliance
Could not find validation handler 1 for accept_alliance
Could not find validation handler for accept_alliance
I can't imagine that my validation is not done, because some hours ago I had a mistake which leads to empty fields and I got the correct validation message that this field can't left blank.
Can anyone tell me where I do the mistake which leads to these errors and how to correct it?
Thanks in advance!
There is no validation rule definition
From the question, compare:
'request_alliance' => array(
'required' => true,
'allowEmpty' => false
),
With
'type' => array(
'required' => true,
'allowEmpty' => false,
'rule' => array('between', 1, 2)
)
In the first case there is no rule, rule is a mandatory key if you define the validation rules as an array.
Use the notEmpty validation rule
From the validation rules defined, it looks like there's a misunderstanding. You probably want the notEmpty validation rule:
'request_alliance' => array(
'rule' => 'notEmpty'
)
If you want to ensure that the field is present in all saves, use the required key
'request_alliance' => array(
'rule' => 'notEmpty',
'required' => true
)
There is no need to define the allowEmpty key, as it is the same as the notEmpty validation rule if false, and illogical if defined as true.
I have a login form (login.ctp) in my Members View. But when I give the url as /login, than instead of showing the login of Members view, its showing login page of users view.
/Views/login.ctp file
<div class="members form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('Member'); ?>
<fieldset>
<legend><?php echo __('Please enter your username and password'); ?></legend>
<?php echo $this->Form->input('username');
echo $this->Form->input('password');
?>
</fieldset>
<?php echo $this->Form->end(__('Login')); ?>
</div>
App controller file
class AppController extends Controller {
//...
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'members', 'action' => 'home'),
'logoutRedirect' => array('controller' => 'members', 'action' => 'index')
)
);
public function beforeFilter() {
$this->Auth->allow('index', 'view');
}
//...
}
My routes.php file
Router::connect('/', array('controller' => 'members', 'action' => 'index'));
Router::connect('/login', array('controller' => 'members', 'action' => 'login'));
I have cleared all the cookies. Where is the mistake?
One more thing, I have even tried deleting user controllers, but if I delete user controllers I get the following error...
Error: UsersController could not be found.
This is my login function from MembersController.php
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
//code in member model.
class Member extends AppModel {
/**
* Validation rules
*
* #var array
*/
public $validate = array(
'firstname' => 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
),
),
'lastname' => 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
),
),
'email' => array(
'email' => array(
'rule' => array('email'),
//'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
),
),
'password' => 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
),
),
'age' => 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
),
),
'address' => 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
),
),
'phone' => 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
),
),
'created_on' => array(
'datetime' => array(
'rule' => array('datetime'),
//'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
),
),
);
function beforeSave() {
if(isset($this->data[$this->alias]['password']))
$this->data[$this->alias]['password'] = Security::hash($this->data[$this->alias]['password'], null, true);
return true;
}
}
Try modifying your components array to this:
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'members', 'action' => 'home'),
'logoutRedirect' => array('controller' => 'members', 'action' => 'index'),
'Form' => array(
'userModel' => 'Member'
),
)
);
Or try this in beforeFilter():
// Pass settings in using 'all'
$this->Auth->authenticate = array(
AuthComponent::ALL => array('userModel' => 'Member'),
'Form',
'Basic'
);
EDIT
Tested Code and process
AppController Code
<?php
class AppController extends Controller
{
public $components = array
(
'Session',
'Auth' => array
(
'loginRedirect' => array('controller' => 'members', 'action' => 'home'),
'logoutRedirect' => array('controller' => 'members', 'action' => 'index')
)
);
public function beforeFilter()
{
$this->Auth->allow('index', 'view');
$this->Auth->fields = array('username' => 'email', 'password' => 'password');
$this->Auth->userModel = 'Member';
}
}
all of your code is working fine all you need to do is just set Auth->userModel to Member.
MemberController
<?php
class MembersController extends AppController
{
var $name = 'Members';
function beforeFilter()
{
parent::beforeFilter();
}
}
?>
And in Member controller define beforeFilter as above.
CREATE TABLE IF NOT EXISTS `web_subjects` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`web_subject_category_id` int(11) DEFAULT NULL,
`title` varchar(128) DEFAULT NULL,
`type` varchar(128) DEFAULT NULL,
`description` text,
`description_long` text,
`editable` int(1) DEFAULT NULL,
`deletable` int(1) DEFAULT NULL,
`published` int(1) DEFAULT NULL,
`order_number` int(11) DEFAULT NULL,
`created` timestamp NULL DEFAULT NULL,
`modified` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=19 ;
Model
class WebSubject extends AppModel
{
public $name = "WebSubject";
public $belongsTo = array("WebSubjectCategory");
public $validate = array(
'title' => array(
'rule' => 'notEmpty',
'message' => "Completati denumirea!"
)
);
public $hasMany = array(
'Image' => array(
'className' => 'WebFile',
'foreignKey' => 'entity_id',
'conditions' => array(
'Image.type' => 'image',
'Image.entity_table_name' => 'web_subjects'
),
'order' => array('Image.order_number ASC', 'Image.id DESC'),
'dependent' => true
),
'Video' => array(
'className' => 'WebFile',
'foreignKey' => 'entity_id',
'conditions' => array(
'Video.type' => 'video',
'Video.entity_table_name' => 'web_subjects'
),
'order' => array('Video.order_number ASC', 'Video.id DESC'),
'dependent' => true
)
);
}
Controller Action
public function admin_page_add(){
if(!empty($this->request->data))
{
$this->WebSubject->create($this->data["WebSubject"]);
$this->WebSubject->type = 'page';
//debug($this->WebSubject);
if($this->WebSubject->save()){
//debug($this->WebSubject);
//die(0);
$this->Session->setFlash("Pagina a fost salvata!", "flash/simpla_success");
$this->redirect('pages');
}
else{
$this->Session->setFlash("Pagina NU a fost salvata!", "flash/simpla_error");
}
}
}
The problem is that the model appeares to be saved and I am redirected as expected, but it doesn't get inserted into the database.
Using debug(Model) I saw that the id that the model is taking is incremented (like it is inserted and then deleted).
I used sql_dump - no trace of INSERT.
And, of course, no validation errors.
What am I missing ?
User this
This is my model
<?php
App::uses('AppModel', 'Model');
/**
* CarModel Model
*
* #property Manufacturer $Manufacturer
* #property Showroom $Showroom
*/
class CarModel extends AppModel {
/**
* Display field
*
* #var string
*/
public $displayField = 'model';
/**
* Validation rules
*
* #var array
*/
public $validate = array(
'manufacturer_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
),
),
'model' => 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(
'Manufacturer' => array(
'className' => 'Manufacturer',
'foreignKey' => 'manufacturer_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
/**
* hasMany associations
*
* #var array
*/
public $hasMany = array(
'Showroom' => array(
'className' => 'Showroom',
'foreignKey' => 'car_model_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'RequestCar' => array(
'className' => 'RequestCar',
'foreignKey' => 'car_model_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
?>
My controller
/**
* admin_add method
*
* #return void
*/
public function admin_add() {
$this->layout = 'admin_layout';
if ($this->request->is('post')) {
$this->CarModel->create();
if ($this->CarModel->save($this->request->data)) {
$this->Session->setFlash(__('The car model has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The car model could not be saved. Please, try again.'));
}
}
$manufacturers = $this->CarModel->Manufacturer->find('list');
$this->set(compact('manufacturers'));
}
$this->WebSubject->save();
saves nothing as there is no data! (Edit : this statement is wrong as said in comments.)
Put:
$this->WebSubject->save($this->request->data);
save() function docs