I created a site for fun to learn CakePHP but for some reason I can't get a multiple select dropdown box to show my selected items. In this example 1 video game can have multiple difficulties (easy, normal, hard). On my Game edit page I have a multi select box to pick the difficulties. It shows all three difficulties and I can select them and it saves correctly. However when I return to the edit page the items I previously saved do not show highlighted as selected. I have verified that the records are saving correctly in the database.
Tables:
games
difficulties
difficulties_games
Models:
class Game extends AppModel {
public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Difficulty' =>
array(
'className' => 'Difficulty',
'joinTable' => 'difficulties_games',
'foreignKey' => 'game_id',
'associationForeignKey' => 'difficulty_id',
'unique' => 'true'
)
);
}
class Difficulty extends AppModel {
public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Game' =>
array(
'className' => 'Game',
'joinTable' => 'difficulties_games',
'foreignKey' => 'difficulty_id',
'associationForeignKey' => 'game_id',
'unique' => 'true'
)
);
}
Controller:
$game = $this->Game->findById($id);
$this->set('difficulties', $this->Game->Difficulty->find('list'));
View (edit.ctp):
echo $this->Form->input('Difficulty');
This has to be something simple I am missing but I've read through the book on HABTM and searched here and couldn't find much on multi-select boxes.
UPDATE:
Here is the entire edit function in the controller:
public function edit($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$game = $this->Game->findById($id);
if (!$game) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is('post') || $this->request->is('put')) {
$this->Game->id = $id;
if ($this->Game->saveAll($this->request->data)) {
$this->Session->setFlash('Your game has been updated.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash($this->Game->invalidFields());
}
}
if (!$this->request->data) {
$this->request->data = $game;
}
$this->set('systems', $this->Game->System->find('list'));
$this->set('genres', $this->Game->Genre->find('list'));
$this->set('difficulties', $this->Game->Difficulty->find('list'));
}
Also here is some more on the View:
echo $this->Form->create('Game');
echo $this->Form->input('name');
echo $this->Form->input('system_id');
echo $this->Form->input('genre_id');
echo $this->Form->input('Difficulty');
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->end('Save Game');
What CakePHP version are you using? Releases 2.2.6 and 2.3.0 have a bug related to showing existing habtm selected. So updated to 2.2.7 if using 2.2.6 or if using 2.3.0 use the master branch from github until the next bugfix release is done.
For everyone who sets public $recursive = -1; in his AppModel due to performance reasons, or changes the recursion in his controller:
The automagic won't work without recursive 1! Make sure you change it in the options when retreiving your data for the edit.
$options = array(
'recursive' => 1,
'conditions' => array('YourModel.' . $this->YourModel->primaryKey => $id)
);
$this->request->data = $this->YourModel->find('first', $options);
Related
This my database:
http://gyazo.com/c6a86127d6f91aae947cf45ee535cecd
Example:
http://gyazo.com/c23fec3fabb7e4504c42453980fbc372
When I press the edit button , they able to retrieve the data however the page show me empty field instead of the field that have old data.
Secondly, unable to undate because they keep send empty id_field back to controller.
p.s. add,edit,delete method work totally fine.
Below are my code:
Model
<?php
App::uses('AppModel', 'Model');
class EventDate extends AppModel {
public $useTable = 'eventdate';
public $primaryKey = 'eventDate_id';
public $validate = array(
'event_date' => array(
'rule' => array('date','ymd'),
'message' => 'Enter a valid date in YY-MM-DD format.',
'required' => true,
'allowEmpty' => false
)
);
}
Controller
public function edit($id = null) {
//Retrieve from database
$post = $this->EventDate->findByEventdateId($id);
$this->set('edate', $post) ;
// debug($post);
//Without Id
if (!$id) {
throw new NotFoundException(__('Invalid Event Date'));
}
//If Not Exist the id
if (!$post) {
throw new NotFoundException(__('Invalid Event Date'));
}
//After press the submit
if ($this->request->is(array('post','put'))) {
$this->EventDate->eventDate_id = $id;
debug($_POST);
if ($this->EventDate->save($this->request->data)) {
$this->Session->setFlash(__('The Event has been saved.'));
return $this->redirect(array('action' => 'index'));}
else
{$this->Session->setFlash(__('The Event could not be saved. Please, try again.'));}
}
//Set the data same as retrieved
if (!$this->request->data) { $this->request->data = $post;}
}
edit.ctp
<h2>Edit Event</h2>
<?php
echo $this->Form->create('eventdate');
//echo $this->Form->input('eventDate_id', array('type' => 'hidden'));
echo $this->Form->hidden('eventDate_id');
echo $this->Form->input('event_date',array(
'label' => 'Event Date',
'type' => 'text',
'id' => 'datepicker'));
echo $this->Form->end('Save Post');
?>
Below link is the debug($_Post) been shown:
http://gyazo.com/5e569e6cc6b3026fc8896c315197a938
Should be:
echo $this->Form->create('EventDate'); // notice the capital CamelCase
Side note: The info that displays in the fields will be out-of-date, since you 1) get the data from the DB and set to var, THEN do the save based on posted data.
Another side note: There are quite a few things that you're doing that are non-standard and not consistent w/ the recommended conventions. Cleaning that up will make it easier to work with AND easier to receive help.
Using CakePHP 2.2.3
I'm nearly finished with my project and now going back through to setup authorization.
I'm implementing ACL, truncated both the users and groups tables for a fresh start, ran the command to recreate the aco/aro/aros_acos tables and have followed the tutorial.
When I create a group, it creates a corresponding ARO entry but the lft, and rght fields are NULL. I commented out all of my other code in the users/groups models and controllers to try to narrow it down, but it doesn't seem to help.
I will post my code below, with comments and validations removed for the sake of space.
group model:
App::uses('AppModel', 'Model');
class Group extends AppModel {
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' => ''
)
);
}
User model:
App::uses('AppModel', 'Model');
App::uses('AuthComponent', 'Controller/Component');
class User extends AppModel {
//setup ACL settings and function
public $actsAs = array('Acl' => array('type' => 'requester'));
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));
}
} // end parentNode()
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
AppController:
App::uses('Controller', 'Controller');
class AppController extends Controller {
public $components = array(
//'Security',
'Acl',
'Auth' => array(
'authorize' => array(
'Actions' => array('actionPath' => 'controllers')
)/*,
'authenticate' => array(
'Form' => array(
'scope' => array('User.activated' => 1 )
)
) */
),
'Session'
);
public $helpers = array(
'Html',
'Text',
'Session',
'Form'
);
/* public function isAuthorized($user = null) {
return true;
} */
public function beforeFilter(){
$this->Auth->loginRedirect = array('controller' => 'products', 'action' => 'index' );
$this->Auth->logoutRedirect = array('controller' => 'products', 'action' => 'index');
$this->Auth->authError = 'You are not allowed to see that.';
}
I even did an ACL implementation on a fresh install of cakephp 2.4.6, and everything works great. I have the projects side by side for comparison but can't find a difference in my ACL setup
Why aren't my lft and rght fields being set in my ARO table?
Short Answer: Remove MVC files associated with ACL tables.
Less Short Answer:
I setup ACL on a fresh install of cake 2.2.3, and everything worked great. Overwrote my code from my user and group models and controllers as well as AppController, and still no go.
I've seen a similar situation when I forget to add $actsAs = array('Tree'); to a model.
I realized I baked controllers/models/views for all ACL tables. DOH! (look for aroscontroller, acoscontroller, etc.)
I removed all the MVC files for these tables and it works great now.
This isn't a typical issue since normally one would add ACL schema after baking, but I started with a database I used on another project and forgot to remove the tables.
I really hope my stupidity helps someone else in this situation.
I am trying to get my edit to work I need the contact detail data to load when the user data loads. I have set the data in a similar manner to how I am retrieving the list of roles. I also don't know how to retrieve according to the model currently I was hard-coding it to retrieve 28. Would greatly appreciate any help provided.
public function edit($id = null) {
//Populate roles dropdownlist
$data = $this->User->Role->find('list', array('fields' => array('id', 'name')));
$this->set('roles', $data);
$data2 = $this->User->ContactDetail->find('first', array(
'conditions' => array('ContactDetail.id' =>'28')));
$this->set('contactdetails', $data2);
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
if ($this->request->is(array('post', 'put'))) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
$this->request->data = $this->User->find('first', $options);
}
}
my view is set up in the following manner
<?php echo $this->Form->create('User'); ?>
<fieldset>
<legend><?php echo __('Edit User'); ?></legend>
<?php
echo $this->Form->input('id');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('role_id');
echo $this->Form->input('ContactDetail.name');
echo $this->Form->input('ContactDetail.surname');
echo $this->Form->input('ContactDetail.address1');
echo $this->Form->input('ContactDetail.address2');
echo $this->Form->input('ContactDetail.country');
echo $this->Form->input('ContactDetail.email');
echo $this->Form->input('ContactDetail.fax');
?>
<label>Are you interested in buying property in Malta?</label>
<?php
$interest_buy = array('0'=>'no','1' => 'yes');
echo $this->Form->input('ContactDetail.interest_buy_property',array('type'=>'radio','options'=>$interest_buy,'value'=>'0','legend'=>FALSE));
?>
<label>Are you interested in renting property in Malta?</label>
<?php
$interest_rent = array('0'=>'no','1' => 'yes');
echo $this->Form->input('ContactDetail.interest_rent_property',array('type'=>'radio','options'=>$interest_rent,'value'=>'0','legend'=>FALSE));
echo $this->Form->input('ContactDetail.mobile');
echo $this->Form->input('ContactDetail.phone');
echo $this->Form->input('ContactDetail.postcode');
echo $this->Form->input('ContactDetail.town');
echo $this->Form->input('ContactDetail.newsletter',array('type'=>'checkbox','label'=>'Would you like to register for the newsletter?' ,'checked'=>'1','legend'=>FALSE,));
?>
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
User Model
public $primaryKey = 'id';
public $displayField = 'username';
public function bindNode($user) {
return array('model' => 'Role', 'foreign_key' => $user['User']['role_id']);
}
public function beforeSave($options = array()) {
$this->data['User']['password'] = AuthComponent::password(
$this->data['User']['password']
);
return true;
}
public $belongsTo = array(
'Role' => array('className' => 'Role'));
public $hasOne = array(
'ContactDetail' => array(
'foreignKey' => 'id'));
public $actsAs = array('Acl' => array('type' => 'requester', 'enabled' => false));
public function parentNode() {
if (!$this->id && empty($this->data)) {
return null;
}
if (isset($this->data['User']['role_id'])) {
$roleId = $this->data['User']['role_id'];
} else {
$roleId = $this->field('role_id');
}
if (!$roleId) {
return null;
} else {
return array('Role' => array('id' => $roleId));
}
}
}
ContactDetail Model
public $primaryKey = 'id';
public $displayField = 'name';
If I get you right, you have 1 contact details row for each user. In this case, you need to define in your User model:
public $hasOne = array(
'ContactDetail' => array(
'foreignKey' => 'id',
),
);
Like this, your ids will be synced in both tables. If you don't want to make the id a foreign key, you don't have to, it's just a suggestion.
Next, when you retrieve your data in the controller, you can do:
$this->User->Behaviors->load('Containable');
$user = $this->User->find('first', array(
'conditions' => array('User.id' => $id),
'contain' => array('ContactDetail'),
));
Now I don't know if there is an automated way to do this, but I sort my data manually to fill in the inputs. I am guessing you will get a structure like array('User' => array(), 'ContactDetail' => array()).
$user['User']['ContactDetail'] = $user['ContactDetail'];
unset($user['ContactDetail']);
$this->request->data = $user;
Then in your view just set the fields as the input array:
$this->Form->create('User');
$this->Form->input('User.some_user_field');
$this->Form->input('User.ContactDetail.some_contact_detail_field');
This should fill in your fields. When you go save your data, if your array is structured like this, you can use saveAssociated():
$this->User->saveAssociated($this->request->data, array('deep' => true));
EDIT
In case your relation is defined as User hasMany ContactDetail, then you need to structure your data like this:
$this->request->data = array(
'User' => array(
// user data
'ContactDetail' => array(
[0] => array(
//contact data
),
),
),
);
And in your view:
$this->Form->input('User.ContactData.0.field')
This is for 1 row only, If you need more rows on the child table with 1 input, do your logic accordingly.
Once your User model hasOne ContactDetail, you don't need retrieve the information twice, since you've done in $this->request->data line, all association model will retrieve too.
So, your Controller looks like this:
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid user'));
}
// Roles
$roles = $this->User->Role->find('list', array('fields' => array('id', 'name')));
$this->set(compact('roles');
if ($this->request->is(array('post', 'put'))) {
if ($this->User->saveAll($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->User->read(null, $id);
}
}
And your View, for ContactDetail's fields looks like this:
echo $this->Form->input('ContactDetail.name');
And so for all the fields related to the model ContactDetail. You can find more details here: Saving Your Data.
User model:
public $hasOne = array(
'ContactDetail' => array(
'className' => 'ContactDetail',
'foreignKey' => 'user_id',
'dependent' => true
)
);
The best solution I have found is by setting
public $belongsTo = array(
'Role' => array('className' => 'Role')
, 'ContactDetail' => array('className' => 'ContactDetail'));
This way the contact detail data loads. Although the data once saved does not update contactdetails.
For me to save I used
$this->User->saveAll($this->request->data)
this worked fully
For some reason i'm really having a hard time wrapping my head around HABTM associations. I learn best by watching someone do something and explaining why. Anyways, I have 2 tables I want associated, Drugs, and SideEffects. I've created the intermediate table drugs_side_effects(has no data right now). Does cake put the data in that automatically or do I need to do something? The 3.7.6.5 hasAndBelongsToMany (HABTM) from the book didn't specify.
I've set up the models correctly(I think) and am not sure how to proceed at this point. It seems pretty simple. I need to display side_effect from the SideEffects table in a Drug view. I think in the edit_french controller function i'll need something like
$side_effect = $this->Drug->SideEffect->read(
array('SideEffect.id','SideEffect.side_effect'), $id);
$this->set('side_effect',$side_effect);
but I feel like that won't work as expected. Or maybe there's a more efficient way? Any advice or help is appreciated.
Drug Model:
var $hasAndBelongsToMany = array(
'SideEffect' => array(
'className' => 'SideEffect',
'joinTable' => 'drug_side_effects',
'foreignKey' => 'drug_id',
'associationForeignKey' => 'side_effect_id'
)
);
}
?>
SideEffect Model:
var $hasAndBelongsToMany = array(
'Drug' => array(
'className' => 'Drug',
'joinTable' => 'drug_side_effects',
'foreignKey' => 'side_effect_id',
'associationForeignKey' => 'drug_id'
)
);
}
?>
Drugs Controller:
<?php
class DrugsController extends AppController {
var $name = 'Drugs';
var $helpers = array('Html','Form','Paginator');
var $paginate = array(
//'contain' => array('SideEffect'),
//'fields' => array('Drug.id', 'Drug.generic'),
'fields' => array('Drug.id', 'Drug.generic','Drug.date_altered'),
'limit' => 50,
'order' => array(
'Drug.generic' => 'asc'
)
);
function index() {
$data = $this->paginate('Drug');
$alldrugs = $this->set('drugs', $this->Drug->find('all'));
$this->set('drugs', $data);
$this->set('alldrugs', $data);
//$this->set('lessdrugs', $this->paginate());
$this->set('title_for_layout','List of all current drugs');
}
function edit_french($id = null) {
$this->Drug->id = $id;
$drug = $this->Drug->read(
array(
'Drug.id','Drug.generic','Drug.ahl','Drug.aap','Drug.rid','Drug.oral','Drug.mw','Drug.clinical_recommendations'
),
$id
);
$this->set('title_for_layout', 'Translate clinical recommendations - ' . $drug['Drug']['generic']);
$this->set('drug',$drug);
if (empty($this->data)) {
$this->data = $this->Drug->read();
} else {
if ($this->Drug->save($this->data)) {
$this->Session->setFlash('The drug has been updated.');
$this->redirect(array('action' => 'index'));
}
}
}
}
?>
You can pull the related data using ContainableBehavior. To do so, simply run a find on the Drug model and tell it to contain the associated SideEffect data.
$drug = $this->Drug->find('first', array(
'conditions' => array(
'Drug.id' => $id
),
'contain' => array(
'SideEffect'
)
));
You can also set the contain before using read() if you prefer.
$this->Drug->contain(array('SideEffect'));
$drug = $this->Drug->read(null, $id);
Using Containable allows you to gather all associated data in a single find() request.
Hello my problem is i try to save a new relation between a shop and a payment method
the relation is habtm... shop and payment already exist. i want to ad more payment methods.
But always when i save ,the old payment realtion in the shop_payment table is only updated, not a second one saved....
i read a lot i set unique to false but nothing changes that.
Anyone got an idea?
Model
class Payment extends AppModel {
var $hasAndBelongsToMany = array(
'Mainshop'=>array('className'=>'Mainshop', 'unique'=>'false')
);
}
View
echo $this->Form->create('Mainshop');
echo $this->Form->input('name',array('default'=>$mainshop['Mainshop']['name']));
echo $this->Form->input('Payment.id', array(
'type' => 'select',
'options' => array($payments),
));
echo $this->Form->input('id', array('type'=>'hidden','value'=>$mainshop['Mainshop'] ['id']));
echo $this->Form->end('Edit Shop');?>
Controller
if (!empty($this->data)){
$this->Mainshop->save($this->data);
$this->redirect(array('action' => 'edit',$this->data['Mainshop']['id']));
}
My recommendation defines the relationship with all fields in model:
var $hasAndBelongsToMany = array(
'Mainshop'=>array(
'className'=>'Mainshop',
'unique'=>'false',
'joinTable' => 'shop_payments',
'foreignKey' => 'payments_id',
'associationForeignKey' => 'shop_id'
)
);
In the controller add create():
if (!empty($this->data)){
$this->Mainshop->create();
$this->Mainshop->save($this->data);
$this->redirect(array('action' => 'edit',$this->data['Mainshop']['id']));
}