How to put contrasting information into a CGridView column based on a condition? - yii

I'm looking into showing/hiding specific column data on a CGridView widget for the Wii Framework.
I have a CButtonColumn which contains 3 buttons. However, on certain conditions, I want to display something different for a particular row.
I have 3 different conditions which determin what gets displayed for particular row.
The following illustrates what I want to do:
| 1 | Title A | [hide][view][update] <-- if (condition == 'a')
| 2 | Title B | [hide][view][update] <-- if (condition == 'a')
| 3 | Title C | display text or link or button <-- if (condition == 'b')
| 4 | Title D | display alternative buttons <-- if (condition == 'c')
What is my best approach to take here?
I can't use 'visible'=> $model->processingStatus != "processed" on the column because this will remove the whole column. I need to target each row insatead.
Should I use the 'visible' parameter on each individual button? I have tried this using the commented out code below but it breaks the page.
FYI: I have successfully tried the 'visible' parameter on the CButtonColumn itself, but its not what I need. Plus not sure which row's status it is reading.
Or should I add a function to the controller? Have it do the if/else statements and return back what is to be displayed. How would this work?
Here is my code:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'my-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
array(
'name'=>'myid',
'header'=>'ID',
),
'Title',
array(
'class'=>'CButtonColumn',
'visible'=> $model->status != "done",
'template'=>'{hide}{view}{update}',
'buttons'=>array(
'hide'=>array(
'label'=>'Hide', //Text label of the button.
'imageUrl'=>Yii::app()->request->baseUrl . '/img/icons/bulb-off.png' //Image URL of the button.
//'click'=>'function(){alert("Toggle Hide!");}', //A JS function to be invoked when the button is clicked.
//'options'=>array(), //HTML options for the button tag.
//'url'=>'javascript:void(0)', //A PHP expression for generating the URL of the button.
//'visible'=> $model->status == "done", //A PHP expression for determining whether the button is visible.
),
'view'=>array(
//Text label of the button.
'label'=>'View',
//Image URL of the button.
'imageUrl'=>Yii::app()->request->baseUrl . '/img/icons/view-record.png'
),
'update'=>array(
'label'=>'Update/Edit',
'imageUrl'=>Yii::app()->request->baseUrl . '/img/icons/edit-pencil.png',
'url'=>'Yii::app()->createUrl("metadataandchapters/create?bookid=" . $data->bookid)',
)
)
)
)
)); ?>
Hope I am making good enough sense here!

You should use visible button option, but it should be a PHP expression string, e.g. :
'visible'=> '$data->status == "done"',
http://www.yiiframework.com/doc/api/1.1/CButtonColumn#buttons-detail

Extend CButtonColumn with your own class, then you should be able to change this function to whatever you need to render or hide buttons or do any changes you want.
/**
* Renders a link button.
* #param string $id the ID of the button
* #param array $button the button configuration which may contain 'label', 'url', 'data-icon', 'imageUrl' and 'options' elements.
* #param integer $row the row number (zero-based)
* #param mixed $data the data object associated with the row
*/
protected function renderButton($id, $button, $row, $data)
More details about the function http://www.yiiframework.com/doc/api/1.1/CButtonColumn#renderButton-detail

Related

Gravityforms - Add category mid-radio-button field

