Yii: CMarkdown with CGridView & CListView - php

How can I enable Markdown formatting for a specific column in GridView and ListView?

You can use custom functions to process columns. If you have PHP 5.3 you can do it the following way:
'columns'=>array(
array(
'name'=>'My markdown column',
'value'=> function($data, $row){
$parser = new CMarkdownParser();
// if data is entered by user you can purify it using safeTransform
return $parser->transform($data);
}
),
)
For PHP <5.3 it's the same except you should wrap your code into a string and avoid using anonymous function.

Related

Yii2 translating data stored in database

I'm working with Yii2 Framework, and already configured i18n component using this guide:
http://thecodeninja.net/2014/12/i18n-with-yii-2-advanced-template/
So, I can now translate strings within my php files using Yii::t() function. Translatable strings are extracted using $ ./yii message/extract console command, which generates proper translation files.
I now need to display translations for strings stored in the database.
I could use Yii:t() with a variable instead of a string as an argument like this
echo Yii:t('app', $some_string_from_db );
and make a new php file with some code like this
<?php
function dbStringsToTranslate() {
$o = Yii::t('app','db english string 1');
$o.= Yii::t('app','db english string 2');
$o.= Yii::t('app','db english string 3');
return $o;
}
This way $ ./yii message/extract command will find the needed translations.
This is working Ok, but of course $ ./yii message/extract is throwing some warnings anywhere I use Yii:t() with variables.
Skipping line 39. Make sure both category and message are static strings.
I think this is not a big deal, but well, here is my question:
Is this a right way to translate strings stored in a database?
Is there a better way to accomplish this?
You can check out this extension. https://github.com/creocoder/yii2-translateable it allows for attaching behaviors to models to support multiple languages.
I am using it now in a projects and it is easy to use.
I was having the same problem, and I found the solution with this module. In the module configuration you have the 'tables' array, in which you can specify which field(s) of which table(s) should be translated.
Then, the module has its own 'scan' action (equivalent to message/extract) with which it adds all the translatable strings to database (using DbMessageSource): all Yii::t, the specified database fields, and many more (even javascript, check the docs). It also has a nice user interface to do the translations, it's awesome!
For example, with the following configuration the field name from table nationality will be scanned and added for its translation (i.e country names):
'modules' => [
'translatemanager' => [
'class' => 'lajax\translatemanager\Module',
...
'tables' => [ // Properties of individual tables
[
'connection' => 'db', // connection identifier
'table' => 'nationality', // table name
'columns' => ['name'], // names of multilingual fields
'category' => 'database-table-name',// the category is the database table name
'categoryPrefix' => 'lx-' //
]
]
],
],
You can generate php file with some fake Yii:t() calls.
For example:
$filename = Yii::getAlias('#frontend/runtime/fake-category-translations.php');
$str = '<?php' . PHP_EOL;
foreach (Category::find()->all() as $category) {
$str .= "Yii::t('category', '{$category->name}');" . PHP_EOL;
}
file_put_contents($filename, $str);
In output this file will be something like this:
<?php
Yii::t('category', 'Art & Design');
Yii::t('category', 'Creativity');
Yii::t('category', 'Educational');
Yii::t('category', 'Education');
Yii::t('category', 'Lifestyle');
Yii::t('category', 'Casual');
So, now you can just call console method for searching untranslated strings:
php yii message/extract #frontend/messages/config.php
I know this is old but I faced same thing with rest API, and here is how I went about resolving it. Note that When saving I used
$post->comment = Yii::t('app', 'My Nice Comment here');
$post->save();
class Post extends ActiveRecord
{
public function fields()
{
$fields = parent::fields();
$fields['comment'] = function ($model) {
return Yii::t('app', $model->comment);
};
return $fields;
}
}

Yii active dropdownlist with optgroup

