How to show categories in a treeview in Yii - yii

I have a category model with this structure:
id,name,parent_id
I want to display categories in a treeview in Yii. As I found there is a widget called 'CTreeView' but I cannot find an clear example how to use it.
Pleas help me.

Yes, there is not much tour for CTreeView. But You can look here
http://www.yiiframework.com/wiki/?tag=ctreeview
Generating tree from database in Yii
http://www.yiiplayground.com/index.php?r=UiModule/ui_other/treeView

1. Download Extension
Download AIOTree
2. Extract it & put in your extension directory of yii project(extension/AIOTree/your extract files)
3. Now add this code at any where you want
<?php
$data=array(
'1'=>array('parentid'=>'','text'=>'One'),
'2'=>array('parentid'=>'','text'=>'Two'),
'3'=>array('parentid'=>'','text'=>'Three'),
'11'=>array('parentid'=>'1','text'=>'One-One'),
'12'=>array('parentid'=>'1','text'=>'One-Two'),
);
// AIOTree
Yii::import("application.extensions.AIOTree.*");
$this->Widget('AIOTree',array(
'data'=>$data,
));
?>

You can create array with your data from database and use it in CTreeView widget
// Your array with data
$data = array(
array(
'text' => 'Node 1',
'expanded' => true, // expanded branch or not (true by default)
'children' => array(
array('text' => 'Node 1.1'),
array('text' => 'Node 1.),
array('text' => 'Node 1.3')
)
),
);
// In your view call widget
$this->widget('CTreeView', array('data' => $data));
See more widget capability in offical documentatio: (http://www.yiiframework.com/doc/api/1.1/CTreeView)

Related

Add new fields in "Files/Links Upload" tt_content

I use File Links [uploads] Content Element to show list of files, and I need to add a field on this CE to show description.
I found this on the documentation : https://docs.typo3.org/m/typo3/reference-coreapi/8.7/en-us/ExtensionArchitecture/ExtendingTca/Examples/#example-2-extending-the-tt-content-table but I couldn't apply it because of a lack of skill with PHP and T3 Customization.
In which file I should add the follwing code :
CREATE TABLE tt_content (
tx_files_description tinyint(4) DEFAULT '0' NOT NULL
);
How can I customize the follwing code ? :
$temporaryColumn = array(
'tx_files_description' => array (
'exclude' => 0,
'label' =>
'LLL:EXT:examples/Resources/Private/Language/locallang_db.xlf:tt_content.tx_files_description',
'config' => array (
'type' => 'check',
)
)
);
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTCAcolumns(
'tt_content',
$temporaryColumn
);
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addFieldsToPalette(
'tt_content',
'visibility',
'tx_files_description',
'after:linkToTop'
);
Why do it in such a complicated way?
tt_contentrecords already has a lot of fields which are not used for rendering the CType uploads.
Even the description field is available, so it is no RTE field. (all CEs have this field for information in the backend only)
You only need to use it in the FE-rendering, though you need to modify the fluid template.
If you need a RTE field, you should activate the field bodytext in the BE form, as it comes with a proper definition and rendering.
You still have to insert the rendered field in the fluid template.
Since you created your own content element i can not really know how to position the lement, but what i can do is to help you create it. I just tested on my TYPO3 installtion and it works.
ext_tables.sql
CREATE TABLE tt_content (
tx_files_description text,
);
yourExtension/Configuration/TCA/Overrides/tt_content.php
$temporaryColumn = [
'tx_files_description' => [
'exclude' => true,
'label' => 'LLL:EXT:your_extension_key/Resources/Private/Language/locallang.xlf:tt_content.tx_files_description',
'config' => [
'type' => 'text',
'enableRichtext' => false,
],
],
];
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTCAcolumns(
'tt_content',
$temporaryColumn
);
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addToAllTCAtypes(
'tt_content',
'tx_files_description',
'general',
'before:media'
);
Assuming that you re using TYPO3 v9 go to the module Maintenance and press Analyze Database, then clear all cache.
If you are on TYPO3 v7-v8 then go to the install module and Run compare database (something like that). Clear the cache.
Then on your extended tab:
Best regards

Yii 2.0 Select Pre-selected values from Database

I have been trying to fix an issue but to no avail but i am sure i will find a solution here. I am using Kartik 2.0 Select extension to do a multiple select. Fine, all working when inserting into the database but i am unable to retrieve the saved records to be displayed as selected back in the select field.
//I have included the kartik widgets already
use kartik\widgets\Select2;
<label>Desired Specialization(s)</label>
<?= $form->field($spec, 'id')->label(false)->widget(Select2::classname(), [
'data' => $model->getAllSpecializations(),
'options' => ['placeholder' => 'You can choose more than one specialization ...'],
'pluginOptions' => [
'allowClear' => true,
'multiple' => true
],
]);
?>
</div>
Please, your reply will be appreciated. Thanks
I think you need to add the saved values as the initial data? Like so:
'value' => $savedDataArray, // initial value
http://demos.krajee.com/widget-details/select2#usage-tags
After much digging into the code, i found a way on how to display selected database values into a multi-select option using Yii Select2
My Model
public function getCandidateLanguage()
{
$langValues = (new \yii\db\Query())
->select('c.language_id AS id, l.lang_name')
->from('candidate_language c ')
->innerJoin('languages l','c.language_id = l.id')
->where('c.candidate_id='.$this->candidate_id)
->orderBy('c.language_id')
->all();
return \yii\helpers\ArrayHelper::map($langValues,'id','lang_name');
}
My View
use kartik\widgets\Select2;
<?php
//the line below is to fetch the array key of $model->getCandidateLanguage() array
$lang->id = array_keys($model->getCandidateLanguage()); // value to initialize
echo Select2::widget([
'model' => $lang,
'attribute' => 'id',
'data' => $model->getAllLanguages(),
'options' => ['placeholder' => 'Choose multiple languages'],
'pluginOptions' => [
'allowClear' => true,
'multiple' => true,
'tags' => true,
],
]);
?>
Hope it help someone who is facing the same issue.

how to integrate multimodelform with echmultiselect yii?

I am running into a little snag with combining extensions "EchMultiSelect" and "MultiModelForm" of YII framework.
What I'm trying to do is copy a set of form elements one of which elements is an EchMultiSelect widget.
According to tutorial on the jqRelCopy page, I would need to pass a copy of the element (datePicker in their example) to the 'jsAfterNewId' option:
'jsAfterNewId' => JQRelcopy::afterNewIdDatePicker($datePickerConfig),
So, I tried to modify that to:
'jsAfterNewId' => MultiModelForm::afterNewIdMultiSelect($memberFormConfig['elements']),
Where I also added the following to MultiModelForm.php:
public static function afterNewIdMultiSelect($element)
{
$options = isset($element['options']) ? $element['options'] : array();
$jsOptions = CJavaScript::encode($options);
return "if(this.attr('multiple')=='multiple'){this.multiselect(jQuery.extend({$jsOptions}));};";
}
its copied and working properly when i am using Add Person link but what happens if i am adding/cloning three items for example and when i change the third item multiselct option then its reflecting to the first multiselect dropdown only this is same for other as well also when i am adding new items by clicking on the Add Person link then its cloning the same element to the new row item
here is the code for the form configuration variables and multimodel widget call.
//$userList=array of the userIds from users table
$memberFormConfig = array(
'elements'=>array(
'userId'=>array(
'type'=>'ext.EchMultiSelect.EchMultiSelect',
'model' => $User,
'dropDownAttribute' => 'userId',
'data' => $userList,
'dropDownHtmlOptions'=> array(
'style'=>'width:500px;',
),
),
...
...
));
calling the MultiModelForm widget from the same view file
$this->widget('ext.multimodelform.MultiModelForm',array(
'id' => 'id_member', //the unique widget id
'formConfig' => $memberFormConfig, //the form configuration array
'model' => $model, //instance of the form model
'tableView' => true,
'validatedItems' => $validatedMembers,
'data' => Person::model()->findAll('userId=:userId', array(':userId'=>$model->id)),
'addItemText' => 'Add Person',
'showAddItemOnError' => false, //not allow add items when in validation error mode (default = true)
'fieldsetWrapper' => array('tag' => 'div',
'htmlOptions' => array('class' => 'view','style'=>'position:relative;background:#EFEFEF;')
),
'removeLinkWrapper' => array('tag' => 'div',
'htmlOptions' => array('style'=>'position:absolute; top:1em; right:1em;')
),
'jsAfterNewId' => MultiModelForm::afterNewIdMultiSelect($memberFormConfig['elements']),
));
Can someone help me with this please?
Thanks in advance!
After a long searching and googleing i found the solution for this, just replace the function in your MultiModelForm.php:
public static function afterNewIdMultiSelect($element)
{
$options = isset($element['options']) ? $element['options'] : array();
$jsOptions = CJavaScript::encode($options);
return "if ( this.hasClass('test123456') )
{
var mmfComboBoxParent = this.parent();
// cloning autocomplete and select elements (without data and events)
var mmfComboBoxClone = this.clone();
var mmfComboSelectClone = this.prev().clone();
// removing old combobox
mmfComboBoxParent.empty();
// addind new cloden elements ()
mmfComboBoxParent.append(mmfComboSelectClone);
mmfComboBoxParent.append(mmfComboBoxClone);
// re-init autocomplete with default options
mmfComboBoxClone.multiselect(jQuery.extend({$jsOptions}));
}";
}
Thats It....!!
Thanks...!!!

Dependent dropdownlist with chosen jquery plugin. Dynamic update

I'm new to yii so dont be strict.
I have dependent dropdown list with countries/states from model. It works perfect until comes Chosen jquery plugin.
I use http://harvesthq.github.com/chosen/.
So the problem is in howto trigger liszt:updated, so 2nd select can obtain data from standart select.
This is view code which makes that lists.
if ($field->varname=='country') {
echo $form->dropDownList($profile, $field->varname,CHtml::listData(Countries::model()->findAll(),'short','title'), array(
'class'=>"chzn-select",
'empty'=>"Select country",
'ajax' => array(
'type' => 'POST',
'url'=>$this->createUrl('registration/state'),
'update' => '#Profile_state',
'data'=>array('country'=>'js:this.value',),
)));
}
elseif($field->varname=='state') {
echo $form->dropDownList($profile, $field->varname,array(), array(
'empty'=>"Select state",
'class'=>"chzn-select",
));
Ok. I found the solution. Writing it here(maybe someone will find it usefull).
In our view file
echo $form->dropDownList($profile, $field->varname,CHtml::listData(Countries::model()->findAll(),'short','title'), array(
'class'=>"chzn-select",
'empty'=>"Select country",
'ajax' => array(
'type' => 'POST',
'url'=>$this->createUrl('registration/state'),
'update' => '#Profile_state',
'data'=>array('country'=>'js:this.value',),
'success'=> 'function(data) {
$("#Profile_state").empty();
$("#Profile_state").append(data);
$("#Profile_state").trigger("liszt:updated");
} ',
)));
Then in 2nd dropdownlist leve data empty:
echo $form->dropDownlist($profile, $field->varname, array(),array(
'class'=>"chzn-select",
'empty'=>"Select state",
));
Works perfect for me but gave me hours of research work.

how to add static elements to yii dropDownList?

echo $form->dropDownList(
$model,'categoryId',
CHtml::listData(Category::model()->findAllBySql(
'SELECT * from category where isnull(parent_id)'),
'id', 'name'),
array(
'empty'=>Yii::t('fim','Search All'),
Yii::t('fim','Jobs'),
Yii::t('fim','Training'),
Yii::t('fim','Events'),
Yii::t('fim','News')
)
);
Jobs, Training, Events and News are not appearing.
How can/should we build this, in order to add those values to the select box ?
Thanks
You cannot add static elements by using the $htmlOptions parameter. Here is how I do it:
$data = CHtml::listData(Category::model()->findAllBySql(
'SELECT * from category where isnull(parent_id)'),
'id', 'name');
// Add extra options here: I am actually prepending with this syntax,
// but you are free to append or interleave instead. Array keys are the values.
$static = array(
'jobs' => Yii::t('fim','Jobs'),
'training' => Yii::t('fim','Training'),
'events' => Yii::t('fim','Events'),
'news' => Yii::t('fim','News'),
);
echo $form->dropDownList(
$model,
'categoryId',
$static + $data,
array('empty'=>Yii::t('fim','Search All')));
For me, what i did is i added jquery code, i append an html option
$("#categoryId").append("<option value='0'>Additional Field</option>");
its less complicated and it works for me