cakephp url not retrieving data - sql

hi all when clicking the link on my page its not carrying the id from the template when going to the view page, so when the sql queries the database it is querying this
SELECT `Field`.`name`
FROM `pra`.`fields` AS `Field`
LEFT JOIN `pra`.`templates` AS `Template` ON (
`Field`.`template_id` = `Template`.`id`)
WHERE `template`.`id` IS NULL
the database says id should be = 2
here is the code for the view function
$fields = $this->Field->find('all',
array('fields'=>array('name','template_id'),
'conditions' => array('template_id' => $this->Auth->user('template.id'))));
$this->set('field', $fields);
updated code, the template_id still equals null
when hardcoded it works correctly, there is a problem with this line $this->Auth->user

You can try with the following code:
$fields = $this->Field->find('all',
array('fields'=>array('name'),
'conditions' => array('Field.template_id' => $this->Auth->user('template_id'))
)
);
$this->set('field', $fields);
Please be sure there must have any template_id value should be there for the current logged in user.
Kindly ask if it not worked for you.

Check the result of the find call, by doing a debug:
debug($fields);
This will show you the returned data from the query. You can add this to the end of your action method.
If the results are empty, double check the values that are stored in the session Auth key. You can do this by dumping out the session with debug($_SESSION) or use the CakePHP DebugKit. The Debug Kit offers you a small toolbar at the top right of the screen and lets you view session information and such.

function view($name){
$this->set('title_for_layout', 'Create Template');
$this->set('stylesheet_used', 'homestyle');
$this->set('image_used', 'eBOXLogoHome.jpg');
$this->layout='home_layout';
$fields = $this->Template->Field->find('list',array(
'fields'=> array('name'),
'conditions' => array(
'template_id'=> $name)));
$this->set('field', $fields);
}
it wasn't passing the param's value

Related

Collecting a referenced app's values

I am trying to cleanup and optimize my come I am running on podio's API. What I am currently doing is using the filter query to return a collection from one app. I then loop over that collection. On each item I use Podio get_field_value to return the value(s) of a field in a referenced app. This creates a lot of API calls. I would like to retrieve everything in one API call Here is a simple version of my current code:
$collection = PodioItem::filter(WHSE_ID, array(
"filters" => array(
WHSE_EQUP_STATUS => array(2),
),
"sort_by" => WHSE_LOAD_IN,
"sort_desc" => false,
"limit" => 50
)
);
foreach ($collection as $item) {
// Table-A ID
$whId = $item->item_id;
// Referenced App Item(s)
$nucId = $item->fields[0]->values[0]->item_id;
// Get Referenced App Item Field
$app_b_value = PodioItem::get_field_value($nucId, NUC_LOAD_OUT);
echo $app_b_value;
}
Is there a more efficient way of doing this? I am thinking inline with the way you would use JOIN in a mysql query.
Thank you for any help you can provide!
if you are trying to get value from each item from filtered collection, you don't need to make podio calls each time.
Podio filter call will give you item with values. you just have to get value from each item.
like following
foreach ($podioFilterData['items'] as $itemData) {
$itemFields = $itemData['fields'];
foreach ($itemFields as $field) {
$value = $field['values'][0];
}
}

Yii with join using CDbCriteria and CActiveDataProvider with custom Search

Hi I am using Yii to create an Application
I have modified the search() in model and I have come up with a problem.
Users can log in as admins, managers, clients
When a user is logged as a manager, he can view clients only from the store they both belong. So far so good, I've managed to accomplish that.
Now the problem is when I try to prevent managers from viewing other managers from the same store (and therefore edit each other's accounts) in CGridView.
The relations
/**
* #return array relational rules.
*/
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(
'authitems' => array(self::MANY_MANY, 'Authassignment', 'authassignment(userid, itemname)'),
'additionalContacts' => array(self::HAS_MANY, 'AdditionalContact', 'Client_Id'),
'store' => array(self::BELONGS_TO, 'Store', 'Store_Id'),
'user' => array(self::BELONGS_TO, 'User', 'User_Id'),
'genericPoints' => array(self::HAS_MANY, 'GenericPoint', 'Client_Id'),
);
}
The Custom model search
public function searchCustom()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->addCondition('t.id !='.$this->id);
$criteria->compare('t.Created',$this->Created,true);
$criteria->compare('t.Updated',$this->Updated,true);
$criteria->compare('t.Discount',$this->Discount,true);
$criteria->compare('t.Discount_Type',$this->Discount_Type,true);
$criteria->addCondition('t.Store_Id ='.$this->Store_Id);
//$criteria->addCondition('t.id !='.$this->id);
//GET FIELDS FROM USER IN SEARCH
$criteria->with=array('user');
$criteria->compare('user.id',$this->User_Id,true);
$criteria->compare('user.First_Name',$this->First_Name,true);
$criteria->compare('user.Last_Name',$this->Last_Name,true);
$criteria->compare('user.Username',$this->Username,true);
$criteria->compare('user.Email',$this->Email,true);
$criteria->addCondition('user.Status = 1');
$criteria->with=array('authitems');
$criteria->compare('authitems.userid',$this->id,false);
$criteria->compare('authitems.itemname','client',false);
$criteria->together = true;
$criteria->order = 't.Created DESC';
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
And this the error I am getting
CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user.Status' in 'where clause'. The SQL statement executed was: SELECT COUNT(DISTINCT `t`.`id`) FROM `client` `t` LEFT OUTER JOIN `authassignment` `authitems_authitems` ON (`t`.`id`=`authitems_authitems`.`userid`) LEFT OUTER JOIN `authassignment` `authitems` ON (`authitems`.`itemname`=`authitems_authitems`.`itemname`) WHERE (((((t.id !=2) AND (t.Store_Id =1)) AND (user.Status = 1)) AND (authitems.userid=:ycp0)) AND (authitems.itemname=:ycp1))
I know it has something to do with the relations the gii set up for me but I can't pinpoint it.
Perhaps authitems' MANY_MANY relation stops the user relation from loading?
Instead of making another assignement for $criteria->with (which will override the previous one), you should simply try :
$criteria->with=array('user', 'authitems');

