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
Related
I have a relationship set up on a model with a primaryKey set to 'Document.guid' along with this i have an associated model DocumentVersion.
class Document extends DocumentAppModel {
public $hasMany = array(
'DocumentVersion' => array(
'className' => 'DocumentVersion',
'foreignKey' => false,
'finderQuery' => 'SELECT * FROM document_versions as `DocumentVersion` WHERE `DocumentVersion`.`document_guid` = {$__cakeID__$} ORDER BY `DocumentVersion`.`version` DESC LIMIT 1'
)
);
}
class DocumentVersion extends DocumentAppModel {
public $belongsTo = array(
'Document'
);
}
When i try and use a $this->Document->saveAll() it only saves the Document data and not the associated data. From my understanding it has something to do with the fact i am not using cakephp conventions to make my association.
My data structure
$filtered[] = array(
'Document' => array(
'guid' => $upload['guid'],
'database_revision' => Configure::read('Settings.LocalDataBaseRevision')
),
'DocumentVersion' => array(
array(
//'guid' => $upload['guid'],
'parent_guid' => (isset($upload['parent_guid'])) ? $upload['parent_guid'] : null,
'document_type_id' => $upload['type'],
'owner' => $upload['owner_id'],
'editor_id' => (isset($uplaod['editor_id'])) ? $uplaod['editor_id'] : null,
'title' => $upload['title'],
'crc' => (isset($upload['crc'])) ? $upload['crc'] : null,
'payload' => (isset($upload['payload'])) ? $upload['payload'] : null,
'database_revision' => Configure::read('Settings.LocalDataBaseRevision'),
'version' => 1 // Always set version number to 1 on uploads
)
)
);
I forgot the prefix the plugin name on the model relationship.
public $hasMany = array(
'Document.DocumentVersion' => array(
'className' => 'DocumentVersion',
'foreignKey' => false,
'finderQuery' => 'SELECT * FROM document_versions as `DocumentVersion` WHERE `DocumentVersion`.`document_guid` = {$__cakeID__$} ORDER BY `DocumentVersion`.`version` DESC LIMIT 1'
));
I was still getting the same issue at this point however i finally resolved the issue by using deep association in my save method.
$this->Document->saveAll($data, array('deep' => true));
Hello everyone can someone help me on this, i am trying to use Prestashop Objectmodel class for Adding, Deliting, Updating and Viewing Data from database, i have achieved retrieving data and displaying it on backoffice Form while clicking Edit button / deliting it from backoffice by clicking Delete option but stuck on saving or Updating it, here is my codes
Class file
<?php
class TestiBlock extends ObjectModel
{
public $id_blocktesti;
public $id_lang;
public $id_shop;
public $testi;
public $image;
public $name;
public $rank;
/**
* #see ObjectModel::$definition
*/
public static $definition = array(
'table' => 'blocktesti',
'primary' => 'id_blocktesti',
'multilang' => true,
'fields' => array(
'id_lang' =>array('type' => self::TYPE_NOTHING),
'id_shop' =>array('type' => self::TYPE_NOTHING),
'testi' => array('type' => self::TYPE_HTML),
'image' => array('type' => self::TYPE_STRING),
'name' => array('type' => self::TYPE_STRING),
'rank' => array('type' => self::TYPE_STRING),
)
);
}
here is my code for rendering Form
protected function renderForm()
{
$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
$fields_form = array(
'tinymce' => true,
'legend' => array(
'title' => $this->l('New Testimonial'),
'image' => '../img/admin/tab-categories.gif',
),
'input' => array(
array(
'type' => 'hidden',
'name' => 'id_blocktesti',
),
array(
'type' => 'file',
'label' => $this->l('Profile Picture'),
'name' => 'image',
'required' => false,
'hint' => $this->l('Upload a image from your computer.').' (.gif, .jpg, .jpeg '.$this->l('or').' .png)'
),
array(
'type' => 'text',
'label' => $this->l('Person\'s Name'),
'required' => false,
'name' => 'name',
'hint' => $this->l('Name of The Person made testimony.')
),
array(
'type' => 'text',
'label' => $this->l('Designation or Rank'),
'required' => false,
'name' => 'rank',
'hint' => $this->l('Degignation, Rank or Job Title of person.')
),
array(
'type' => 'textarea',
'label' => $this->l('Testimonial'),
'required' => false,
'lang' => false,
'name' => 'testi',
'cols' => 40,
'rows' => 10,
'class' => 'rte',
'autoload_rte' => true,
),
),
'submit' => array(
'title' => $this->l('Save'),
),
'buttons' => array(
array(
'href' => AdminController::$currentIndex.'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'),
'title' => $this->l('Back to list'),
'icon' => 'process-icon-back'
)
)
);
if (Shop::isFeatureActive() && Tools::getValue('id_blocktesti') == false)
{
$fields_form['input'][] = array(
'type' => 'shop',
'label' => $this->l('Testimonial association'),
'name' => 'checkBoxShopAsso_theme'
);
}
$helper = new HelperForm();
$helper->module = $this;
$helper->name_controller = 'blocktesti';
$helper->identifier = $this->identifier;
$helper->token = Tools::getAdminTokenLite('AdminModules');
foreach (Language::getLanguages(false) as $lang)
$helper->languages[] = array(
'id_lang' => $lang['id_lang'],
'iso_code' => $lang['iso_code'],
'name' => $lang['name'],
'is_default' => ($default_lang == $lang['id_lang'] ? 1 : 0)
);
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
$helper->default_form_language = $default_lang;
$helper->allow_employee_form_lang = $default_lang;
$helper->toolbar_scroll = true;
$helper->title = $this->displayName;
$helper->submit_action = 'saveblocktesti';
$helper->fields_value = $this->getFormValues();
return $helper->generateForm(array(array('form' => $fields_form)));
}
and here is code for processing it
public function getContent()
{
$id_info = (int)Tools::getValue('id_blocktesti');
if (Tools::isSubmit('saveblocktesti'))
{
$info = new TestiBlock((int)$id_info);
$info->save();
Tools::redirectAdmin(AdminController::$currentIndex.'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'));
}
elseif (Tools::isSubmit('updateblocktesti') || Tools::isSubmit('addblocktesti'))
{
$this->html .= $this->renderForm();
return $this->html;
}
else if (Tools::isSubmit('deleteblocktesti'))
{
$info = new TestiBlock((int)$id_info);
$info->delete();
Tools::redirectAdmin(AdminController::$currentIndex.'&configure='.$this->name.'&token='.Tools::getAdminTokenLite('AdminModules'));
}
else
{
$this->html .= $this->renderList();
return $this->html;
}
}
and here is my db structure:
CREATE TABLE IF NOT EXISTS ps_blocktesti (
id_blocktesti int(2) unsigned NOT NULL AUTO_INCREMENT,
id_lang int(10) unsigned NOT NULL DEFAULT '1',
id_shop int(2) unsigned NOT NULL,
testi text NOT NULL,
image varchar(255) NOT NULL,
name varchar(255) NOT NULL,
rank varchar(255) NOT NULL,
PRIMARY KEY (id_blocktesti)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS ps_blocktesti_lang (
id_blocktesti int(11) NOT NULL,
id_shop int(10) NOT NULL,
id_lang int(10) NOT NULL,
text text NOT NULL,
PRIMARY KEY (id_shop,id_lang)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Any help would be highly appreciated, thanks in advance.
PS Note i am using blockcmsinfo for above project.
I am having an issue where CakePHP is ignoring saving a field I specify and instead creating extra records. I am using CakePHP 2.3.6.
My table looks like this:
CREATE TABLE `events_guests` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`guest_id` int(11) NOT NULL,
`event_id` int(11) NOT NULL,
`promoter_id` int(11) DEFAULT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`attended` varchar(15) NOT NULL DEFAULT 'No',
PRIMARY KEY (`id`)
)
Heres the code
public function addGuest($event_id, $promoter_id = null) {
if ($this->request->is('post')) {
$this->Guest->create();
$event_data = array('event_id' => $event_id);
$data = $this->request->data;
$data['Event'] = $event_data;
if($promoter_id) {
$data['Event']['promoter_id'] = $promoter_id;
}
if ($this->Guest->saveAssociated($data)) {
$this->Session->setFlash(__('The guest has been added to the guestlist'), 'flash/success');
} else {
$this->Session->setFlash(__('The guest could not be saved. Please, try again.'), 'flash/error');
}
Here is my data that I am trying to save:
Array (
[Guest] => Array
(
[first_name] => Joe
[last_name] => Schmoe
)
[Event] => Array
(
[event_id] => 1
[promoter_id] => 2
)
)
My Models follow:
class Guest extends AppModel {
public $hasAndBelongsToMany = array(
'Event' => array(
'className' => 'Event',
'joinTable' => 'events_guests',
'foreignKey' => 'guest_id',
'associationForeignKey' => 'event_id',
'unique' => 'true',
),
'Promoter' => array(
'className' => 'Promoter',
'joinTable' => 'events_guests',
'foreignKey' => 'guest_id',
'associationForeignKey' => 'promoter_id',
'unique' => 'true',
)
);
}
And
class Event extends AppModel {
public $hasAndBelongsToMany = array(
'Guest' => array(
'className' => 'Guest',
'joinTable' => 'events_guests',
'foreignKey' => 'event_id',
'associationForeignKey' => 'guest_id',
'unique' => 'keepExisting',
'order' => 'last_name',
),
'Promoter' => array(
'className' => 'Promoter',
'joinTable' => 'events_promoters',
'foreignKey' => 'event_id',
'associationForeignKey' => 'promoter_id',
'unique' => 'keepExisting',
)
);
}
The results from this are 2 records for EventsGuests, neither with a promoter_id.
One record receives event_id = 1 AS EXPECTED
Other record receives event_id = 2, which is actually the promoter_id
I have tried using a mix of saveAssociated and saveAll
Any help is greatly appreciated! Thank you!
Reference: Cakephp save extra attribute in HABTM relation
For your problem, don't use HABTM, because, HABTM is normally use for connect 2 tables.
So, if you have more than 2 fields, create a model and use it like belongsTo and hasMany relationships.
class Event extends AppModel {
$hasMany = array(
'EventGuest' => array(
'className' => 'EventGuest',
'foreignKey' => 'event_id'
)
);
}
class Guest extends AppModel {
$hasMany = array(
'EventGuest' => array(
'className' => 'EventGuest',
'foreignKey' => 'guest_id'
)
);
}
class Promoter extends AppModel {
$hasMany = array(
'EventGuest' => array(
'className' => 'EventGuest',
'foreignKey' => 'promoter_id'
)
);
}
Now, your relationship model.
class EventGuest extends AppModel {
$belongsTo = array(
'Event' => array(
'className' => 'Event',
'foreignKey' => 'event_id'
),
'Guest' => array(
'className' => 'Guest',
'foreignKey' => 'guest_id'
),
'Promoter' => array(
'className' => 'Promoter',
'foreignKey' => 'promoter_id'
)
);
}
And continue use your code.
public function addGuest($event_id, $promoter_id = null) {
if ($this->request->is('post')) {
$this->Guest->create();
$event_data = array('event_id' => $event_id);
$data = $this->request->data;
$data['Event'] = $event_data;
if($promoter_id) {
// EDITED
$data['Promoter']['promoter_id'] = $promoter_id;
}
if ($this->Guest->saveAssociated($data)) {
$this->Session->setFlash(__('The guest has been added to the guestlist'), 'flash/success');
} else {
$this->Session->setFlash(__('The guest could not be saved. Please, try again.'), 'flash/error');
}
}
}
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' => ''
)
);
I am following the
http://book.cakephp.org/2.0/en/tutorials-and-examples/simple-acl-controlled-application/simple-acl-controlled-application.html tutorial and I am at the part where you add the group and user accounts...
However, when I access to add new user, the drop down for the group is is empty... What can be wrong?
here is how User.php model looks like
<?php
App::uses('AppModel', 'Model');
/**
* User Model
*
* #property Group $Group
* #property Image $Image
*/
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
/**
* Display field
*
* #var string
*/
//The Associations below have been created with all possible keys, those that are not needed can be removed
public $actsAs = array('Acl' => array('type' => 'requester'));
public function beforeSave() {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
return true;
}
public function bindNode($user) {
return array('model' => 'Group', 'foreign_key' => $user['User']['group_id']);
}
public function parentNode() {
if (!$this->id && empty($this->data)) {
return null;
}
if (isset($this->data['User']['group_id'])) {
$groupId = $this->data['User']['group_id'];
} else {
$groupId = $this->field('group_id');
}
if (!$groupId) {
return null;
} else {
return array('Group' => array('id' => $groupId));
}
}
public $belongsTo = array(
'Group' => array(
'className' => 'Group',
'foreignKey' => 'group_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
public $hasMany = array(
'Image' => array(
'className' => 'Image',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
Here is how Group.php model looks like
<?php
App::uses('AppModel', 'Model');
/**
* Group Model
*
* #property User $User
*/
class Group extends AppModel {
/**
* Display field
*
* #var string
*/
public $displayField = 'name';
/**
* Validation rules
*
* #var array
*/
//The Associations below have been created with all possible keys, those that are not needed can be removed
/**
* hasMany associations
*
* #var array
*/
public $actsAs = array('Acl' => array('type' => 'requester'));
public function parentNode() {
return null;
}
public $hasMany = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'group_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
my tables look like this
'users' table
> > Field Type Null Key Default Extra
> > id int(11) NO PRI NULL auto_increment
> > username varchar(64) NO UNI NULL password varchar(82) NO NULL
> > first_name varchar(64) NO NULL last_name varchar(64) NO NULL
> > created datetime YES NULL group_id int(11) NO NULL
'groups' table
Field Type Null Key Default Extra
id int(11) NO PRI NULL auto_increment
name varchar(100) NO NULL
created datetime YES NULL
modified datetime YES NULL
View/Users/add.ctp code
<div class="users form">
<?php echo $this->Form->create('User');?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('first_name');
echo $this->Form->input('last_name');
echo $this->Form->input('group_id');
?>
</fieldset>
<?php echo $this->Form->end(__('Submit'));?>
</div>
<div class="actions">
<h3><?php echo __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('List Users'), array('action' => 'index'));?></li>
<li><?php echo $this->Html->link(__('List Groups'), array('controller' => 'groups', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Group'), array('controller' => 'groups', 'action' => 'add')); ?> </li>
<li><?php echo $this->Html->link(__('List Images'), array('controller' => 'images', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Image'), array('controller' => 'images', 'action' => 'add')); ?> </li>
</ul>
</div>
I created 2 groups. One is "visitors" and one is "admin"..
here is how aros table looks like right now now
id parent_id model foreign_key alias lft rght
2 NULL Group 4 1 2
3 NULL Group 5 3 4
Have you added group first? First you have to add the group then try adding the user.
Please verify you have a belongsTo relationship setup in the user model User.php
public $belongsTo = array(
'Group' => array(
'className' => 'Group',
'foreignKey' => 'group_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Check your UserController Add method has the following code
Please verify the $groups = $this->User->Group->find('list');
$this->set(compact('groups')); part
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
$groups = $this->User->Group->find('list');
$this->set(compact('groups'));
}