How to access data from a query to a CGridView - arrays

I'm trying to use on my view a search made by CreateCommand to fill my CGridView, but I still need to pass as a dataProvider a CActiveDataProvider object.
Is there any way to transform my CreateCommand object into CActiveDataProvider or to do the same query directly as a CActiveDataProvider?
This is the view
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'credenciado-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'afterAjaxUpdate' => "loadAfterAjax",
'rowHtmlOptionsExpression' => 'array("style"=>"cursor: pointer","data-row-id" => $data->cre_id, "class" => "row_grid")',
'columns' => array(
'cre_razao_social',
array(
'header'=>'Status',
'name'=>'cre_ativo',
'value'=>'Status::getStatus($data->cre_ativo)',
'filter'=>array(true => 'ATIVO',false => 'INATIVO'),
'filterHtmlOptions'=>array('class'=>'col-sm-2'),
),
),
)); ?>
This is the controller
$model = new Credenciado('getValoresCredenciadosByConvenioRank');
$model = new CArrayDataProvider($model, array());
// pe($model);
$modelEst = new Estabelecimento('search_adm');
// pe($model);
$modelEst->unsetAttributes();
if (isset($_GET['Estabelecimento']))
$modelEst->setAttributes($_GET['Estabelecimento']);
// $model->unsetAttributes();
// if (isset($_GET['Credenciado']))
// $model->setAttributes($_GET['Credenciado']);
$this->render('listar',array(
'model' => $model,
'modelEst' => $modelEst,
'mes1' => $mes1,
'mes2' => $mes2,
'meses' => $meses,
'produto' => $produto,
'data' => $format,
'datas' => $date_unique,
'series' => $series,
'ano1' => $ano1,
'ano2' => $ano2
));
}
This is the Model
$q = Yii::app()->db->createCommand()
->select("
cre.cre_razao_social,
count(op.ope_id) as linhas,
par.par_data_vencimento,
pro.pro_codigo,
SUM(
CASE
WHEN date_trunc('month',par_data_vencimento) < date_trunc('month',now()) AND pro_codigo != 2 THEN
par.par_valor
WHEN pro_codigo = 2 THEN
op.ope_valor_parcela
ELSE
op.ope_valor_parcela
END
) as total_carteira")
->from("operacao op")
->join('parcela par', 'par.par_operacao_ope_id = op.ope_id')
->join('pos po', 'po.pos_id = op.ope_pos_pos_id')
->join('rubrica_credenciado rub', 'rub.rub_id = po.pos_rubrica_credenciado_rub_id')
->join('credenciado cre','rub.rub_credenciado_cre_id = cre_id')
->join('produto pro', 'pro.pro_id = rub.rub_produto_pro_id')
->join('matricula ma', 'ma.mat_matricula = op.ope_matricula AND ma.mat_convenio_con_id = '.Yii::app()->user->convenioid.' ')
->where('op.ope_con_id = :con_id', array(':con_id' => $con_id));
$q->andWhere(
"(par.par_data_vencimento between :datamin and :datamax and ope_status in('E','S'))
OR
(par.par_data_vencimento between :datamin and :datamax AND par.par_num_parcela = op.ope_qtde_parcelas AND op.ope_status = 'Q')
",
array(':datamin'=>$datamin, ':datamax'=>$datamax));
if(Yii::app()->user->sistema != 1) {
$q->andWhere('rub_consignavel = true');
}
$q->order('par.par_data_vencimento', 'ASC');
//$q->andWhere(array('in', 'ope_status', array('E','S')));
$q->group('cre.cre_razao_social, pro.pro_codigo, par.par_data_vencimento');
$q->queryAll();
This is the error
exception 'CException' with message 'CArrayDataProvider and its behaviors
do not have a method or closure named "search".' in
/var/www/html/yii/framework/base/CComponent.php:266
Stack trace:

you are making a mistake in your view. In your controller you are already passing object of CArrayDataProvider (i.e $model) to your view, so you should not call search() function on $model variable. Instead you should create CArrayDataProvider object from CreateCommand in your model and pass the object of Credenciado as $model in your controller and call your query method in the view like $model-> getValoresCredenciadosByConvenioRank() to get the data provider. Then your view would look like this
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'credenciado-grid',
// call your query function to get data provider (this is the name of function that you have implemented in your model)
'dataProvider' => $model->getValoresCredenciadosByConvenioRank(),
'filter' => $model,
'afterAjaxUpdate' => "loadAfterAjax",
'rowHtmlOptionsExpression' => 'array("style"=>"cursor: pointer","data-row-id" => $data->cre_id, "class" => "row_grid")',
'columns' => array(
'cre_razao_social',
array(
'header'=>'Status',
'name'=>'cre_ativo',
'value'=>'Status::getStatus($data["cre_ativo"])',
'filter'=>array(true => 'ATIVO',false => 'INATIVO'),
'filterHtmlOptions'=>array('class'=>'col-sm-2'),
),
),
));
?>
Your controller would become this
$model = new Credenciado('getValoresCredenciadosByConvenioRank');
$model->unsetAttributes();
if (isset($_GET['Credenciado']))
$model->setAttributes($_GET['Credenciado']);
// pe($model);
$modelEst = new Estabelecimento('search_adm');
// pe($model);
$modelEst->unsetAttributes();
if (isset($_GET['Estabelecimento']))
$modelEst->setAttributes($_GET['Estabelecimento']);
$this->render('listar',array(
'model' => $model,
'modelEst' => $modelEst,
'mes1' => $mes1,
'mes2' => $mes2,
'meses' => $meses,
'produto' => $produto,
'data' => $format,
'datas' => $date_unique,
'series' => $series,
'ano1' => $ano1,
'ano2' => $ano2
));
}
And your model would return CArrayDataProvider instead of query result like this,
$queryResult = $q->queryAll();
// return data provider for view instead of query result
return new CArrayDataProvider($queryResult, array());
Hopefully this solution will solve your problem. Let me know if it works or if the problem still persists.

