yii cgridview button label or title change - php

this is the code for a button, i want to change the label or in other words the title tag content.
'assignParent' => array(
'label' => 'Assign Parent',
'url' => '$data->parentId ? Yii::app()->controller->createUrl("updateParent", array("id" => $data->parentId)): Yii::app()->controller->createUrl("assignParent", array("imei" => $data->imei))',
'imageUrl' => Yii::app()->baseUrl . '/media/images/parent-btn.png',
'visible' => 'Yii::app()->user->checkAccess("oDeviceDeviceAssignParent") ? true : false',
'options' => array('style' => 'padding: 0px 3%'),
),
this is the view source code,
<td class="button-column"><i class="icon-eye-open"></i><i class="icon-pencil"></i><i class="icon-trash"></i><img alt="Assign Parent" src="/qelasysecurity_12/media/images/parent-btn.png"><img alt="Assign Student" src="/qelasysecurity_12/media/images/student-btn.png"></td>
this is how that exact part comes,
<a href="#" rel="tooltip" title="$data->parentId ? Assign Student : Update Student" style="padding: 0px 3%">
i want to make this kind of a logic to change the label name,
'options' => array('style' => 'padding: 0px 3%', 'title'=>'$data->parentId ? Assign Student : Update Student'),
$data->parentId ? Assign Student : Update Student'
any suggestion to accomplish this?

Here is the solution.
With help from http://www.yiiframework.com/wiki/714/yii-1-1-cgridview-use-special-variable-data-in-the-options-of-a-button-i-e-evaluate-options-attribute/
in /protected/components create a new extension "ButtonColumn.php"
<?php
/**
* ButtonColumn class file.
* Extends {#link CButtonColumn}
*/
class ButtonColumn extends CButtonColumn
{
/**
* Renders a link button.
* #param string $id the ID of the button
* #param array $button the button configuration which may contain 'label', 'url', 'imageUrl' and 'options' elements.
* See {#link buttons} for more details.
* #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)
{
if (isset($button['visible']) && !$this->evaluateExpression($button['visible'],array('row'=>$row,'data'=>$data)))
return;
$label=isset($button['label']) ? $button['label'] : $id;
$url=isset($button['url']) ? $this->evaluateExpression($button['url'],array('data'=>$data,'row'=>$row)) : '#';
$options=isset($button['options']) ? $button['options'] : array();
if(!isset($options['title']))
$options['title']=$label;
// Start of modification
if( isset ( $button['evaluateLabel'] ) )
{
$label = $this->evaluateExpression($label,array('data'=>$data,'row'=>$row));
$label = $button['evaluateLabel'][$label];
unset($options['evaluateLabel']);
}
// END of modifications
if(isset($button['imageUrl']) && is_string($button['imageUrl']))
echo CHtml::link(CHtml::image($button['imageUrl'],$label),$url,$options);
else
echo CHtml::link($label,$url,$options);
}
}
Note the modifications line. This checks for a new variable 'evaluateLabel'. If it exits it will parse the 'label' variable through the as an array key to find the desired new value.
My new CGridView code looks as follows
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'users-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'username',
'email',
...
array(
'class' => 'ButtonColumn',
'template' => '{update} {delete} {switch}',
'buttons'=>array (
'delete'=>array(
'label'=>'$data->custom_variable',
'imageUrl'=>false,
'options'=>array( 'class'=>'cbutton delete' ),
'evaluateLabel' => array(0=>"Suspend",1=>"Reactivate"),
),
So in my case '$data->custom_variable is a variable tied to the model that will always be 0 or 1. So the text loaded will be as paired in the evaluateLabel key.
Also note the class has changed from CButtonColumn to ButtonColumn

i think you cant do it directly but you can do it using property cssClassExpression
In it you can write a valid PHP expression that will be calculated. Make two css classes one with content "assign student" and other with "update Student". You can use it like,
1. Write a function in your model named checkStudent like
public function checkStudent()
{
if($this->id)
{
return "class name"
}
else
{
return "class name"}
}
2.Now you can use it like
"cssClassExpression"=>'$data->checkStudent()'
Now question arises that how can u right content using Css class. Here is good answer to that question.

You can use my code
'link'=>array(
'header'=>Yii::t('main', 'login'),
'type'=>'raw',
'value'=> 'CHtml::button($data->islogin==1?"可":"不可",array("onclick"=>"document.location.href=\'".Yii::app()->controller->createUrl("user/changelogin",array("id"=>$data->id))."\'", "class"=>"btn-link"))',
),

Related

Why does my custom code show warnings in the logs?

I have a site on Drupal 8.6 and Bootstrap 3.3.7
I created a custom module for the customer to accept the terms and conditions of the store when placing an order.
This displays a link to a checkbox before payment to display the terms and conditions in a modal window.
When I place an order here are the warnings in the logs (sorry my code is too long to be published here):
https://pastebin.com/1p5m1Ved
https://pastebin.com/XYbqDJje
https://pastebin.com/P93bStKh
Here is the file that created the problem :
<?php
namespace Drupal\commerce_marketplace_terms_and_conditions\Plugin\Commerce\CheckoutPane;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;
/**
* Provides the completion message pane.
*
* #CommerceCheckoutPane(
* id = "marketplace_terms_and_conditions",
* label = #Translation("Marketplace Terms and Conditions"),
* default_step = "review",
* )
*/
class MarketplaceTermsAndConditions extends CheckoutPaneBase implements CheckoutPaneInterface {
/**
* {#inheritdoc}
*/
public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
$store_name = $this->order->getStore()->getName();
$store_id = $this->order->getStoreId();
$pane_form['#attached']['library'][] = 'core/drupal.dialog.ajax';
$attributes = [
'attributes' => [
'class' => 'use-ajax',
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => auto
]),
],
];
$link = Link::fromTextAndUrl(
$this->t('terms and conditions of the store "#store_name"', ['#store_name' => $store_name]),
Url::fromUri("internal:/store/$store_id/cgv", $attributes)
)->toString();
$pane_form['marketplace_terms_and_conditions'] = [
'#type' => 'checkbox',
'#default_value' => FALSE,
'#title' => $this->t('I have read and accept #terms.', ['#terms' => $link]),
'#required' => TRUE,
'#weight' => $this->getWeight(),
];
return $pane_form;
}
}
What's wrong with my custom module and how to fix the problem ? Thank you
Change this to
'width' => auto
this
'width' => 'auto'
It is assuming it to be a constant, as you can see from the errors, it has to be either a variable or a string.

