"Error: SQLSTATE[42S22]: Column not found: 1054" when using a custom primary key in CakePHP 2.x - cakephp

I'm trying to build a drop-down list in CakePHP 2.x with the following code:
Controller
$Propertytype=$this->Propertytype->find("list",array("fields" => array("Propertytype.propertytype_id,Propertytype.propertytype_name,Propertytype.propertytype_id"),"order" => array("Propertytype.propertytype_id" => "desc"),"conditions" => array("Propertytype.propertytype_status" => "0")));
$this->set("propertytype",$Propertytype);
View
<?php echo $this->Form->input("propertytype",array("class"=>"form-control","data-style"=>"btn-white",
"data-live-search"=>"true","label"=>false,"data-size"=>"5","required"=>"required","options"=>$propertytype));
?>
I am not using Propertytype.id as primary key. I renamed it to Propertytype.Propertytype_id. But when I run the query, it's asking for Propertytype.id.
Database Error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Propertytype.id' in 'field list'
How can I change it to Propertytype.property_id as option value?

You have to define $primaryKey in class Propertytype:
class Propertytype extends AppModel
{
public $primaryKey = 'property_id';
}
You also have to write your query using the right syntax:
$Propertytype=$this->Propertytype->find("list",array(
"fields" => array(
"Propertytype.propertytype_id",
"Propertytype.propertytype_name"
),
"order" => array("Propertytype.propertytype_id" => "desc"),
"conditions" => array("Propertytype.propertytype_status" => "0")
));
You forgot the quotes.

Related

How to fix Grid->addQuickSearch() + Field_Callback error?

It seems that Grid->addQuickSearch() method does not work will Field_Callback.
I have the following model:
class Country extends \AppAtk4\MyModel {
public $title_field = 'calc_title';
public function init() {
parent::init();
$this->addField('iso_code', ['type' => 'string', 'required' => true]); // ISO 3166-1 alpha-2
$this->addField('name', ['type' => 'string', 'required' => true]);
$this->addExpression('calc_title', ['CONCAT([iso_code], \' - \', [name])', 'type' => 'string', 'read_only' => true, 'ui' => ['visible' => false]]);
}
}
And Grid with search input inicialized by this code:
$crud->setModel($model);
// add quick search
$searchFields = [];
foreach ($model->elements as $name => $element) {
if (!$element instanceof \atk4\data\Field) {
continue;
}
$searchFields[] = $name;
}
$crud->addQuickSearch($searchFields);
$crud->quickSearch->owner->add(new \atk4\ui\FormField\Input(['inputType' => 'Hidden', 'short_name' => 'crud_model', 'content' => get_class($model)]));
Then when I open the Grid, write some search text and press Search, the following Exception is fired:
atk4\dsql\Exception: DSQL got Exception when executing this query
Exception Parameters
error: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_sql' in 'where clause'"
query: "select count(*) from `fromatk4_country` where (`id` like '%s%' or `created_at` like '%s%' or `notes` like '%s%' or `iso_code` like '%s%' or `name` like '%s%' or (CONCAT(`iso_code`, ' - ', `name`)) like '%s%' or `field_sql` like '%s%')"
It seems there is a wrong column name in the SQL query (field_sql). This problem came up one I upgraded to the atk4/data 1.3.5 from some version from last year.
Is this a bug or should/can I inicialize the search fields differently?
I also opened a issue in the project repo: https://github.com/atk4/data/issues/329
My guess is that this extra field is added by something. Perhaps you're using "$grid->addColumn". In the past this used to add a new decorator for existing fields, now it would add a non-existant field.
It does not seem as your code adds it, so perhaps there is something else. Try commenting things out and using foreach without Grid/CRUD to see if that field is still there.

Yii Relational Query with 'through'

Good evening,
In this page (http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-through) it's described how to get all comments for all users of a particular group using 'through':
class Group extends CActiveRecord
{
...
public function relations()
{
return array(
'roles'=>array(self::HAS_MANY,'Role','group_id'),
'users'=>array(
self::HAS_MANY,'User',array('user_id'=>'id'),'through'=>'roles'
),
'comments'=>array(
self::HAS_MANY,'Comment',array('id'=>'user_id'),'through'=>'users'
),
);
}
}
How can I do exactly the opposite? That is, get the group of the user who made a particular comment (Comment Model basically).
So far, I'm not even able to reach 'role' table:
'user' => array(self::BELONGS_TO, 'User', 'user_id'),
'roles'=>array(self::HAS_MANY, 'Role', array('id'=>'user_id'), 'through' => 'user') // shouldn't it join User.id to Role.user_id ?
It's raising the following error: 'Column not found: 1054 Unknown column 'user.user_id' in 'where clause'. And it seems related to the first line, not the second...
Any ideas?
Sincerely,
Apidcloud
As you want to get the group of the user who made a particular comment. You have to add these relation in the comment model.
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(
'user' => array(self::BELONGS_TO, 'User', 'user_id'),
'roles'=>array(
self::HAS_ONE,'Role',array('id'=>'user_id'),'through'=>'user'
),
'group'=>array(
self::BELONGS_TO,'Group','group_id','through'=>'roles'
)
);
}
And view file you can get group name like this.
<?php echo CHtml::encode($data->group->name); ?>
Hope this will help you.

How to set up GoogleCharts with cakePHP?