Related

Array to DB::insert()->values(), which is in different order with the columns

Hi folks! I'm trying to transfer data as array from the controller to the model, and then paste the data into the query builder, but the data must be in the same order as specified in the columns.
What options do I have?
And do you think this is a bad practice?
Controller:
$responseNotes = Model::factory('Notes')-> createTicket([
'description' => htmlspecialchars($_POST['description']),
'contact_id' => $_POST['contact_id'],
'pref_contact' => $_POST['pref_contact'],
'dog_id' => $_POST['document_id'],
'type' => $_POST['type'],
'owner_id' => Auth::instance()->get_user()->id,
'cc' => $_POST['cc-emails'],
'title' => $_POST['title']
]);
Model:
public function createNote(array $data)
{
$columns = [
'type',
'owner_id',
'cc',
'title',
'description',
'contact_id',
'pref_contact',
'dog_id'
];
if (!array_diff($columns, array_keys($data))) {
// All needed values exists
$result = DB::insert($this->NOTES, $columns)-> values($data)-> execute($this->SCHEMA);
}
return ($result) ? $result : false ;
}
Thanks to this answer. Solved this by:
// Order $data array according to $column.values
$orderedData = [];
foreach ($columns as $key) {
$orderedData[$key] = $data[$key];
}
$result = DB::insert($this->TICKETS, $columns)
-> values($orderedData)
-> execute($this->SCHEMA);
Why you don't use ORM Model?
in controller:
$responseNotes = ORM::factory('Notes')-> values([
'description' => htmlspecialchars($_POST['description']),
'contact_id' => $_POST['contact_id'],
'pref_contact' => $_POST['pref_contact'],
'dog_id' => $_POST['document_id'],
'type' => $_POST['type'],
'owner_id' => Auth::instance()->get_user()->id,
'cc' => $_POST['cc-emails'],
'title' => $_POST['title']
])
try{
$responseNotes->save();
} catch (ORM_Validation_Exception $ex) {
print_r($ex->errors('models'));
}
And don't use htmlspecialchars($_POST['description'])
In model class modify function (doc):
public function filters()
{
return array(
'description' => array( array('htmlspecialchars') ),
);
}
It looks like You have associative array with structure db_column=>value right? Than You can simply insert like this:
DB::Insert('table_name',array_keys($data))->values(array_values($data))->execute();