Why are characters inserted in my PHP link?

I created a module, but the link is not correct.
My site now shows :
/store/2?0=/cgv
The correct link should be :
/store/2/cgv
Why doesn't it work ? where is the error ?
What should I change in the code below, to get the link ?
<?php
namespace Drupal\commerce_agree_cgv\Plugin\Commerce\CheckoutPane;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;
/**
* Provides the completion message pane.
*
* #CommerceCheckoutPane(
* id = "agree_cgv",
* label = #Translation("Agree CGV"),
* default_step = "review",
* )
*/
class AgreeCGV extends CheckoutPaneBase implements CheckoutPaneInterface {
/**
* {#inheritdoc}
*/
public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
$store_id = $this->order->getStoreId();
$pane_form['#attached']['library'][] = 'core/drupal.dialog.ajax';
$attributes = [
'attributes' => [
'class' => 'use-ajax',
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 800,
]),
],
];
$link = Link::createFromRoute(
$this->t('the general terms and conditions of business'),
'entity.commerce_store.canonical',
['commerce_store' => $store_id, '/cgv'],
$attributes
)->toString();
$pane_form['cgv'] = [
'#type' => 'checkbox',
'#default_value' => FALSE,
'#title' => $this->t('I have read and accept #cgv.', ['#cgv' => $link]),
'#required' => TRUE,
'#weight' => $this->getWeight(),
];
return $pane_form;
}
}
Because $link is not built correctly :
$link = Link::createFromRoute(
$this->t('the general terms and conditions of business'),
'entity.commerce_store.canonical',
['commerce_store' => $store_id, '/cgv'], # -> this is wrong
$attributes
)->toString();
$route_parameters: (optional) An associative array of parameter names
and values.
You did not specify any name for the 2nd route parameters, so the corresponding array key fallback to the first available numeric indice, that is 0, meaning [ '/cgv' ] becomes [ 0 => '/cgv' ] and you don't get the link you expected.
I think (if I understood your issue correctly) what you need is to define in the first place that specific route handling cgv's for a given commerce_store, that is with the /cgv appended :
$route_collection = new RouteCollection();
$route = (new Route('/commerce_store/{commerce_store}/cgv'))
->addDefaults([
'_controller' => $_controller,
'_title_callback' => $_title_callback,
])
->setRequirement('commerce_store', '\d+')
->setRequirement('_entity_access', 'commerce_store.view');
$route_collection->add('entity.commerce_store.canonical.cgv', $route);
... so that you can build links based on that specific route :
$link = Link::createFromRoute(
$this->t('the general terms and conditions of business'),
'entity.commerce_store.canonical.cgv',
['commerce_store' => $store_id],
$attributes
)->toString();

Yii - Pass model ID into a view from CButtonColumn image