I am populating Gravityforms fields using the functions.php from my template and it works like a charm, but I have one field that is ... a challenge. I have been able to populate the choices from my database just fine, but with the functions.php I cannot control the content of the display area of the field so that I can, for example, add a title or header for each category. Is there a way to programattically adjust the display here's an example of what im hoping to accomplish
RadioButton Choice (Field ID 21)
Dark Colors (category title)
maroon (choice 1)
navy blue (choice 2)
black (Choice 3)
Standard Colors (Category Title)
Red (choice 4)
blue (choice 5)
gray (Choice 6)
Light Colors )Category Title)
pink (choice 7)
sky blue (choice 8)
white (Choice 9)
I am just looking for a way to add the category title between the choices. My DB Query has the categories as part of the response, but the only option I have to populate choices to to feed an array.
I have seen where I can add additional Gravityform fields and have them controlled by the same "single select" radio button option, but the categories involved change based on the DB query I call to dynamically populate the choices and could range from 1 category to 10, which will not have correlating fields in the form itself, as this is all under a single radio-button field.
Any thoughts would be appreciated.
I was able to use the link I posted in my comment to provide a solution. As part of my "choices"
here is the function for the Pre-Render to populate choices. In this case I am populating a radio-button field with product images instead of default radio buttons
add_filter('gform_pre_render_1', 'populate_choices');
function populate_choices($form) {
global $wpdb;
// Now to get a list of the products I want to include on this radio-button
$dataQ = "
SELECT category, product_id, product_name
FROM product_table
WHERE product_type = 'whatever I am looking for'
ORDER BY category, product_name ASC
";
$dataR = $wpdb->get_results($dataQ);
$dataList = array();
// get current protocol to use in Product Images
$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
// Rebuild URL for use with product image graphics
$productImageUrl = $protocol.$_SERVER['HTTP_HOST'].'/wp-content/product_images/';
// Generate list of choices for the radio-button, along with category headers
foreach ($form['fields'] as $field) {
if ($field->id == '32') { // 32 My specific radio-button field
$category = "";
foreach ($dataR as $data) {
if ($category != $data->category) {
// If I hit a new category, add the "header" item to the "choices" list with a unique search item to identify it, in this case "###"
$category = $data->category;
$dataList[] = array(
'text' => '#'.$category."#",
'value' => ''
);
}
$productImage = str_replace(" ","",strtolower($data->product_name)).".jpg";
$productID = $data->product_id;
$dataList[] = array(
'text' => $data->product_name,
'value' => $productID,
'isSelected' => false,
'price' => '0.00',
'imageChoices_image' => $productImagehUrl.$productImage
);
}
$field->choices = $dataList;
}
}
}
I then added a specific field modifier to update the "#category#" choice elements with html to make the category names show up.
// numbers after filter = "1" for form ID 1, "32" for field ID 32
add_filter('gform_field_choice_markup_pre_render_1_32', function( $choice_markup, $choice) {
if ( strpos( $choice['text'], '#' ) === 0 ) {
$categoryName = str_replace("#","",$choice['text']);
$choice_markup = '
<li style="width:100%;text-align:left;">
<span style="color:#000000;font-weight:bold;font-size:18px;">
<br>
'.$categoryName.'
</span>
</li>
';
}
return $choice_markup;
}, 10, 2);

Checkboxlist in YII AJAX filter deselecting items

I have an ajaxfilter on a YII listview. When I select an item in the checkboxlist everything works properly: ajax calls vacature/index and gives 'vacature' the right ID which I handle in my controller, so this works fine. (vacature/index?vacature=13)
Now when I uncheck the same item it does exactly the same call, so it passes the id of the changed item. I only need it to not pass the id of the de-selected item and the string to be empty.
Thanks in advance!
echo CHtml::beginForm(CHtml::normalizeUrl(array('vacature/index')), 'get', array('id'=>'filter-vacature'))
echo CHtml::checkBoxList('niveau', (isset($_GET['niveau'])) ? $_GET['niveau'] : '',
CHtml::listData(Lov::model()->findAllByAttributes(array('wat'=>'opleiding')), 'id', 'item'),
array('class'=>'niveau','template'=>'<span class="checkbox-columns">{input} {label}</span>', 'separator'=>''))
$('.niveau').change(function(){
niveau = $('.niveau').serialize();
$.fn.yiiListView.update(
'ajaxListView',
{data: niveau}
);
});
I added a comparison to check if the string is empty, and pass the working empty value:
$('.niveau').change(function(){
niveau = $('.niveau').serialize();
if(empty(niveau))
{
niveau = 'niveau%5B%5D=0';
}
$.fn.yiiListView.update(
'ajaxListView',
{data: niveau}
);
});

