I have a site develop in cakephp 2.0.
I have a relation HABTM to the same model like this:
class Product extends AppModel {
public $name = 'Product';
public $useTable = 'products';
public $belongsTo = 'User';
public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Product' => array(
'className' => 'Product',
'joinTable' => 'ingredients_products',
'foreignKey' => 'product_id',
'associationForeignKey' => 'ingredient_id',
'unique' => false
)
);
}
I want to save a record into my view with a simple form like this:
echo $this->Form->create('IngredientProduct', array ('class' => 'form', 'type' => 'file'));
foreach ($product as $prod) {
echo '<div>'.$prod['ProductAlias']['alias'].'</div>';
echo $this->Form->input('IngredientProduct.product_id', array ('type'=>'text', 'value'=> $prod['ProductAlias']['id'], 'label'=> false, 'id' => 'id'));
}
$select = '<select name="data[IngredientProduct][ingredient_id]" id="[IngredientProductIngredientId">';
foreach ($other_product as $prod2) {
$select .= '<option value="'.$prod2['ProductAlias']['id'].'">'.$prod2['ProductAlias']['alias'].'</option>';
}
$select .= '</select><br>';
echo($select);
echo $this->Form->submit('Collega', array('id'=>'link_product'));
echo $this->Form->end();
Into my controller I save in this mode:
if ($this->Product->saveAll($this->request->data)){
$this->Session->write('flash_element','success');
$this->Session->setFlash ('Prodotto collegato con successo.');
//$this->redirect(array('action'=>'edit',$alias));
}
else{
$this->Session->write('flash_element','error');
$this->Session->setFlash('Errore di salvataggio activity');
}
When I'm going to see into the database I see that ingredient:id is setting well but product_id is 0.
I have debugged my request->data and this is the array:
array(
'IngredientProduct' => array(
'product_id' => '1',
'ingredient_id' => '2'
)
)
I have print the sql query created by cakephp:
INSERT INTO `db`.`ingredients_products` (`product_id`, `ingredient_id`, `modified`, `created`) VALUES ('', 2, '2012-10-09 23:19:22', '2012-10-09 23:19:22')
Why product_id is null instead of 1?
Can someone help me?
Thanks
I think this line is wrong:
$this->Product->saveAll($this->request->data);
Try:
$this->IngredientProduct->saveAll($this->request->data);
as your form seems to ask data for a relationship, not a new product.
Related
I'm working in a web aplication for board role playing games management. Its very simple for now.
I have 3 tables:
(1) Game
* id
* title
* user_id (game master)
(2) Sheet
* id
* name
* game_id
* user_id
(3) Users
* id
* username
Well, I have two problems:
1 - In Sheet view, i cant show the game tittle or the user name, just his id's
2 - In Game view, I cant show the user name (the game master).
I try a lot of answers found here for similar problems, but nothing works. I'm i little bit frustrated :( please help.
Here my code details:
MODELS:
/*User Model*/
class User extends AppModel {
public $name = 'User';
public $hasMany = array(
'Sheet' => array(
'className' => 'Sheet',
'foreignKey' => 'user_id'
),
'Game' => array(
'className' => 'Game',
'foreignKey' => 'user_id'
)
);
}
/*Game Model*/
class Game extends AppModel {
public $name = 'Game';
public $belongsTo = array(
'Master' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
public $hasMany = array (
'Chars' => array (
'className' => 'Sheet',
'foreignKey' => 'game_id'
)
);
}
/*Sheet Model*/
class Sheet extends AppModel {
public $name = 'Sheet';
public $belongsTo = array (
'Party' => array (
'className' => 'Game',
'foreignKey' => 'game_id'
),
'Player' => array (
'className' => 'User',
'foreignKey' => 'user_id'
)
);
}
CONTROLLERS:
/*SheetController*/
class SheetController extends AppController {
public $helpers = array('Html', 'Form');
var $name = 'Sheets';
public function view($id = null) {
$this->Sheet->id = $id;
$this->Sheet->recursive = 2;
if (!$this->Ficha->exists()) {
throw new NotFoundException(__('La ficha no existe'));
}
$this->set('sheet', $this->Sheet->read(null, $id));
}
}
class PartidasController extends AppController {
public $helpers = array('Html', 'Form');
var $name = 'Partidas';
public function view($id) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$this->Partida->recursive=2;
$partida = $this->Partida->findById($id);
if (!$partida) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('partida', $partida);
}
}
VIEWS:
/*Game View*/
<?php echo $game['Game']['title']; ?>
<strong>Master: </strong>
<?php
echo $this->Html->link($game['Game']['user_id'], array('controller' => 'Users','action' => 'view',$game['Game']['user_id'])); ?>
/*Sheet View*/
<?php echo $this->Html->link($sheet['Sheet']['nombreFicha'],array('controller' => 'sheets', 'action' => 'view', $sheet['Sheet']['id']));?>
<?php echo $this->Html->link($sheet['Sheet']['user_id'],array('controller' => 'users', 'action' => 'view', $sheet['Sheet']['user_id'])); ?>
<?php echo $this->Html->link($sheet['Sheet']['game_id'],array('controller' => 'games', 'action' => 'view', $sheet['Sheet']['game_id'])); ?>
In CakePHP I've a model Customer which looks like this:
<?php
class Customer extends AppModel {
public $hasMany = array(
'Invoice' => array(
'className' => 'Invoice',
)
);
public function getDisplayName($id){
$customer = new Customer();
$customer_array = $customer->find('first', array(
'conditions' => array('Customer.id' => $id)
));
if($customer_array['Customer']['company']){
return $customer_array['Customer']['company'];
} else {
return $customer_array['Customer']['frontname'] . ' ' . $customer_array['Customer']['lastname'];
}
}
public function getFullName($id){
$customer = new Customer();
$customer_array = $customer->find('first', array(
'conditions' => array('Customer.id' => $id)
));
return $customer_array['Customer']['frontname'] . ' ' . $customer_array['Customer']['lastname'];
}
}
?>
In an other view (Project) I want to show a list of customers with there display name (because some of them have an company and others don't).
So in the ProjectController I added this:
$customers = $this->Project->Customer->find('list', array(
'fields' =>array(
'Customer.id', $this->Project->Customer->getDisplayName('Customer.id')
),
'conditions' => array(
'Customer.cloud_id' => '1'
)
));
$this->set('customers', $customers);
But then I get an MySQL error because the second field isn't a databasecolumn.
Who can help me with this question?
Your best best would be using virtual fields in your Customer model:
See the docs: http://book.cakephp.org/2.0/en/models/virtual-fields.html
<?php
class Customer extends AppModel {
public $hasMany = array(
'Invoice' => array(
'className' => 'Invoice',
)
);
public $virtualFields = array(
'display_name' => 'IF(Customer.company IS NOT NULL, Customer.company, CONCAT_WS(' ', Customer.frontname, Customer.lastname))'
);
}
?>
Then in projects controller:
<?php
$customers = $this->Project->Customer->find('list', array(
'fields' =>array(
'Customer.id', 'Customer.display_name'
),
'conditions' => array(
'Customer.cloud_id' => '1'
)
));
$this->set('customers', $customers);
?>
To answer the question more generally (here the virtual fields solutions works fine), you could rewrite the getDisplayName function and put in in your Controller.
Then you could call it from the view using
$displayName= $this->requestAction(array(
'controller'=>'CustomersController',
'action'=>'getDisplayName ')
);
echo $displayName;
I'm Using cakePHP 2.3.8
I have two tables: application, computer_application. The relationship is one application hasMany computer_application, foreign key is application_id
in my ComputerApplication model:
class ComputerApplication extends AppModel{
public $name = "ComputerApplication";
public $useTable = "computer_application";
var $belongsTo = array(
'Computer' => array(
'className' => 'Computer',
'foreignKey' => 'computer_id',
'dependent' => true
),
'Application' => array(
'className' => 'Application',
'foreignKey' => 'application_id',
'dependent' => true
)
);
}
In my ComputerApplication controller. HERE I INITIALIZE THE POPULATION OF DROPDOWN in **add** function
public function add($id=null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('computerApplications',
$this->ComputerApplication->Application->find('list',
array('fields' => array('description') ) ) );
}
Now In my Add View
echo $this->Form->create("computerApplication");
echo $this->Form->input('application_id',array('empty'=>''));
echo $this->Form->end('Save Post');
My problem is that it won't populate the select input. This is the first time I used 2 words in table [computer_application] using cake since I don't have problem populating other table with just one word. Just help me identify which I need to tweak for it to populate.
$this->set('applications', ...
and not
$this->set('computerApplications', ...
Ok this is kind of hard to explain but I'll try my best.
I have 3 tables
companies products product_availabilities
--------- -------- ----------------------
id id id
name name company_id
product_id
buys (tinyint)
sells (tinyint)
And their models
class Company extends AppModel
{
public $name = 'Company';
public $hasMany = array(
'ProductAvailability'
);
class Product extends AppModel
{
public $name = 'Product';
public $hasMany = array(
'ProductAvailability'
);
class ProductAvailability extends AppModel
{
public $name = 'ProductAvailability';
public $belongsTo = array(
'Company',
'Product'
);
}
What I want to do is when I create a company, I want to be able to select products that the company buys or sells. I've seen an example of a hasMany through relationship in the book (http://book.cakephp.org/1.3/view/1650/hasMany-through-The-Join-Model) but they are creating the form from the "join table" controller. Is it possible to bind the productAvailability model to my company model to be able to select the products while creating the company?
Edit : Here is how I've done it. I know it is not optimal as there is a lot of looping involved but it works.
Company controller :
$products = $this->Company->ProductAvailability->Product->find('list', array('fields' => array('Product.id', 'Product.label')));
$this->set('products', $products);
if($this->request->is('post')){
if($this->Company->save($this->request->data)){
foreach($products as $product)
{
$tmpArray = array(
'company_id' => $this->Company->id,
'product_id' => $product['Product']['id']
);
foreach($this->request->data('BuyProducts.product_id') as $buyProduct)
{
if($buyProduct == $product['Product']['id'])
$tmpArray['buys'] = 1;
}
foreach($this->request->data('SellProducts.product_id') as $sellProduct)
{
if($sellProduct == $product['Product']['id'])
$tmpArray['sells'] = 1;
}
if(count($tmpArray) > 2)
{
$this->Company->ProductAvailability->create();
$this->Company->ProductAvailability->set($tmpArray);
$this->Company->ProductAvailability->save();
}
}
$this->Session->setFlash('Yay', 'success');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Nay', 'error');
}
}
Company add form :
<?php echo $this->Form->create('Company'); ?>
<?php echo $this->Form->input('name', array( 'div' => 'full-form')); ?>
<?php echo $this->Form->input('BuyProducts.product_id', array('multiple' => 'checkbox', 'options' => $products, 'div' => 'full-form', 'label' => false)); ?>
<?php echo $this->Form->input('SellProducts.product_id', array('multiple' => 'checkbox', 'options' => $products, 'div' => 'full-form', 'label' => false)); ?>
<?php echo $this->Form->end(array('label' => __('Save'), 'div' => 'center', 'class' => 'bouton-vert')); ?>
You have two options. Either let cakePHP do some magic with the hasAndBelongsToMany relationship or doing it manually which is necessary if you add attributes to the join table
1. CakePHP HABTM
Using the capabilities of CakePHP and making a straight forward solution I would make these changes:
Model
If one company has more than one product, and the products belong to many companies. It is a hasAndBelongsToMany relationship between Company<->Product
// company.php
...
var $hasAndBelongsToMany = array(
'Product' => array(
'className' => 'Product',
'joinTable' => 'companies_products',
'foreignKey' => 'company_id',
'associationForeignKey' => 'product_id',
'unique' => true,
)
);
...
// similar in product.php
Add the required table 'companies_products' in the database.
Controller
Then in the add function from the Company Controller there should be something like:
$products = $this->Company->Product->find('list');
$this->set(compact('products'));
View
Finally insert the products in the add.ctp, the select should allow multiple selections and let cakePHP do some magic, like this:
echo $this->Form->input('products', array(
'label' => 'Products to buy (Ctr+multiple choice)'
'type' => 'select',
'multiple' => true,
));
2. Manually
When the HABTM becomes more 'exotic' and includes some attributes like in your case 'buy' or 'sell' you need to do the manual way. This is in the Product Controller setting manually the fields before inserting them in the database. Something like:
foreach($availableProducts as $availableProduct ){
$this->Product->ProductAvailabilities->create();
$this->Product->ProductAvailabilities->set( array(
'company_id' => $this->Product->id,
'product_id' => $availableProduct['Product']['id'],
'buys' => $availableProduct['Product']['buy'],
'sells' => $availableProduct['Product']['sell']
// or however you send it to the controller
));
$this->Product->ProductAvailabilities->save();
}
Let's hope this helps you ...
you are planning a habtm-relationship (m:n) with the possibility to have extra fields in the join table. Even though this can be done with regular habtm I prefer the way you choose and implement the m:n as 1:n:1, which is simply the same and gives you more options when saving your data.
Here is a similar question and answer
As for your question: You can collect the the data from your products table like this:
$this->Company->ProductAvailability->Product->find('all', $params);
Also you might want to have a look at the containable-behaviour which is very useful for this use case:
$params['conditions'] = array(
'Company.id' => $id
);
$params['contain'] => array(
'ProductAvailability' => array(
'conditions' =>array(
'buys' => 1
),
'Product' => array(
'order' => array(
'name' => 'ASC'
)
)
)
);
$this->Company->find('all', $params);
I have two tables:
evaluation_employees
Fields: id, username
evaluation_results
Fields: id, grade, evaluation_employee_id
In evaluation_results view I need to search the results (using the cakephp search plugin) by the employee's username, but in evaluation_results table I have the employee's id(evaluation_employee_id), not the username. I don't know how to make a link between those tables, to make it work.
Code in my view (evaluation_results/index.ctp):
echo $this->Form->create('EvaluationResult', array(
'url' => array_merge(array('action' => 'index'), $this->params['pass'])
));
echo $this->Form->input('username', array('div' => false, 'empty' => true)) . '<br/><br/>';
echo $this->Form->submit(__('Search', true), array('div' => false));
echo $this->Form->end();
Code in my controller (evaluation_results_controller.php):
var $components = array('Search.Prg');
function index() {
$this->Prg->commonProcess();
$this->EvaluationResult->recursive = 0;
$this->paginate = array(
'conditions' => $this->EvaluationResult->parseCriteria($this->passedArgs));
$this->set('evaluationResults', $this->paginate());
}
Code in my model (evaluation_result.php):
public $actsAs = array('Search.Searchable');
//Search fields data description for processing.
public $filterArgs = array(
array('name' => 'EvaluationEmployee.username', 'type' => 'query', 'method' => 'filterUsername')
);
//Method as decalred in $filterArgs to process the free form search.
public function filterUsername($data, $field = null) {
if (empty($data['EvaluationEmployee']['username'])) {
return array();
}
$username = '%' . $data['EvaluationEmployee']['username'] . '%';
return array(
$this->alias . '.EvaluationEmployee.username LIKE' => $username
);
}
Please tell me if more info is needed.
If you set up the associations in the model it will find all related records automatically when you search for an employee.
http://book.cakephp.org/1.3/en/view/1039/Associations-Linking-Models-Together