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']));
}
Related
I have a simple api that allows customers to book vehicles. In my reservations controller i have a function which is to add a reservation. Here is the code:
Controller
function add() {
if($this->request->is('post')) {
if($this->Reservation->save($this->data)) {
$this->Session->setFlash('The Reservation was successfully added!');
$this->redirect(array('action'=>'index'));
} else {
$this->Session->setFlash('The Reservation was not added.');
}
}
$this->set('title_for_layout','Add Reservation');
}
Here is what i have in my add view for a reservation.
View
<?php
echo $this->Form->create('Reservation', array('action'=>'add'));
echo $this->Form->input('customer_id', array( 'type' => 'text' ) );
echo $this->Form->input('vehicle_id', array( 'type' => 'text' ) );
echo $this->Form->input('date');
echo $this->Form->end('Add Reservation');
?>
But because i am adding a new reservation and i want a dropdown box for vehicle ids and one for customer ids how can i do this?
I think i have linked the models by putting this into the customers and vehicles models:
var $hasMany = array( 'Reservation' => array( 'className' => 'Reservation' ) );
Could anyone point me into the right direction so that a dropdown box would appear with a list of vehicle and customer IDs on the add reservation page.
In your add function in controller, use
$vehicle = $this->Reservation->Vehicle->find('list', array('fields' =>array('Vehicle.id','Vehicle.name')));
$this->set('vehicle', $vehicle);
In your view,use
<?php echo $this->Form->input('vehicle_id', array('type' => 'select',
'options' => $vehicle)); ?>
Use the same thing for customers also and you will get list of customers and vehicles in dropdown.
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);
I have a users and a posts table.
When I save the post it successfully saves it through HABTM (in posts_users table as well).
Now I want that post to be accessible to multiple user.
How can I add data in posts_users table alone so that post_id is now also associated with other user_id in the table users_posts ?
I have tried the following code:
<?php
echo $this->Form->create('Post');
echo $this->Form->input('User.id',array('value'=>34));
echo $this->Form->input('Post.id',array('value'=>34));
echo $this->Form->end('Save Post');
?>
I think what you want is the unique HABTM key:
public $hasAndBelongsToMany = array(
'Post' => array(
'className' => 'Post',
'foreignKey' => 'user_id',
'associationForeignKey' => 'post_id',
'joinTable' => 'posts_users',
'unique' => 'keepExisting'
)
);
I'm working on a small app to help learn cakephp 2.0. Its a simple task manager app.
Tables
users
tasks
tasktypes
I've a set up a foreign key in the tasks table called 'user_id'
As a task belongs to a user.
Now all I'm trying to do is display the tasks of a certain user and it wont work at all despite the sql query getting correct results when I tested it any help would be great.
In my taskscontroller I've the method;
//show the tasks of the current user
public function mytasks(){
$this->set('title_for_layout', 'Gerrys TaskManager: Display Tasks');
$this->Task->recursive = 0;
$tasks=$this->Task->find('all', array('conditions'=>array('username'=>'admin')));
$this->set('tasks', $this->paginate());
}
I'm trying to find the tasks of the user 'admin' or the "realted tasks" what am I doing wrong?
I suspect the problem maybe to with my models;
usermodel
/**
* hasMany associations
*
* #var array
*/
public $hasMany = array(
'Task' => array(
'className' => 'Task',
'foreignKey' => 'user_id'
)
);
task model;
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Tasktype' => array(
'className' => 'Tasktype',
'foreignKey' => 'tasktype_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
To get the tasks that belong to a user, it's much simpler to do that in the UsersController. Of course you have to set User hasMany Task in your UserModel.
Now you can create a function, for example to view the User and it's Tasks by id:
public function view($id = null) {
$this->User->id = $id;
$this->set('user', $this->User->read(null, $id));
}
The Tasks should now be available in your view by $user['tasks']. You have to pass the id in the url like: /path_to_your_app/users/view/1
You can always use debug() to see contents of an array or variable. To see what you've got add <?php debug($user);?> to your view.
You most likely want to list any tasks with a foreach in your view, very simple example::
foreach($user['Task'] as $task) {
echo $task['field1'] . ": " . $task['fied2'];
echo "<br />";
}
of course you might want to display the tasks in tables or something.
A good starting point for learning cakePHP is the Blog-Tutorial:
http://book.cakephp.org/2.0/en/getting-started.html#blog-tutorial
I have two issues with my CakePHP application (its my first one in CakePHP). I am trying to convert an old php website to cake.
1.Issue
I have my controller that accepts a parameter $id, but the data is comming from joined tables so in the cookbook it had something like this
MY Controller
dish_categories_controller.php
class DishCategoriesController extends AppController {
var $uses = array("DishCategory");
var $hasOne ='';
function get_categories($id)
{
$this->set('dishes',$this->DishCategory->find());
$this->layout = 'master_layout';
}
}
model
dish_category.php
class DishCategory extends AppModel{
var $name = 'DishCategory';
var $hasOne = array(
'Dish' => array(
'className' => 'Dish',
'conditions' => array('Dish.id' => '1'),
'dependent' => true
)
);
}
As you can see the Dish.id=> '1' is hard coded, how can make it dynamic there so that I pass a value and make it something like Dish.if =>$id ?.
So that was my first issue.
The second issue is related to the view
That model returns only one record, how can I make it so that it returns all and also how would I be able to loop through that, below the code in the view currently and the array format.
This is in my view
<?php
echo $dishes['DishCategory']['category_info'];
echo $dishes['DishCategory']['category_title'];
echo $dishes['Dish']['dish_name'];
echo $dishes['Dish']['dish_image'];
echo $this->Html->image($dishes['Dish']['dish_image'], array('alt' => 'CakePHP'))
?>
Array Format
Array ( [DishCategory] => Array
( [id] => 1 [category_name] => Appetizers
[category_keywords] => appetizer, appetizers
[category_title] => Our Side Dishes
[category_info] => Test Test
[dish_id] => 1 )
[Dish] => Array ( [id] => 1
[dish_name] => Rice
[dish_disc] => The Best flavor ever
[dish_price] => 2.90 [dish_image] => /img/rice_chicken.jpeg [dish_category_id] => 1
[dish_price_label] => Delicious Arepa ) )
I would appreciate your help to help me understand how to better do this. Thank you.
Firstly, you DishCategoriesController has model properties, you can remove them. In your controller, you will set up the conditions for the find like so:
class DishCategoriesController extends AppController {
function get_categories($id)
{
// find category with a dish of $id
$this->set('dishes', $this->DishCategory->find('all', array(
'conditions' => array(
'Dish.id' => $id
)
)));
// set master layout
$this->layout = 'master_layout';
}
}
Your DishCategory model will look very basic, you don't need to hard code the relationship condition:
class DishCategory extends AppModel {
/**
* hasOne associations
*
* #var array
*/
public $hasOne = array(
'Dish' => array(
'className' => 'Dish',
'foreignKey' => 'dish_category_id'
)
)
}
At this point it is worth noting that since the DishCategory hasOne Dish, using the above find query, it will only ever return a single result. But, it you were returning multiple results, you could loop through them in your view like so:
<?php foreach ($dishes as $key => $dish): ?>
<?php var_dump($dish) ?>
<?php endforeach ?>