Adding associated value by not using foreign key in CakePHP 2 - php

Recently I've started using CakePHP by starting from using Bake to get simple CRUD.
I have one Model called "Contract" which is associated with "Product" and "Customer" as following.
public $belongsTo = array(
'Customer' => array(
'className' => 'Customer',
'foreignKey' => 'customer_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Product' => array(
'className' => 'Product',
'foreignKey' => 'product_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
Now I wanted to customize the add view (add.ctp) created by Bake by not using select box as an input form for customer_id and product_id. Instead of using select box which shows all the possible name of product/customer that are associated with foreign key I want to use text field so that people can type in one of the field (for example product_code, customer_code) from Product / Customer table and convert it to foreign key to create a row for Contract table. In case there is a chance that no values be found from Customer / Product field I want to skip adding a row to Contract table.
I would like to know if this is possible.
Thank you,

The basic concept is this: Use a JS lib of your choice, guess it's jquery. Watch the text field for changes, on change make an ajax GET request with the value of the text field to a controller / action of your app that returns json. On click on one of the results set the id of the selected record to a hidden field. Done.
If you search Google or Stackoverflow you'll find plenty of examples.

Related

how to add country column in prestashop AdminCustomersControllerCore

i want to add an extra column in AdminCustomersControllerCore so that it will show a new column in my back office manage customer page.
Use the hook actionControllerNameListingFieldsModifier to add fields.
Every admin controller calls this hook before generating the list/table.
Hook::exec('action'.$this->controller_name.'ListingFieldsModifier', array(
'select' => &$this->_select,
'join' => &$this->_join,
'where' => &$this->_where,
'group_by' => &$this->_group,
'order_by' => &$this->_orderBy,
'order_way' => &$this->_orderWay,
'fields' => &$this->fields_list,
));
You will need to modify select and fields variable to include your own. You might need to modify join variable as well if you have data in a custom table.

Implementing a custom filter in SugarCRM based on relationship ID

I've defined a many-to-many relationship between Accounts and a custom module (Tags). Tags have a subpanel in Accounts; however, I need a custom filter on Accounts that will show all the Accounts records related to the Tag name you type in.
/custom/Extension/modules/Accounts/Ext/clients/base/basic/filterAccountsByTag.php
$viewdefs['Account']['base']['filter']['basic']['filters'][] = array(
'id' => 'filterAccountsByTag',
'name' => 'LBL_FILTER_ACCOUNTS_BY_TAG',
'filter_definition' => array(
array(
'custom_tags_accountscustom_tags_ida' => array(
'$equals' => ' ',
),
),
array(
'name' => ''
)
),
'editable' => false,
'is_template' => false
);
To sum it up, I want to display the primary module results based upon a filter from a sub-module. Has anyone been through this? This is not a relate field; it's a relationship.
I hope this below article will help you.
Apply initial filter in relate fields and relationship fields with quick(popup) search sugarcrm 7.x

Yii create CButton Column for field that exists in another model

I'm trying to add the following functionality, however I'm not sure where to start. Any advice, examples, or direction would be greatly appreciated.
I want to add button to the cgridview of the main model in this context. Each of the records available in the cgridview for this model, have a unique attribute called lot for example R3XSEF9
There is another secondary table/model in my database that has records with this same lot attribute. However, this table only has certain records out of all the possible records, sometimes duplicates, and has a set of different attributes.
What I'd like to do is, using the lot attribute, for example lot R3XSEF9 from my cgridview, search the secondary table to see if there is one ore more corresponding rows which contains that same lot R3XSEF9.
If so, I would like the button to be displayed in my CButtonColumn and link to the views for those corresponding models of the secondary table. If not, I would like no button to appear.
Thanks for any help. If any clarification is required, I would be happy to do so.
First of all you need to link tables using "relations" function in model class. If you use FOREIGN KEY constraint in DB relations already filled.
SQL statement:
CREATE TABLE Model1
(
...
FOREIGN KEY(lot) REFERENCES MainModel(lot) ON UPDATE CASCADE ON DELETE RESTRICT,
...
)
Model class:
class MainModel extends CActiveRecord
{
...
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'lots' => array(self::HAS_MANY, 'Model2', 'lot'),
);
}
Then you can use custom button column in your grid (view file) like this:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'main-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
...
array(
'class' => 'CButtonColumn',
'template' => '{lots}',
'header' => 'Lots',
'buttons' => array(
'lots' => array(
'label' => 'Lots',
'imageUrl' => Yii::app()->request->baseUrl.'/img/....png',
'url' => 'Yii::app()->createUrl("controller1/lotlistbymainid", array("id" => $data->id))',
'visible' => 'count($data->lots) > 0',
),
),
),
Explanation of button parameters to be passed thru "buttons" array you can find here. Especialy this part:
buttons property
public array $buttons;
the configuration for additional buttons. Each array element specifies a single button which has the following format:
'buttonID' => array(
'label'=>'...', // text label of the button
'url'=>'...', // a PHP expression for generating the URL of the button
'imageUrl'=>'...', // image URL of the button. If not set or false, a text link is used
'options'=>array(...), // HTML options for the button tag
'click'=>'...', // a JS function to be invoked when the button is clicked
'visible'=>'...', // a PHP expression for determining whether the button is visible
)

Model Associations and Data Modelling

I am developing a web app for an art gallery, and I want to check I have set up the data model correctly.
I have a people table and an artists table. Some of the people are artists and some are not.
I also have a products table and each product belongs to one artist.
Below is a simplified version of the tables:
products
********
id
title
artist_id
artists
*******
id
profile
rating
person_id
people
******
id
first_name
last_name
I need to be able to retrieve the name of the artist when performing the find() method on the Product model.
Have I set up the data model correctly and if so what is the best way to retrieve the artist's name without getting lots of unwanted data?
It's possible to use CakePHP's bindModel & unbindModel to build up relations that don't rely on Cake's automagic goodness.
Since you were interested in doing the find on the Product model, I'll set out an example that can be called from the Products controller:
// unbind Artist
$this->Product->unbindModel(array(
'belongsTo' => array('Artist')
));
// bind Artist & Person using explicit conditions
$this->Product->bindModel(array(
'hasOne' => array(
'Artist' => array(
'foreignKey' => false,
'conditions' => array('Artist.id = Product.artist_id')
),
'Person' => array(
'foreignKey' => false,
'conditions' => array('Person.id = Artist.person_id')
),
)
));
// return the person
$person = $this->Product->find('first', array(
'conditions' => array(
'Product.id' => 1 // or any other condition
),
'fields' => array(
'Person.first_name',
'Person.last_name'
)
));
What's happening here?
Firstly, we unbind the Product model's relationship with the Artist model.
Secondly, we bind the Artist and Person models by explicitly defining the relationships and disabling Cake's automatic forigenKey connections.
Lastly, we do a 'first' find on the Product model and only request the 'first_name' & 'last_name' of the Person.
Each 'Product' belongs to an 'Artist' and each 'Artist' hasAndBelongsToMany 'Product'
You will also need the following table:
artists_products
****************
id
product_id
artist_id
http://book.cakephp.org/#!/view/1044/hasAndBelongsToMany-HABTM

CakePHP/Croogo: A veeery complex association

When I was working on my current project, I ran into a rather complex issue. I'll point out my problem much more detailed right now:
There are three Models: User, UsersExtendedField and UsersExtended.
UsersExtendedField contains custom fields that can be managed manually. All custom fields can be shown in the Users view as well, and be filled out of course. The values are then stored in UsersExtended, which has got two foreignKeys: user_id and field_id.
The relations look like this: User hasMany UsersExtendedField, UsersExtendedField hasMany UsersExtended, UsersExtended belongsTo User, UsersExtendedField.
The problem: When accessing the Users view, a form with user information input is shown. Any UsersExtendedFields are available as well, and since these hasMany UsersExtended, they've got plenty of UsersExtended values. But I want to reduce those to only the value(s) that belong to the User, whose view is shown at the moment. Here are my (desired) relations:
Croogo::hookBehavior('User', 'Crooboard.ExtendedUser', array(
'relationship' => array(
'hasMany' => array(
'UsersExtendedField' => array(
'className' => 'Crooboard.UsersExtendedField',
'foreignKey' => '',
'conditions' => array('status' => 1)
),
),
),
));
class UsersExtendedField extends AppModel {
var $name = 'UsersExtendedField';
var $displayField = 'fieldname';
var $hasMany = array(
'UsersExtended' => array(
'className' => 'Crooboard.UsersExtended',
'foreignKey' => 'field_id',
'conditions' => array(
'UsersExtended.user_id = User.id'
)
),
);
}
This is not the full code, these are the important parts. The problem starts right where I wrote 'UsersExtended.user_id = User.id'. Obviously, this won't work. But I do not have any idea how to access the User.id here. I also could not imagine a HABTM structure to solve this task. Do you have any idea how to get the semantics of this 'UsersExtended.user_id = User.id' to work?
Thank your very much for taking the time to read through this and helping me!
It sounds like you need to set up your HABTM relationship properly.
You already have the join table, UsersExtended, which contains your foreign keys.
Remove all previous relationships and set up HABTM in each of your User and UserExtendedField models.
The relationship code in your User model would look like this:
var $hasAndBelongsToMany = array(
'UsersExtended' => array(
'className' => 'UsersExtended',
'joinTable' => 'UsersExtended', //assuming this is the
//name of that model's table
'foreignKey' => 'user_id',
'associationForeignKey' => 'field_id'
)
);
For more information check out the page in the cakephp book
In addition, this blog post helped me grasp the relationship concepts when I was learning cakephp.

Categories