I am trying to select week using datepicker in Yii . I have the following code.
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'name'=>'accountingweekselect',
'value' => date('d-M-y'),
'flat'=>true,
'htmlOptions' => array(
'size' => '10', // textField size
),
'options'=>array(
'dateFormat'=>'yy-m-dd',
'firstDay'=> 5,
'onSelect' => 'js: function(dateText, inst){
//$("#accountingweekselect_container").datepicker("setDate",dateText );
}',
'maxDate' => 'today',
'selectWeek'=>true,
)
));
?>
I would liek to make it work like the following link. http://2008.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerSelectWeek.html
Maybe i can use onselect to get the day selected and use css to highlight the row. The following code only logs the container and not the day you select.
'onSelect' =>
'js:function() {
// to automatically assign check out date input value
console.log(this);
}',
updated code
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'name'=>'accountingweekselect',
'value' => date('d-M-y'),
'flat'=>true,
'htmlOptions' => array(
'size' => '10', // textField size
),
'options'=>array(
//'dateFormat'=>'yy-m-dd',
'dateFormat'=>'yy-mm-dd',
//'firstDay'=> 5,
'showOtherMonths'=>true,// Show Other month in jquery
'selectOtherMonths'=>true,// Select Other month in jquery
'onSelect' => 'js: function(dateText, inst){
console.log($("#accountingweekselect_container div table tbody tr td").children("a.ui-state-active").html());
console.log($("#accountingweekselect_container div table tbody tr td.ui-datepicker-current-day").children("a").html());
}',
//'maxDate' => 'today',
/*'onSelect' =>
'js:function() {
// to automatically assign check out date input value
console.log(this);
}',*/
'selectWeek'=>true,
)
));
I have commented out all extra options and still doe snot work. below is code from source
jQuery('#accountingweekselect_container').datepicker({'dateFormat':'yy-mm-dd','selectWeek':true,'defaultDate':'03-Nov-14','altField':'#accountingweekselect'});
Related
I am using Drupal7,in that i have module where in i have written my own functions using php,with two dropdown list in row, now my requirement is when i select for example say "A" from 1st drop down then in 2nd drop down only related to "A" all data need show in the second dropdown,
In simple words if i select the city name from the 1st dropdown, then all the colleges of that city should display in 2nd dropdown.How can i achieve this in php?i found this link and piece of code http://w3shaman.com/article/creating-ajax-dropdown-drupal-7 but no use, it will be great helpful for me if someone answer for this.
If you created your form using Drupal Form API, then you can achive this using the Drupal Ajax.
Below is a code snippet from the Drupal Ajax examples module
function ajax_example_dependent_dropdown($form, &$form_state) {
// Get the list of options to populate the first dropdown.
$options_first = _ajax_example_get_first_dropdown_options();
// If we have a value for the first dropdown from $form_state['values'] we use
// this both as the default value for the first dropdown and also as a
// parameter to pass to the function that retrieves the options for the
// second dropdown.
$selected = isset($form_state['values']['dropdown_first']) ? $form_state['values']['dropdown_first'] : key($options_first);
$form['dropdown_first'] = array(
'#type' => 'select',
'#title' => 'Instrument Type',
'#options' => $options_first,
'#default_value' => $selected,
// Bind an ajax callback to the change event (which is the default for the
// select form type) of the first dropdown. It will replace the second
// dropdown when rebuilt.
'#ajax' => array(
// When 'event' occurs, Drupal will perform an ajax request in the
// background. Usually the default value is sufficient (eg. change for
// select elements), but valid values include any jQuery event,
// most notably 'mousedown', 'blur', and 'submit'.
// 'event' => 'change',
'callback' => 'ajax_example_dependent_dropdown_callback',
'wrapper' => 'dropdown-second-replace',
),
);
$form['dropdown_second'] = array(
'#type' => 'select',
'#title' => $options_first[$selected] . ' ' . t('Instruments'),
// The entire enclosing div created here gets replaced when dropdown_first
// is changed.
'#prefix' => '<div id="dropdown-second-replace">',
'#suffix' => '</div>',
// When the form is rebuilt during ajax processing, the $selected variable
// will now have the new value and so the options will change.
'#options' => _ajax_example_get_second_dropdown_options($selected),
'#default_value' => isset($form_state['values']['dropdown_second']) ? $form_state['values']['dropdown_second'] : '',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
return $form;
}
function ajax_example_dependent_dropdown_callback($form, $form_state) {
return $form['dropdown_second'];
}
function _ajax_example_get_second_dropdown_options($key = '') {
$options = array(
t('String') => drupal_map_assoc(
array(
t('Violin'),
t('Viola'),
t('Cello'),
t('Double Bass'),
)
),
t('Woodwind') => drupal_map_assoc(
array(
t('Flute'),
t('Clarinet'),
t('Oboe'),
t('Bassoon'),
)
),
t('Brass') => drupal_map_assoc(
array(
t('Trumpet'),
t('Trombone'),
t('French Horn'),
t('Euphonium'),
)
),
t('Percussion') => drupal_map_assoc(
array(
t('Bass Drum'),
t('Timpani'),
t('Snare Drum'),
t('Tambourine'),
)
),
);
if (isset($options[$key])) {
return $options[$key];
}
else {
return array();
}
}
I am trying to create a dependent combobox system in my Yii application.
First combobox is populated with States and the second one is dynamically generated with ajax and renderPartial() method.
Code below:
View
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => $adMulti,
'attribute' => 'state_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData(State::model()->findAll(), 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
// JS code to execute on 'select' event, the selected item is
// available through the 'item' variable.
'onSelect' => 'getCities(item.value);',
// If false, field value must be present in the select.
// Defaults to true.
'allowText' => false,
),
// Options passed to the text input
'htmlOptions' => array(
'style' => 'height: 36px',
),
));
?>
<script type="text/javascript">
function getCities(state) {
$.ajax({
url: '<?php echo $this->createUrl('ad/ajaxCities'); ?>',
data: {state_name: state},
type: 'POST',
success: function (data) {
$('#city_id-carrier').html(data);
}
});
}
</script>
<div id="city_id-carrier" class="textboxes"></div>
AdController
public function actionAjaxCities()
{
$stateName = isset($_POST['state_name']) ? $_POST['state_name'] : FALSE;
if ($stateName) {
$state = State::model()->findByAttributes(array(
'name' => $stateName
));
$stateId = $state->id;
$cities = City::model()->findAllByAttributes(array(
'state_id' => $stateId
));
$this->renderPartial('_cities', array(
'cities' => $cities,
'stateId' => $stateId
), FALSE, TRUE
);
}
}
_cities.php
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => AdMulti::model(),
'attribute' => 'city_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData($cities, 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
// JS code to execute on 'select' event, the selected item is
// available through the 'item' variable.
// 'onSelect' => 'getLocalities(item.value);',
// If false, field value must be present in the select.
// Defaults to true.
'allowText' => false,
),
));
?>
The code is working and creating the combobox for the first time. But when I change the value in state combobox, something weird happens. A new combobox is created, but the values shown are still from the first combobox generated.
I am getting an error "TypeError: this.input is undefined" in Firebug Console.
I tried creating unique id for combobox using uniqid() but it isn't affecting the id of select element of the combobox.
If I change
$('#city_id-carrier').html(data)
to
$('#city_id-carrier').append(data)
it is working well but with multiple combobox generated.
Any ideas/suggestions to make this work?
I've found a solution to get this working. Instead of creating the combobox dynamically, place the combobox once and then populate it dynamically upon each request. Much like dependent dropdown.
A combobox is a combination of a dropdown and textbox. So, note down the id of the hidden dropdown and update it upon ajax update.
Code:
View:
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => $adMulti,
'attribute' => 'state_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData(State::model()->findAll(), 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
// JS code to execute on 'select' event, the selected item is
// available through the 'item' variable.
'onSelect' => 'getCities(item.value);',
// If false, field value must be present in the select.
// Defaults to true.
'allowText' => false,
),
));
?>
<script type="text/javascript">
function getCities(state) {
$.ajax({
url: '<?php echo $this->createUrl('ad/ajaxCities'); ?>',
data: {state_id: state},
type: 'POST',
beforeSend: function() {
$('#AdMulti_city_id_combobox').val(''); // emptying textbox in case a value is previously selected.
},
success: function (data) {
$('#AdMulti_city_id').html(data); // populating the hidden dropdown.
}
});
}
</script>
<?php
$this->widget('ext.combobox.EJuiComboBox', array(
'model' => $adMulti,
'attribute' => 'city_id',
// data to populate the select. Must be an array.
'data' => CHtml::listData(array(''), 'id', 'name'),
'assoc' => true,
// options passed to plugin
'options' => array(
'allowText' => false,
),
));
?>
AdController
public function actionAjaxCities()
{
$stateName = isset($_POST['state_id']) ? $_POST['state_id'] : FALSE;
if ($stateName) {
$state = State::model()->findByAttributes(array(
'name' => $stateName
));
$cities = City::model()->findAllByAttributes(array(
'state_id' => $state->id
));
$data = CHtml::listData($cities, 'id', 'name');
foreach ($data as $id => $name) {
echo CHtml::tag('option', array('value' => $id),
CHtml::encode($name), TRUE);
}
}
}
First, actually I'm not using CGridView, but I'm using TbExtendedGridView from YiiBooster. I use CGridView on the title because it's more familiar, but still these two things works in quite the same way.
I'm enabling inline edit on my TbExtendedGridView (TbJEditableColumn). TbExtendedGridView is using jquery's Jeditable for this functionality. This Jeditable also applicable to CGridView.
Thanks to this SO's question: Change the Row Color Based on the Column value in CGridView
I know how to change the row color. But, it's still not working with the inline edit functionality. So, my question is, how can that rowCssClassExpression be updated everytime I edit some value on a column?
This is my view's code on [root]/protected/views/transaction/admin.php
<?
$this->widget('bootstrap.widgets.TbExtendedGridView', array(
'id'=>'transaction-grid',
'rowCssClassExpression'=>'$data->getCssClass()',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
array(
'name'=>'date',
'value'=> 'date("j M Y", strtotime($data->date))',
'htmlOptions' => array('style'=>'width:52px')
),
array(
'name' => 'amount',
'value' => 'number_format($data->amount, 0, ",", ".")',
'htmlOptions' => array('class'=>'currency', 'style'=>'width:72px')
),
array(
'name' => 'category_name',
'value'=>'$data->category->name',
'header'=>'Category',
'sortable' => 'true',
'htmlOptions' => array('style'=>'width:131px'),
'class'=>'bootstrap.widgets.TbJEditableColumn',
'jEditableOptions' => array(
'type' => 'optgroup',
'loadurl' => Yii::app()->baseUrl . '/index.php/transaction/getCategory',
'submitdata' => array('attribute'=>'category'),
'cssclass' => 'form',
'width' => '180px',
'submit' => 'save changes'
)
),
array(
'name'=>'desc',
'value'=>'$data->desc',
'htmlOptions' => array('class'=>'desccell'),
'class'=>'bootstrap.widgets.TbJEditableColumn',
'jEditableOptions' => array(
'type' => 'text',
// very important to get the attribute to update on the server!
'submitdata' => array('attribute'=>'desc'),
'cssclass' => 'form',
'width' => '180px',
)
),
array(
'htmlOptions' => array('nowrap'=>'nowrap'),
'class'=>'bootstrap.widgets.TbButtonColumn',
)
)
)
And this is my getCssClass code on [root]/protected/models/Transaction.php:
public function getCssClass(){
$categoryType = Category::model()->findByPk($this->categoryId)->getAttribute("type");
$categoryName = Category::model()->findByPk($this->categoryId)->getAttribute("name");
$class = "";
if($categoryName == "Uncategorized Income"){
$class = "darkgreen";
}
else if($categoryName == "Uncategorized Expense"){
return "darkred";
}
else if($categoryType == "INCOME"){
return "green ";
}
else if($categoryType == "EXPENSE" || $categoryType == "COST OF GOODS"){
return "red ";
}
else if($categoryType == "WITHDRAW" || $categoryType == "DEPOSIT" ){
return "blue ";
}
else{
return "grey ";
}
return $class . " " . $categoryName . " " . $categoryType;
}
Use the 'afterAjaxUpdate' attribute to fire a javascript function on any update.
'afterAjaxUpdate' => ' function(){ //enterJScode }',
I have a gridview which contains a checkbox column and also uses pagination. When I check some checkboxes in the first page and navigate to the second page and check another one in the second page, the options I checked in the first page is not retained there. Is it posssible to retain the checkbox values during pagination?
Code for Gridview is
$widget = $this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $model->search(),
'cssFile' => Yii::app()->baseUrl . '/media/js/admin/css/admingridview.css',
//'filter' => $model,
'ajaxUpdate' => true,
'enablePagination' => true,
'columns' => array(
array(
'name' => 'id',
'header' => '#',
'value' => '$this->grid->dataProvider->pagination->currentPage * $this->grid->dataProvider->pagination->pageSize + ($row+1)',
),
array(
'class' => 'CCheckBoxColumn',
'selectableRows' => '2',
'header' => 'Selected',
),
array(
'name' => 'fb_user_id',
'header' => 'FaceBook Id',
'value' => 'CHtml::encode($data->fb_user_id)',
),
array(
'name' => 'first_name',
'header' => 'Name',
'value' => 'CHtml::encode($data->first_name)',
),
array(
'name' => 'email_id',
'header' => 'Email',
'value' => 'CHtml::encode($data->email_id)',
),
array(
'name' => 'demo',
'type' => 'raw',
'header' => "Select",
'value' => 'CHtml::checkBox("email[]","",array("class"=>"check","value"=>$data->email_id))',
),
),
));
Edit:
Extension for remembering the selected options in gridview,check this link Selgridview
Thanks to bool.dev
You could use sessions/cookies to store the checked values. I'm not very sure how to make cookies work, so i'll tell you how to do it with sessions. Specifically the user session that yii creates.
Now to use sessions we need to pass the checked (and unchecked) ids to the controller, therefore we'll modify the data being sent to the controller on every ajax update(i.e between paginations), to do this we exploit the beforeAjaxUpdate option of CGridView.
I'm also using CCheckBoxColumn instead of the following in your code(of course you can modify the solution to suit your own needs):
array(
'name' => 'demo',
'type'=>'raw',
'header' => "Select",
'value' => 'CHtml::checkBox("email[]","",array("class"=>"check","value"=>$data->email_id))',
),
GridView Changes:
<?php $this->widget('zii.widgets.grid.CGridView', array(
// added id of grid-view for use with $.fn.yiiGridView.getChecked(containerID,columnID)
'id'=>'first-grid',
'dataProvider'=>$model->search(),
'cssFile' => Yii::app()->baseUrl . '/media/js/admin/css/admingridview.css',
// added this piece of code
'beforeAjaxUpdate'=>'function(id,options){options.data={checkedIds:$.fn.yiiGridView.getChecked("first-grid","someChecks").toString(),
uncheckedIds:getUncheckeds()};
return true;}',
'ajaxUpdate'=>true,
'enablePagination' => true,
'columns' => array(
array(
'name' => 'id',
'header' => '#',
'value' => '$this->grid->dataProvider->pagination->currentPage * $this->grid->dataProvider->pagination->pageSize + ($row+1)',
),
array(
'name' => 'fb_user_id',
'header' => 'FaceBook Id',
'value' => 'CHtml::encode($data->fb_user_id)',
),
array(
'name' => 'first_name',
'header' => 'Name',
'value' => 'CHtml::encode($data->first_name)',
),
array(
'name' => 'email_id',
'header' => 'Email',
'value' => 'CHtml::encode($data->email_id)',
),
/* replaced the following with CCheckBoxColumn
array(
'name' => 'demo',
'type'=>'raw',
'header' => "Select",
'value' =>'CHtml::checkBox("email[]","",array("class"=>"check","value"=>$data->email_id))',
),
*/
array(
'class' => 'CCheckBoxColumn',
'selectableRows' => '2',
'header'=>'Selected',
'id'=>'someChecks', // need this id for use with $.fn.yiiGridView.getChecked(containerID,columnID)
'checked'=>'Yii::app()->user->getState($data->email_id)', // we are using the user session variable to store the checked row values, also considering here that email_ids are unique for your app, it would be best to use any field that is unique in the table
),
),
));
?>
Pay special attention to the code for beforeAjaxUpdate and CCheckBoxColumn, in beforeAjaxUpdate we are passing checkedIds as a csv string of all the ids(in this case email_ids) that have been checked and uncheckedIds as a csv string of all the unchecked ids, we get the unchecked boxes by calling a function getUncheckeds(), which follows shortly. Please take note here, that when i was testing i had used an integer id field (of my table) as the unique field, and not an email field.
The getUncheckeds() function can be registered like this anywhere in the view file for gridview:
Yii::app()->clientScript->registerScript('getUnchecked', "
function getUncheckeds(){
var unch = [];
/*corrected typo: $('[name^=someChec]') => $('[name^=someChecks]') */
$('[name^=someChecks]').not(':checked,[name$=all]').each(function(){unch.push($(this).val());});
return unch.toString();
}
"
);
In the above function pay attention to the selectors and each and push function.
With that done, we need to modify the controller/action for this view.
public function actionShowGrid(){
// some code already existing
// additional code follows
if(isset($_GET['checkedIds'])){
$chkArray=explode(",", $_GET['checkedIds']);
foreach ($chkArray as $arow){
Yii::app()->user->setState($arow,1);
}
}
if(isset($_GET['uncheckedIds'])){
$unchkArray=explode(",", $_GET['uncheckedIds']);
foreach ($unchkArray as $arownon){
Yii::app()->user->setState($arownon,0);
}
}
// rest of the code namely render()
}
That's it, it should work now.
For developing that scheme you would need to know working of what happens when you navigate.
When ever you navigate to a pagination page ajax calls are made and new data is received and it is fetched from CActive Record or what ever the data source. New data is in accordance of database records or source records. when you come back to previous page again Ajax call is made and content is updated so same comes as it is in database.
what i feel is you should save data of checked items temporary and make it permanent if action is made.
You can do something like this
<script type="text/javascript">
$("input:checkbox").click(function () {
var thisCheck = $(this);
if (thisCheck.is (':checked')){
// do what you want here, the way to access the text is using the
// $(this) selector. The following code would output pop up message with
// the selected checkbox text
$(this).val());
}
});
</script>
you can save temporary storage somewhere
Also make this work on normal form submit:
I wanted to add this as a comment on bool.dev's answer, but I do not have enough reputation to do that yet. So I had to put it in a separate answer.
bool.dev, your answer is great and it works well, thanx.
However, as intended, it only works when ajax calls update the gridview. I have the gridview forming part of a form, so I wanted it to also work on normal submission of the form, otherwise the checkboxes are not loaded again when there are other validation errors on the form.
So, in ADDITION to what you did, I added hidden fields on my form e.g.:
<input type="hidden" name='checkedBox1' id='checkedBox1' value=''>
<input type="hidden" name='uncheckedBox1' id='uncheckedBox1' value=''>
Then, before submitting the form, my sumbit button runs your getChecked() and getUncheckeds() functions and store their results in the hidden fields:
if ($('#checkedBox1').length >0) {$('[name=checkedBox1]').val(getChecked());}
if ($('#uncheckedBox1').length >0) {$('[name=uncheckedBox1]').val(getUncheckeds());}
In the controller, besides from checking for $_GET['checkedIds'], you also check for $_POST['checkedBox1'] and store its values to session in the same way you do for $_GET['checkedIds'], using the same session variable.
Do the same with $_POST['uncheckedBox1'].
That should work.
I want an alert that pops when user tries to click "add to favorite"
1) if there's no checkboxes checked.
2) I also want to know how to get the values of the checked boxes here's my current code on backend
<?php $this->widget('zii.widgets.grid.CGridView',array(
'id' => 'wsrecruitcvhead-grid',
'dataProvider' => $model->search(),
#'filter' => $model,
'columns' => array(
array(
'name' =>'',
'value' => 'CHtml::checkBox("rid[]",null,array("value"=>$data->ResumeID,"id"=>"rid_".$data->ResumeID))',
'type'=>'raw',
'htmlOptions' => array('width'=>5),
'visible' => !Yii::app()->user->isGuest,
),
array(
'name' => 'ResumeTitle',
'value' =>$model->ResumeTitle,
),
'ResumeSummaryIntroduction',
'Name',
array(
'class' => 'CButtonColumn',
'viewButtonUrl' => 'Yii::app()->createUrl("wsrecruitcvhead/view",array("id"=>$data["ResumeID"]))',
'template'=>'{view}',
),
),
));
?>
and here's the screen shot http://pastebin.com/sEpJBCiU
I hope this helps you.
Your code works just fine, just tried it. I would implement the functionality you mentioned using jQuery, like this:
<script type="text/javascript">
$("input:checkbox").click(function () {
var thisCheck = $(this);
if (thisCheck.is (':checked')){
// do what you want here, the way to access the text is using the
// $(this) selector. The following code would output pop up message with
// the selected checkbox text
$(this).val());
}
});
</script>
This code selects all those DOM elements of type checkbox, and then checks with the if condition if it is selected or not. Here you can find more information about this jQuery selector. jQuery is such a powerful tool!!
For get all seleccions of a Grid yii provides the follow code
var seleccions = ($.fn.yiiGridView.getSelection('id_my_cgridview'));
this return an array with the values of checkboxes selected