CakePHP: Keep the same checkboxes checked after submit

How can I keep the same checkboxes checked after submit? All the other input fields on the form automatically keeps the values. I thought this would also go for checkboxes, but nope.
echo $this->Form->input('type_id', array(
'multiple' => 'checkbox',
'options' => array(
'1' => 'Til salgs',
'2' => 'Ønskes kjøpt',
'3' => 'Gis bort'
),
'div' => false,
'label' => false
));
I believe this can be done in the controller, but how?
Edit:
Since I posted this question I've changed to CakeDcs Search plugin, because I've gotten this to work with that before. Still... I can't get it to work this time.
Adding model and controller code:
AppController
public $components = array('DebugKit.Toolbar',
'Session',
'Auth' => array(
'loginAction' => '/',
'loginRedirect' => '/login',
'logoutRedirect' => '/',
'authError' => 'Du må logge inn for å vise denne siden.',
'authorize' => array('Controller'),
),
'Search.Prg'
);
public $presetVars = true; //Same as in model filterArgs(). For Search-plugin.
AdsController
public function view() {
$this->set('title_for_layout', 'Localtrade Norway');
$this->set('show_searchbar', true); //Shows searchbar div in view
$this->log($this->request->data, 'debug');
//Setting users home commune as default filter when the form is not submitted.
$default_filter = array(
'Ad.commune_id' => $this->Auth->user('User.commune_id')
);
$this->Prg->commonProcess(); //Search-plugin
$this->paginate = array(
'conditions' => array_merge($default_filter, $this->Ad->parseCriteria($this->passedArgs)), //If Ad.commune_id is empty in second array, then the first will be used.
'fields' => $this->Ad->setFields(),
'limit' => 3
);
$this->set('res', $this->paginate());
}
Model
public $actsAs = array('Search.Searchable');
public $filterArgs = array(
'search_field' => array('type' => 'query', 'method' => 'filterSearchField'),
'commune_id' => array('type' => 'value'),
'type_id' => array('type' => 'int')
);
public function filterSearchField($data) {
if (empty($data['search_field'])) {
return array();
}
$str_filter = '%' . $data['search_field'] . '%';
return array(
'OR' => array(
$this->alias . '.title LIKE' => $str_filter,
$this->alias . '.description LIKE' => $str_filter,
)
);
}
/**
* Sets the fields which will be returned by the search.
*
* #access public
* #return array Database table fields
* #author Morten Flydahl
*
*/
public function setFields() {
return array(
'Ad.id',
'Ad.title',
'Ad.description',
'Ad.price',
'Ad.modified',
'User.id',
'User.first_name',
'User.middle_name',
'User.last_name',
'User.link',
'User.picture_url',
'Commune.name',
'Type.id',
'Type.name'
);
}
You have to set manually the selected option of the input, as an array with "keys = values = intval(checkbox id)"
I cannot explain why this format, but this is the only way I get it to work.
Here is my code:
echo $this->Form->create('User');
// Read the submitted value
$selected = $this->Form->value('User.Albums');
// Formats the value
if (empty($selected)) {
$selected = array(); // avoid mess
} else {
$selected = array_map('intval', $selected);
$selected = array_combine ($selected, $selected);
}
// Renders the checkboxes
echo $this->Form->input('Albums',array(
'type' => 'select',
'multiple' => 'checkbox',
'options' => $albums, // array ( (int)id => string(label), ... )
'selected' => $selected, // array ( (int)id => (int)id, ... )
));
Hope this helps.
++

Populating #options, #header for tableselect in ajax callback function