I try to create dropdown-list with Yii, using listData and activeDropDownList.
I use the examples found on the web, but it refuses to create the optgroups for me.
$data = CHtml::listData(MyModel::model()->getEntries(0), 'id', 'text', 'group');
Generates an array as expected:
Array([group1] => Array([10]=>FirstEntry, [20]=>SecondEntry),
[group2]=>Array([30]=>firstEntryGroup2, [40]=>firstEntryGroup2))
And so on. So it's an associative array filled with sub-arrays...
But when I use
echo CHtml::activeDropDownList($model, 'dropdownName', $data);
All I get is a flat dropdown without the optgroups. Just the entries from the sub-arrays...
Yii 1.1.6 (I read something about safe-attributes and tried to implement it, but with no success...
The old answer below is incorrect. Sorry. You create optgroups using a 'group' attribute in your drop down data array.
array(
array('id'=>256,'text'=>'TV','group'=>'Electrical'),
array('id'=>257,'text'=>'Radio','group'=>'Electrical'),
);
http://www.yiiframework.com/forum/index.php/topic/6903-how-can-i-generate-a-select-list-with-optgroup/
Old answer:
There is a great gist here that shows how do create what you're after: https://gist.github.com/StandardNerd/2909111
<?php echo CHtml::dropDownList('Cars', 'car_id', array(
'Mazda'=>array(
'mazda-rx7'=>'RX7',
'mazda-rx5'=>'RX5',
),
'Volvo'=>array(
'volvo-b9tl'=>'B9TL',
'volvo-l90e-radlader'=>'L90E Radlader',
),
)); ?>
You're currently using an activeDropDownList which should only be different because you add your $model variable instead of 'Cars' and tweak the function
One of solutions is anonymous function.
$data = CHtml::listData(
MyModel::model()->getEntries(0),
'id',
'text',
function(MyModel $aMyModelInstance){
return $aMyModelInstance->getLocalizedGroupNameForThisInstance();
});

Yii php: Displaying a widget in a Tab

i've been using Yii framework for some time now, and i've been really having a good time especially with these widgets that makes the development easier. I'm using Yii bootsrap for my extensions..but i'm having a little trouble understanding how each widget works.
My question is how do i display the widget say a TbDetailView inside a tab?
i basically want to display contents in tab forms..however some of them are in table forms...some are in lists, detailviews etc.
I have this widget :
$this->widget('bootstrap.widgets.TbDetailView',array(
'data'=>$model,
'attributes'=>$attributes1,
));
that i want to put inside a tab
$this->widget('bootstrap.widgets.TbWizard', array(
'tabs' => $tabs,
'type' => 'tabs', // 'tabs' or 'pills'
'options' => array(
'onTabShow' => 'js:function(tab, navigation, index) {
var $total = navigation.find("li").length;
var $current = index+1;
var $percent = ($current/$total) * 100;
$("#wizard-bar > .bar").css({width:$percent+"%"});
}',
),
and my $tabs array is declared like this :
$tabs = array('studydetails' =>
array(
'id'=>'f1study-create-studydetails',
'label' => 'Study Details',
'content' =>//what do i put here?),
...
...);
when i store the widget inside a variable like a $table = $this->widget('boots....);
and use the $table variable for the 'content' parameter i get an error message like:
Object of class TbDetailView could not be converted to string
I don't quite seem to understand how this works...i need help..Thanks :)
You can use a renderPartial() directly in your content, like this:
'content'=>$this->renderPartial('_tabpage1', [] ,true),
Now yii will try to render a file called '_tabpage1.php' which should be in the same folder as the view rendering the wizard. You must return what renderPartial generates instead of rendering it directly, thus set the 3rd parameter to true.
The third parameter that the widget() function takes is used to capture output into a variable like you are trying to do.
from the docs:
public mixed widget(string $className, array $properties=array ( ), boolean $captureOutput=false)
$this->widget('class', array(options), true)
Right now you are capturing the object itself in the variable trying to echo out an object. Echo only works for things that can be cast to a string.

Regarding Yii CMarkdown Class

I want to display some text in a CDetailView which was previously encoded in MarkDown format.
this is my view code:
<?php
$this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'title',
array(
'name'=>'text',
'type'=>'raw',
'value'=>$this->markdown->transform($model->text)
),
'author_id',
'date_added',
),
));
?>
and in my controller, I instantiate a CMarkDown filter like this:
private $_markdown = null;
public function getMarkdown()
{
if ( $this->_markdown === null)
{
$this->_markdown = new CMarkdown();
$this->_markdown->purifyOutput = true;
}
return $this->_markdown;
}
notice how I explicitly set purifyOutput to true.
So I created a mock post full of things like marquee and injected javascript to see how it would behave and it didn't filter anything at all!! I got an alert on my face and the marquee was all happy moving around on the page....
I found a workaround which was to set 'type'=>'html' in the CDetailView but I shouldn't need to do that, should I??
Isn't that purifyOutput option supposed to filter unwanted stuff out for me when I call the ->transform() method??
Some help, please.
To purify the output you need to use CMarkdown::processOutput, not the transform method (that one is more low-level and does not honor purifyOutput).
If you look at the documentation carefully, you will notice that processOutput mentions the purifyOutput setting while transform does not. Viewing the source confirms this.

Yii Framework: Horizontal activeCheckboxList?

I'm trying to use an activeCheckboxlist in a form in my Yii site. When generating the checkboxlist, Yii automatically puts a < br > between the checkboxes.
Is there any way to avoid/override this except with CSS?
Yes, you can do that by give 'separator' param in htmlOptions
echo CHtml::activeCheckboxList($model, $attribute, $dataArr,
array(
//..
'separator'=>'|', //new separator. html allowed also
//'template'=>'<span class="myItem">{label} {input}</span>', // use template to customize each item
//..
));
http://www.yiiframework.com/doc/api/1.1/CHtml#activeCheckBoxList-detail

Categories