I'm trying to display data in cakePHP with a Google Chart.
I downloaded the GoogleCharts plugin on https://github.com/scottharwell/GoogleCharts and put it in my App/Plugin directory. I load all plugins in my application's bootstrap file with
CakePlugin::loadAll();
In my Controller, I put
App::uses('GoogleCharts', 'GoogleCharts.Lib');
and
public $helpers = array('GoogleCharts.GoogleCharts');
, so cakePHP is able to detect I will work with this plugin. Of course, I created the GoogleChartHelper.php in App/View/Helper.
Before working with my data, what I want is just to display an example of chart to see if it is working. Which is not! I copied the example of the above-provided link (on github.com), so here is my Controller class:
<?php
App::uses ( 'AppController', 'Controller');
App::uses ('GoogleCharts', 'GoogleCharts.Lib');
class StatisticsController extends AppController{
public $helpers = array('GoogleCharts.GoogleCharts');
public $components = array (
'Paginator',
'Session'
);
public function index(){
//Setup data for chart
$chart = new GoogleCharts();
$chart->type("LineChart");
//Options array holds all options for Chart API
$chart->options(array('title' => "Recent Scores"));
$chart->columns(array(
//Each column key should correspond to a field in your data array
'event_date' => array(
//Tells the chart what type of data this is
'type' => 'string',
//The chart label for this column
'label' => 'Date'
),
'score' => array(
'type' => 'number',
'label' => 'Score',
//Optional NumberFormat pattern
'format' => '#,###'
)
));
//You can also manually add rows:
$chart->addRow(array('event_date' => '1/1/2012', 'score' => 55));
//Set the chart for your view
$this->set(compact('chart'));
}
}
In my View, I put the code
<div id="chart_div"><?php $this->GoogleChart->createJsChart($chart);?></div>
(without "s" to "GoogleChart" (not like on the download page, where is it written "GoogleCharts"), which took me 3 hours to notice)
My charts should be displayed on the page, but I got the following error:
Warning (512): Method GoogleChartHelper::createJsChart does not exist
[CORE\Cake\View\Helper.php, line 192]
(and if I put the "s" in the View, my page displays like without any error but without any chart...)
Am I missing something?
N.B. : I didn't copy the first method given on the github page, because with it a new worst error appears:
Error: Call to a member function find() on null
That method is:
//Get data from model
//Get the last 10 rounds for score graph
$rounds = $this->Round->find(
'all',
array(
'conditions' => array(
'Round.user_id' => $this->Auth->user('id')
),
'order' => array('Round.event_date' => 'ASC'),
'limit' => 10,
'fields' => array(
'Round.score',
'Round.event_date'
)
)
);
Please help me, I just want to display some random data in a chart and it should not be complicated (but with cakePHP, everything seems complex)...
The problem is that one step was missing:
you have to write
<?php echo $this->fetch('script'); ?>
in View/Layouts/bootstrap.ctp and if you followed all other steps, it should work!

CakeDC Ratings stars do now appear and data is not saved

I am trying to add CakeDC ratings to my CakePHP website. I have followed the instructions in readme provided with the plugin, but the rating stars do not appear. Also the ratings are not saved when I press 'Rate'. Here is the code from the view file:
<h3><?php echo ($post['Post']['title']); ?></h3>
<?php echo $this->Rating->display(array(
'item' => $post['Post']['id'],
'type' => 'radio',
'stars' => 5,
'value' => $post['Post']['rating'],
'createForm' => array('url' => array_merge($this -> passedArgs, array('rate' => $post['Post']['id'], 'redirect' => true)))));?></h3>
After pressing "Rate", the url changes to '.../rate:2/redirect:1' , but the data does not appear in the database. Am I missing something?
i also encountered this problem, but what i did was, i added this
public $components = array('Ratings.Ratings');
public $actsAs = array('Ratings.Ratable');
and after that, it managed to save the data

Creating multiple fixtures in cakePhp

I've been trying, but in vain, to create multiple fixtures in cakePhP. Currently, I need to test a function that requires two different fixture database tables. If possible, could someone please post some simple snippet and show me create multiple fixtures.
Furnace,
have you taken a look at cake's bake utility? You can bake fixtures with it.
cake bake fixture all
bakes all fixtures at once in your app. Use with care in order not to overwrite existing code.
Edit0:
Use
cake bake fixture help
if you have further questions.
Here's a simple fixture: app/tests/fixtures/entity_fixtures.php
In your case you will create two of these files, one per model and with different names.
<?php
class EntityFixture extends CakeTestFixture {
var $name = 'Entity';
var $table = 'entities';
// Define the fields
var $fields = array(
'entity_id' => array('type' => 'integer', 'key' => 'primary'),
'type' => array('type' => 'string' , 'length' => 255),
'created' => 'datetime',
'modified' => 'datetime'
);
var $records = array(
array('entity_id' => 1, 'type' => 'entity', 'created'=>'2010-01-01', 'modified' => '2010-01-01')
);
}
?>
When in your test case include your fixtures at the top of your test case
class EntityTestCase extends CakeTestCase {
var $fixtures = array(
'plugin.myplugin.entity', // Including a sample plugin fixture
'entity', // The fixture above shown in code above
'blogs' // Including a third fixture (should be in app/tests/fixtures/blog_fixture.php)
);
}

Resources