What I am trying to do is display a table with checkboxes on the press of a button by ajax. The table should be initially hidden and get populated on the fly by a function call.
If initially I load $options1 with some dummy values , then after ajax call it throws in an error saying-
Notice: Undefined index: red in theme_tableselect() (line 3285 of
D:\wamp\www\drupal7\includes\form.inc).
where 'red' is the index of a dummy row value and #options don't get populated with the new values. What is the way to get this working ?
Here is the code for the form-
$form['mltag_new']['tag'] = array(
'#type' => 'button',
'#value' => t("Suggest Tags"),
'#ajax' => array(
'callback' => 'mltag_suggest_tags_ajax',
'wrapper' => 'mltag_suggest_tags_table_div',
'effect' => 'slide',
),
);
$options1 = array(); //initial dummy values
$options1['red']['tag'] = "A red row";
$options1['red']['chi'] = "A red row";
$form['mltag_new']['myselector'] = array (
'#type' => 'tableselect',
'#title' => 'My Selector',
'#header' => $header,
'#options' => $options1,
'#prefix' => '<div id="mltag_suggest_tags_table_div">',
'#suffix' => '</div>',
);
return $form;
and the Ajax callback looks something like this-
function mltag_suggest_tags_ajax($form, $form_state) {
//$content has some content
//pass the content to a function
include_once 'includes/content_tag.inc';
$tags = mltag_content_tag($content, variable_get('algo_type'), 20);
if (empty($tags)) {
$output .= t('Content is insufficient to generate Tags using this algorithm. <br>Please choose other algorithm from Settings Page.');
$form['mltag_new']['sample_text']['#markup'] = $output;
return $form['mltag_new']['sample_text'];
}
else {
$algo = variable_get('algo_type');
if ($algo == 1) {
$header = array(
'tag' => t('Tag'),
'frequency' => t('Frequency'),
);
$options = array();
foreach ($tags as $key => $value) {
$options[$key] = array(
'tag' => $key,
'frequency' => $value,
);
}
}
elseif ($algo == 2) {
$header = array(
'tag' => t('Tag'),
'chi' => t('Chi Square Value'),
);
$options = array();
foreach ($tags as $key => $value) {
$options[$key] = array(
'tag' => $key,
'chi' => $value,
);
}
}
$form['mltag_new']['myselector']['#header'] = $header;
$form['mltag_new']['myselector']['#options'] = $options;
return $form['mltag_new']['myselector'];
}
}
I replied to your post on Drupal.org about how I'm working on a somewhat similar problem. Try adding
$form['mltag_new']['myselector'] =
form_process_tableselect($form['mltag_new']['myselector']);
just before your return. Hopefully that helps you more than it did me. Beware that the #options just get rendered when the block reloads from the ajax, but the original $form object doesn't seem to be aware.
I know that this is a few years later, but I found this while searching for my own solution:
The tableselect module creates checkboxes in the $ form that have to be removed. in the example above, they would be in $form['mltag_new']['myselector'] with keys equal to the original $option1 in your original code. If you unset those, then call
$form['mltag_new']['myselector'] = form_process_tableselect($form['mltag_new']['myselector']);
before your return, it will eliminate the dummy rows.

cakephp beforeSave callback in Behaviors don't save data correctly

Controller:
$data =
array(
'ContentI18n' =>
array(
0 =>
array(
'title' => 'first',
'author' => 'first',
'source' => 'sgfsdfrst',
'lang' => 'fa',
),
),
'Content' =>
array(
'publish' => 1,
'type' => 3,
'pages' => 8,
'volume' => 7,
'modified' => '2012-05-27 14:16:37',
'created' => '2012-05-27 14:16:37',
'lang' => 'fa',
),
);
$this->Content->create();
$this->Content->saveAll($data);
Model:
public $hasMany = array(
'ContentI18n' => array(
'className' => 'ContentI18n',
)
);
beforeSave function in behavior:
public function beforeSave(Model $model) {
// Define the new Translate model
App::uses($model->name . 'I18n', 'Model');
$varI18n = $model->name . 'I18n';
$modelI18n = new $varI18n;
foreach ($model->data[$model->name] as $key => $data) {
if (!in_array($key, $this->setting))
$modelData[$model->name][$key] = $data;
else
$modelData[$model->name . 'I18n'][0][$key] = $data;
}
$modelData[$model->name . 'I18n'][0]['lang'] = $model->locale;
$modelData[$model->name]['lang'] = $model->locale;
$model->data = $modelData;
//pr($model->data);
return TRUE;
}
every things seems be cause when is save it directly it's save with saveAll. but when i use same structure of data in behavior did not work without any error.
I found out that beforeSave callback will not trigger by saveAll. for executing some code before saveAll we must override saveAll function in our model.
public function saveAll($data, $options = array()) {
/*
your code you want execute before saving...
*/
parent::saveAll($data, $options);
}
for other saving methods such as saveMany,saveAssociated,... beforeSave trigger by them.

