Dependent dropdownlist with chosen jquery plugin. Dynamic update - yii

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.

Related

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.

Yii2 use own sql query in gridview (gii)

I'm fairly new to Yii(2).
I need to show the total amount of a single product, ignoring the locations. As shown here:
Before:
After:
Now, I need to show this in the gridview that Gii automatically made. But with my own query inside of it.
So instead of this:
It should show the total amount.
I have no idea how to use my own query inside of that.. Any help please? It's a standard Gii CRUD, can post code if requested.
Create new method inside of your related model and call with $data
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
.....
# below $data is current Model initial
['label' => 'Count', 'format' => 'html',
'value' => function($data){return $data::getCreatedStaticFuntion($data->product_id);}
],
# or use like below
['label' => 'Count', 'format' => 'html',
'value' => function($data){
$sql = 'SELECT * FROM tbl_product WHERE id ='.data->product_id;
return \app\models\Product::findBySql($sql)->all();}
],
....

Get images by custom field

I'm trying to display all images that have a certain custom field from the types plugin set to true. It would also work to filter them by post_content or post_excerpt but none of my attempts have worked so far.
<?
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_content' => 'foo',
'numberposts' => -1
);
?>
<? print_r(get_posts($args)); ?>
This get's all images allthough only one has the post_content foo. My attempt to use WP_Query failed miserably as well.
Any help is appreciated!
WP_Query method :
$args = array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'meta_query' => array(
array(
'key' => 'color',
'value' => 'blue',
'compare' => 'LIKE',
),
),
);
$query = new WP_Query( $args );
I am presuming that the reason why you failed with WP_Query is due to the following condition.
Codex states : The default WP_Query sets 'post_status'=>'publish', but attachments default to 'post_status'=>'inherit' so you'll need to explicitly set post_status to 'inherit' or 'any' as well.
http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters
get_posts method :
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'meta_key' => 'custom-field',
'meta_value' => 'custom value',
'numberposts' => -1
);
print_r(get_posts($args));
The only draw back with this method is that the meta_value needs to exactly match what was entered in the custom field. If you still like to use get_posts then use the meta_query as shown in WP_Query example above.

Passing ID to CGridView

How to pass grid row id from CGridView to filter values in another CGridView opened in Dialog
My View Code for Form Grid(see screenshot),
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'document-grid',
'dataProvider'=>$model->search(),
'columns'=>array(
array(
'class' => 'CButtonColumn',
'template' => '{edit}{DocumentDelete}',
'buttons' => array(
'DocumentDelete' => array(
'imageUrl'=>Yii::app()->request->baseUrl.'/images/delete.png',
'url'=>'Yii::app()->createUrl("baseContact/DocumentDelete", array("id"=>$data->crm_document_id))',
),
'edit' => array(
'imageUrl'=>Yii::app()->request->baseUrl.'/images/update.png',
'url'=>'Yii::app()->createUrl("baseContact/edit", array("id"=>$data->crm_document_id))',
),
),),
'crm_document_id',
'name',
'doc_type',
'delivery_method',
'content_subject',
'content_body',
'is_active',
),
)); ?>
View Code for Popup Grid,
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'ManagedocumentAttach-grid',
'dataProvider'=>DocumentAttachmentModel::model()->search(),
//'filter'=>$model,
'columns'=>array(
array(
'name'=>'',
'value'=>'CHtml::checkBox("cid[]",null,array("value"=>$data->crm_document_attachment_id,"id"=>"cid_".$data->crm_document_attachment_id))',
'type'=>'raw',
'htmlOptions'=>array('width'=>5),
//'visible'=>false,
),
'crm_document_id',
'name',
'type',
),
)); ?>
how to pass Form edited row id to Popup GridView ?
Clearly you use AJAX to get the popup so i would first would make sure the ID of the edit button is the same as the ID from the item you want to open. Then you can do the following JS (using JQUERY)
$(".edit").on("click", function() {
var id = $(this).attr("id");
$.ajax({
type:"POST",
url: "controller/action/"+id;
success: function(data) {
//open dialog box and fill it with data
}
});
You could also add the id as data so you can get it with $_POST instead of it being a variable defined by the function. If you write the JS in a php document you can use $this->createUrl, but that is just whatever you prefer.
If with this you can not solve your problem then let us see how you implemented it right now.
i am not sure ... but i have a technique to do it....
if i have to do something like this ....
i will give class by htmlOptions and after that i will get value which should be an id to open popup..
example
<?php $this->widget('bootstrap.widgets.TbGridView', array(
'dataProvider' => $dataProvider ,
'type' => TbHtml::GRID_TYPE_BORDERED,
'template' => "{items}",
'columns' => array(
array(
'name' => 'vendor_configuration_id',
'header' => $dataProvider->model->getAttributelabel('vendor_configuration_id'),
'htmlOptions' => array('class'=>'idClass'),
),
array(
'name' => 'menu_type',
'header' => $dataProvider->model->getAttributelabel('menu_type'),
'htmlOptions' => array(),
),
?>
now jquery for it
$('.idClass').on("click",function(){
var neededId = $(this).html();
alert(neededId );
//openn popup based on this id or caal ajax to retrive data based on this
});

How do you add a button to a CGridView?

Sounds simple, right? I've searched high and low and I can't find out how to do this. I have a CGridView:
$dataProvider = new CArrayDataProvider ($auctions);
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>array(
'id::ID',
'product.title::Title',
'state::Status',
),
));
I want to add a fourth column that only contains a simple button that will execute javascript when pressed. I've tried:
array(
'class' => 'CButtonColumn',
),
This just gives me an error:
Undefined property: stdClass::$primaryKey
Any ideas?
Try this:
$dataProvider = new CArrayDataProvider ($auctions);
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>array(
'id::ID',
'product.title::Title',
'state::Status',
array(
'type' => 'raw',
'value' => '<button onclick=\'alert("It works!")\' value="clickme"/>'
)
),
));
The best way to do it is with CButtonColumn::template and CButtonColumn::buttons.
array(
'class' => 'CButtonColumn',
'template' => '{view} {update} {delete} {copy}',
'buttons'=>array(
'copy' => array(
'label'=>'Copy', // text label of the button
'url'=>"CHtml::normalizeUrl(array('copy', 'id'=>\$data->id))",
'imageUrl'=>'/path/to/copy.gif', // image URL of the button. If not set or false, a text link is used
'options' => array('class'=>'copy'), // HTML options for the button
),
),
),
In this example there are the three default buttons and one custom, the 'copy' button.
If you don't want some of the default buttons (i.e. view, update and delete), you can remove them. Then, define the properties of the button that you added. I defined label, url, image and html options.