Alright, still new to Yii I am attempting to create a button in a column of CGridView. This button, when clicked, will take the user to the "view.php" page and display the information of the node they clicked on by passing in its ID.
I am frustrated that I cannot figure out how to simply add a link to the image that will direct my users. Here are some snippets of the code I have been working on for the past couple of days.
index.php
<?php echo CHtml::beginForm(); ?>
<?php
$pageSize = Yii::app()->user->getState('pageSize', Yii::app()->params['defaultPageSize']);
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'nodes-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
array(
'class' => 'CButtonColumn',
'template' => '{restart}',
'buttons' => array
(
'restart' => array
(
'label'=>'Restart this node',
'imageUrl'=>Yii::app()->baseUrl.'/images/refresh.png',
'options'=>array('id'=>'NB_bounce_Button'),
'url'=>array('view', 'id'=>$model->id),
)
),
),
/* 'id', */
'name',
'url',
'description',
'node_type',
'last_bounced',
//..
NodeBouncerController.php (View action)
/**
* Displays a particular model.
* #param integer $id the ID of the model to be displayed
*/
public function actionView($id) {
$this->render('view', array(
'model' => $this->loadModel($id),
));
}
The button is on the left. (Refresh green arrow)
What am I doing wrong? More specifically, am I using the buttons of CButtonColumn incorrectly? If so, how may I fix this?
My company uses: Yii v1.1.8.r3324
EDIT: [8/10/15]
It seems I may have been overcomplicating it. What I needed was to simply have an image-link that when clicked went to the view for that particular node that was clicked. Well, Gii auto-generates the particular view I needed and the code associated with it (as seen above).
My fix was to do away with the over complicated mess that I had and keep it simple. Use the template already provided for "view" and just alter it to my needs.
Like so:
/* 'id', */
array(
'class'=>'CButtonColumn',
'template'=>'{view}',
'buttons' => array
(
'view' => array
(
'label'=>'Restart this node',
'imageUrl'=>Yii::app()->baseUrl.'/images/refresh.png',
'options'=>array
(
'id'=>'NB_bounce_Button'
)
)
),
),
'name',
'url',
'description',
'node_type',
'last_bounced',
//....
It would be nice to know how to do this manually but I needed something to simply work for now and expand on it later for work.
I think the problem is url of the button. Because you did not include controllerID in the url. You should use this:
'url' => 'Yii::app()->createUrl("nodeBouncer/view", "id"=>$model->id)';
For creating url in yii, usually you should follow this pattern:
contollerID/actionID

Changing display logic for a field in sugarcrm