the rss helper doesnt generate the index.rss

i have an issue trying to generate rss. I followed all the steps of http://book.cakephp.org/1.3/en/view/1460/RSS, but when i try in the url my index.rss shows me only my index page not in xml format.
this is my index of post_Controller:
var $components = array('Session','RequestHandler');
var $helpers = array('Html','Form','Time','Text');
function index() {
if( $this->RequestHandler->isRss() ){
$posts = $this->Post->find('all', array('limit' => 20, 'order' => 'Post.created DESC'));
$this->set(compact('posts'));
}
$this->set('title_for_layout', 'mi blog');
$this->Post->recursive = 1;
$this->set('posts', $this->paginate());
}
this is my layout in app/views/layouts/rss/default.ctp:
echo $this->Rss->header();
if (!isset($documentData)) {
$documentData = array();
}
if (!isset($channelData)) {
$channelData = array();
}
if (!isset($channelData['title'])) {
$channelData['title'] = $title_for_layout;
}
$channel = $this->Rss->channel(array(), $channelData, $content_for_layout);
echo $this->Rss->document($documentData,$channel);
this the view in app/views/posts/rss/index.ctp
$this->set('documentData', array(
'xmlns:dc' => 'http://purl.org/dc/elements/1.1/'));
$this->set('channelData', array(
'title' => __("Articles", true),
'link' => $this->Html->url('/', true),
'description' => __("Articulos mas recientes.", true),
'language' => 'en-us'));
// content
foreach ($posts as $post) {
$postTime = strtotime($post['Post']['created']);
$postLink = array(
'controller' => 'posts',
'action' => 'view',
$post['Post']['id']);
// You should import Sanitize
App::import('Sanitize');
// This is the part where we clean the body text for output as the description
// of the rss item, this needs to have only text to make sure the feed validates
$bodyText = preg_replace('=\(.*?\)=is', '', $post['Post']['body']);
$bodyText = $this->Text->stripLinks($bodyText);
$bodyText = Sanitize::stripAll($bodyText);
$bodyText = $this->Text->truncate($bodyText, 400, array(
'ending' => '...',
'exact' => true,
'html' => true,
));
echo $this->Rss->item(array(), array(
'title' => $post['Post']['title'],
'link' => $postLink,
'guid' => array('url' => $postLink, 'isPermaLink' => 'true'),
'description' => $bodyText,
'pubDate' => $post['Post']['created']));
}
which could be the problem ... Also i have put the component in the app_controller.php
var $components = array ('Auth', 'Session', 'RequestHandler');
but nothing happens the index.rss is the Same of posts / index
It looks like you are not returning the RSS view in the index controller. Update the RSS section of the index function to return the rss view:
function index() {
if( $this->RequestHandler->isRss() ){
$posts = $this->Post->find('all', array('limit' => 20, 'order' => 'Post.created DESC'));
return $this->set(compact('posts'));
}
// ...snip...
}
UPDATE
It's how Chrome handles the layout. I know it is horrible. FireFox and IE handle RSS layout much better. But you can install the RSS Layout extension for Chrome and it will format it the same way.
https://chrome.google.com/extensions/detail/nlbjncdgjeocebhnmkbbbdekmmmcbfjd
In the action of the controller. You must add
$this->response->type("xml");
at the end.

Resources