using listdata only and get from another model in Yii

can i just have listdata by itself? The list doesn't list anything, all I keep getting is "Array" as the return.
I have:
$awards= $model->findAll('uid='.$uid);
return CHtml::listData($awards, 'award_id', '$data->award->name');
try this code:
$awards= $model->findAll(array('condition'=>'uid ='.$uid)); // get records from table
return CHtml::listData($awards, 'award_id', 'award_name'); // third parameter should the array value. Most of the case we use to display in combo box option text.
If you are getting from another table, then declare a variable in your award model.
public $awrd_name;
Then you have to get records using relation in criteria.
Output will be :
array("1" => "award1", "2" => "award2", "3" => "award3");
refer this link : http://www.yiiframework.com/forum/index.php/topic/29837-show-two-table-fields-in-dropdownlist/

Cgridview selected row column value in Yii

Using below code im getting all "Name" Column values
$.fn.yiiGridView.getColumn("CGridViewUser",1).text();
if i want to get selected row "Name" column value (like shown in image), how to achevie this?
First add an ID to your GridView.
<?php
$this->widget('zii.widgets.grid.CGridView', array
(
'dataProvider'=>$dataProvider,
'htmlOptions'=>array('id'=>'MyID'), //MyID is an ID to grid wrapper
........
........
Now, jQuery
$("#MyID table tbody tr").click(function()
{
$this=$(this);
var firstColVal= $this.find('td:first-child').text();
var secondColVal= $this.find('td:nth-child(2)').text();
var lastColVal= $this.find('td:last-child').text();
alert(firstColVal);
});
It will work.

Yii Pagination Variables from DataProvider

I need certain pagination variables in my controller action.
such as:
1.Current Page Number
2.Current Page offset
3.total records displayed
i.e. 31 to 40 of 2005 records displayed
I tried the following:
$dataProvider = NodesTerms::getNodesDataFromTerms($nodeId) ;
$pagination = $dataProvider->getPagination();
var_dump($pagination->getPageCount());
//var_dump($pagination->currentPage);
I can get the Pagination Object, but zero (0) in $pagination->currentPage or $pagination->offset etc....
I need this information to dynamically generate meta page title and description on actions with page listings such as pagetitle: page 3 of 10 for American Recipes...
Appreciate any help with this.
Try setting the itemCount explicitly in your dataProvider:
'pagination'=>array(
'pageSize'=>10,
'itemCount'=>$count
)
Or use a new CPagination object:
$pagination = new CPagination($count);
$dataProvider = new CSqlDataProvider($sql, array(
// ... other config
'pagination' => $pagination
));
How this works:
The pagination's itemCount is set during creation of the data-provider and again in CSqlDataProvider's fetchData function:
$pagination->setItemCount($this->getTotalItemCount());
During creation of data-provider only the values passed to the pagination property are used, and if we don't pass itemCount value, then the default of 0 is used.
So if we want to access offset or pageCount or currentPage or itemCount before the call to fetchData we have to set the itemCount explicitly.
However if we want those values after the call to fetchData then the values are already correctly populated due to the call to setItemCount within fetchData.
An example for clarity (without passing itemCount during data-provider creation):
$dataProvider = NodesTerms::getNodesDataFromTerms($nodeId);
$pagination = $dataProvider->getPagination();
var_dump($pagination->getPageCount()); // this will be zero
$data=$dataProvider->getData(); // getData calls fetchData()
var_dump($pagination->getPageCount()); // now this will be correct value
getCurrentPage returns "the zero-based index of the current page"
http://www.yiiframework.com/doc/api/1.1/CPagination#getCurrentPage-detail
so if you're on the first page, it should be returning 0.
And as you know the page size and the total number of records that will be enough for you to generate your page title.