I have the following situation: Contacts without a first or last name, in fact, they only have a email address.
I can work with these contacts fine, but when I use the listview anywhere (for instance to show all contacts from a company) there now is no way to click through to the contact (normally you would click on the name).
I'm looking for a way to solve this, for instance by showing a clickable text like 'name not known', but can't figure out how to do this. I've been looking at the manual and in the files in the modules directory and the sugarfields dir, but can't quite figure it out.
The closest I got was in /sugarcrm/modules/Contacts/metadata/listviewdefs.php
where this piece of code resides:
$listViewDefs['Contacts'] = array(
'NAME' => array(
'width' => '20%',
'label' => 'LBL_LIST_NAME',
'link' => true,
'contextMenu' => array('objectType' => 'sugarPerson',
'metaData' => array('contact_id' => '{$ID}',
'module' => 'Contacts',
'return_action' => 'ListView',
'contact_name' => '{$FULL_NAME}',
'parent_id' => '{$ACCOUNT_ID}',
'parent_name' => '{$ACCOUNT_NAME}',
'return_module' => 'Contacts',
'return_action' => 'ListView',
'parent_type' => 'Account',
'notes_parent_type' => 'Account')
),
'orderBy' => 'name',
'default' => true,
'related_fields' => array('first_name', 'last_name', 'salutation', 'account_name', 'account_id'),
),
Somewhere there has to be a function that joins the first and lastname together...
Edit: I found a solution:
The actual concatenation function is in /sugarcrm/include/SugarObjects/templates/person/person.php and is called _create_proper_name_field()
I can modify the output for my specific case by adding something like this to the end of the function:
if (empty(trim($full_name))){
$full_name = 'Name unknown';
}
However, I would rather have a upgrade safe solution, so that will be the next challenge.
Don't edit the core because the next upgrade will break your SugarCRM instance. Use logic hooks to be upgrade safe:
create a file 'logic_hooks.php' in /custom/modules/Contacts/
In that file, add the followin code:
<?php
$hook_array['before_save'][] = Array(1,'logic_fill_name','custom/modules/Contacts/logic_hooks/logics.php','ContactLogics','logic_fill_name');
After you have done this. create the file 'logics.php' in /custom/modules/Contacts/logic_hooks.
In the logics.php file, add something like:
<?php
require_once 'include/SugarQuery/SugarQuery.php';
/**
* Class ContactLogics
*/
class ContactLogics {
/**
* #param $bean
* #param $event
* #param $arguments
*/
public function logic_fill_name($bean, $event, $arguments) {
if (empty(trim($bean->first_name)) && empty(trim($bean->last_name))){
$bean->last_name = 'Name unknown';
}
}
}
Now some explanation. When you edited a recordview and pressed the save button, the logic hook 'before_save' will be triggered. This code will change the full name to 'Name unknown' when the full name is empty. When the 'before_save' is executed, the actual save will take place.

Yii - CGridView - add own attribute

$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>array(
'title', // display the 'title' attribute
'category.name', // display the 'name' attribute of the 'category' relation
'content:html', // display the 'content' attribute as purified HTML
array( // display 'create_time' using an expression
'name'=>'create_time',
'value'=>'date("M j, Y", $data->create_time)',
),
array( // display 'author.username' using an expression
'name'=>'authorName',
'value'=>'$data->author->username',
//HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
'htmlOptions'=>array('class'=>'$data->author->username', 'secondAttribute' => $data->author->id),
//HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
),
array( // display a column with "view", "update" and "delete" buttons
'class'=>'CButtonColumn',
),
),
));
In option value i can add variable from PHP, but for option htmlOptions this is not possible. Why?How can i make attribute with PHP variable?
When you add arrays in the columns collection without specifying a class property, the type of column being created is CDataColumn. The property CDataColumn::value is explicitly documented to be
a PHP expression that will be evaluated for every data cell and whose
result will be rendered as the content of the data cells.
Therefore, value has the special property that it gets eval'ed for each row and that's why you can set it "dynamically". This is an exception however, and almost nothing else supports the same functionality.
However, you are in luck because the property cssClassExpression is another special exception that covers exactly this usage case. So you can do it like this:
array(
'name'=>'authorName',
'value'=>'$data->author->username',
'cssClassExpression' => '$data->author->username',
),
Edit: I made a mistake while copy/pasting from your example and did not notice that you were trying to do the same thing for additional attributes inside htmlOptions (I have now deleted the relevant part of the code).
If you need to add more options for dynamic values you have no choice but to subclass CDataColumn and override the renderDataCell method (stock implementation is here).
Don't know if this still applies or not (given that there is an accepted answer), but there is a slightly better solution in the form of "rowHtmlOptionsExpression". This specifies an expression that will be evaluated for every row. If the result of the eval() call is an array, it will be used as the htmlOptions for the <tr> tag. So you can basically now use something like this:
$this->widget('zii.widgets.grid.CGridView', array
(
...
'rowHtmlOptionsExpression' => 'array("id" => $data->id)',
...
All your tags will have an id attribute with the records' PK.
Just modify the jQuery slightly to obtain the id from that tag instead of an extra column and you should be set.
Extend the class CDataColumn
Under protected/components/ create the file DataColumn.php with the following content:
/**
* DataColumn class file.
* Extends {#link CDataColumn}
*/
class DataColumn extends CDataColumn
{
/**
* #var boolean whether the htmlOptions values should be evaluated.
*/
public $evaluateHtmlOptions = false;
/**
* Renders a data cell.
* #param integer $row the row number (zero-based)
* Overrides the method 'renderDataCell()' of the abstract class CGridColumn
*/
public function renderDataCell($row)
{
$data=$this->grid->dataProvider->data[$row];
if($this->evaluateHtmlOptions) {
foreach($this->htmlOptions as $key=>$value) {
$options[$key] = $this->evaluateExpression($value,array('row'=>$row,'data'=>$data));
}
}
else $options=$this->htmlOptions;
if($this->cssClassExpression!==null)
{
$class=$this->evaluateExpression($this->cssClassExpression,array('row'=>$row,'data'=>$data));
if(isset($options['class']))
$options['class'].=' '.$class;
else
$options['class']=$class;
}
echo CHtml::openTag('td',$options);
$this->renderDataCellContent($row,$data);
echo '</td>';
}
}
We can use this new class like this:
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'article-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
'id',
'title',
array(
'name' => 'author',
'value' => '$data->author->username'
),
array(
'class' => 'DataColumn',
'name' => 'sortOrder',
'evaluateHtmlOptions' => true,
'htmlOptions' => array('id' => '"ordering_{$data->id}"'),
),
array(
'class' => 'CButtonColumn',
),
),
));

Categories