cakephp see the compiled SQL Query before execution

My query gets the timeout error on each run. Its a pagination with joins.
I want to debug the SQL, but since I get a timeout, I can't see it.
How can I see the compiled SQL Query before execution?
Some cake code:
$this -> paginate = array(
'limit' => '16',
'joins' => array( array(
'table' => 'products',
'alias' => 'Product',
'type' => 'LEFT',
'conditions' => array('ProductModel.id = Product.product_model_id')
)),
'fields' => array(
'COUNT(Product.product_model_id) as Counter',
'ProductModel.name'
),
'conditions' => array(
'ProductModel.category_id' => $category_id,
),
'group' => array('ProductModel.id')
);
First off, set the debug variable to 2 in app/config/config.php.
Then add:
<?php echo $this->element('sql_dump');?>
at the end of your layout. This should actually be commented out in your default cake layout.
You will now be able see all SQL queries that go to the database.
Now copy the query and use the SQL EXPLAIN command (link is for MySQL) over the database to see what the query does in the DBMS. For more on CakePHP debugging check here.
Since your script doesn't even render you can try to get the latest log directly from the datasource with:
function getLastQuery()
{
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
This needs to be in a model since the getDatasource() function is defined in a model.
Inspect the whole $logs variable and see what's in there.
One more thing you can do is ....
Go to Cake/Model/DataSource/DboSource.php and locate function execute() and print $sql variable.
That should print the sql.
This certainly is not be the cleanest way (as you are changing Cake directory) .. but certainly would be quickest just to debug if something is not working with sql.
Try...
function getLastQuery($model) {
$dbo = $model->getDatasource();
$logData = $dbo->getLog();
$getLog = end($logData['log']);
echo $getLog['query'];
}
Simple way to show all executed query of your given model:
$sqllog = $this->ModelName->getDataSource()->getLog(false, false);
debug($sqllog);
class YourController extends AppController {
function testfunc(){
$this->Model->find('all', $options);
echo 'SQL: '.$this->getLastQuery();
}
function getLastQuery()
{
$dbo = ConnectionManager::getDataSource('default');
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
}
or you can get all the query by adding following line in to the function execute() in lib/Cake/Model/DataSource.php
Debugger::dump($sql);
set the debug variable to 2 in app/config/config.php.
echo $this->Payment->save();
Out put like =>SQL Query: INSERT INTO photoora_photoorange.payments VALUES (*******)
[insert query][2]
set the debug variable to 2 in app/config/config.php.
And

My cgridview is showing only one record in yii

i am newbii in yii development and have an issue while displaying data using cgridview as it is showing only first record
Motel,Hotel,Roomcategory and halls are models in which PK and FK are passing ...
Code is here
$sponsorm = Motel::model()->find('MotelId=:MotelId', array(':MotelId'=>Yii::app()->user->id));
$sponsorhotel = Hotel::model()->find('hotelId=:hotelId', array(':hotelId'=>$sponsorm->MotelId));
$room = Roomcategory::model()->find('hotelId=:hotelId', array(':hotelId'=>$sponsorhotel->hotelId));
$halls = Halls::model()->find('hotelId=:hotelId', array(':hotelId'=>$sponsorhotel->hotelId));
echo CHtml::image(Yii::app()->request->baseUrl.'/img/4.png');
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'businessowner-grid',
'dataProvider'=>$room->search(),
//'filter'=>$sponsore,
'columns'=>array(
'roomCategoryNames',
'noOfRooms',
'price',
),
));
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'businessowner-grid',
'dataProvider'=>$halls->search(),
//'filter'=>$sponsore,
'columns'=>array(
'Type',
//'noOfHalls',
'seats',
'price',
),
));
Right now you are finding only one record because you use find to get one specific record. So you assign this record data to model variables and then you do
$model->search();
This searches from specific table multiple values but you have set the attributes so, that it matches only one record.
To get Motel gridview data use following code:
$sponsorm = $dataProvider=new CActiveDataProvider('Motel', array(
'criteria'=>array(
'condition'=>'MotelId = :MotelId',
'params' => array(':MotelId'=>Yii::app()->user->id)
),
));
It is doing the same as search() but the difference is that searching criteria is different. You can use also code below.
$motelModel = new Model();
$motelModel->MotelId = Yii::app()->user->id;
Now there is only one attribute assigned an is setting a criteria to match all rows what has this user id in MotelId field.
$modelModel->search();
Also, I see that you echo something between logic. Please do not do that. Output data only in views and keep the logic out of views. :)

Yii and database row in dropdown

I have two model: test1 , test2
And an action in test1 :
public function active_widgets_list()
{
$widgets = SiteWidget::model()->find('status=:status', array(':status' => '1'));
return $widgets;
}
And I will show test1.tbl_1 rows as dropdown list in test2's view:
$list=CHtml::listData(SiteWidget::model()->active_widgets_list(), 'id', 'title');
echo $form->dropDownList($model,'widget_id', $list, array('empty' => 'Select Please'));
but down't work. i have just an empty dropdown.
You should be using findAll instead of find, since find returns only a single active record with the specified condition.
$widgets = SiteWidget::model()->findAll('status=:status', array(':status' => '1'));
If you use Gii tools, You don't need any thing for saving. It generate all the codes you need it. It is so easy to make a huge of models, controllers, views and CRUD.
http://www.yiiframework.com/doc/guide/1.1/en/topics.gii