Dropdownlist is not updating using Yii - php

I'm using
PHP language , yii-1.1.13 framework and MySQL DB.
In my Views , I have this code:
Views Code of Main Page
/** Start Widget **/
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'dialog',
'options' => array(
'title' => 'Locations Management',
'autoOpen' => false,
'modal' => true,
'resizable' => false,
'dialogClass' => 'managelocation-dialog-class',
'show'=>array(
'effect'=>'drop',
'duration'=>500,
),
'hide'=>array(
'effect'=>'drop',
'duration'=>500,
),
),
));
/**
* Render dialog view.
*/
echo $this->renderPartial('manageLocationDialog', array(
'model' => $model,
'locationInfo' => $locationInfo,
));
$this->endWidget('zii.widgets.jui.CJuiDialog');
/**
* Filter Dialog widget
*/
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'filter-dialog',
'options' => array(
'title' => 'Filter',
'autoOpen' => false,
'modal' => true,
'resizable' => false,
'width' => 350,
'dialogClass' => 'location-dialog-class',
'show'=>array(
'effect'=>'drop',
'duration'=>500,
),
'hide'=>array(
'effect'=>'drop',
'duration'=>500,
),
),
));
/**
* Render the filter dialog view.
*/
echo $this->renderPartial('manageLocationFilter', array(
'filterFormloc' => $filterFormloc,
'locationInfo' => $locationInfo,
));
$this->endWidget('zii.widgets.jui.CJuiDialog');?>
Views Code of Add/Edit Dialog
<div id="action-button-div" class="row">
<?php
echo CHtml::button('Create New', array(
'id'=>'action-button',
'class'=>'submit-button',
'onclick'=>"{submitActionJs();}",
'update' =>'#filter_province_name',
));
?>
<?php
echo CHtml::button('Cancel', array(
'id'=>'cancel-button',
'onclick'=>'{$("#dialog").dialog("close");}',
));
?>
</div>
Views Code of Filter Dialog
<div id="dialog-contents-container">
<div class="row">
<div id="filter-mode-div">
<?php
echo $form->labelEx($filterFormloc, 'filter_mode', array(
'label' => 'Filter Mode',
));
?>
<div>
<?php
echo $form->radioButtonList($filterFormloc, 'filter_mode', array(
1=>'ON',2=>'OFF'),array('id'=>'filter_mode'
));
?>
</div>
</div>
<div id="reset-button-div">
<?php
echo CHtml::button('Reset Settings', array(
'id'=>'reset-button',
'onclick'=>'{$(this.form).find("textarea, :text, select").val("").end().find(":checked").prop("checked", false);$("#ManageLocationFilterForm_filter_mode_1").attr("checked",true);}',
));
?>
</div>
</div>
<div id="under-container">
<div class="row">
<div id="province_name">
<?php
echo $form->labelEx($filterFormloc, 'province_name', array(
'label' => 'Province *',
));
?>
<div>
<?php
echo $form->dropDownList($filterFormloc, 'province_name',
$locationInfo->getAllProvincesForSelection(true, 'Select Province'),
array(
'id' => 'filter_province_name',
'class' => 'selectbox',
)
);
?>
</div>
</div>
</div>
</div>
<div id="action-button-div" class="row">
<?php
echo CHtml::button('Apply Filter Settings', array(
'id'=>'action-button_2',
'onclick'=>"{submitFilterActionJs();}"
));
?>
<?php
echo CHtml::button('Cancel', array(
'id'=>'cancel-button_2',
'onclick'=>'{$("#filter-dialog").dialog("close");}',
));
?>
</div>
</div>
In my controller, below is my code:
public function actionRegisterLocation() {
$model = new ManageLocationForm;
if (isset($_POST['ManageLocationForm']))
{
$model->attributes = $_POST['ManageLocationForm'];
if (Yii::app()->request->isAjaxRequest)
{
if ($model->hasErrors())
{
$errors = '';
foreach ($model->getErrors() as $e) $errors .= implode($e).'<br>';
echo CJSON::encode(array(
'status'=>'failure',
'messages'=>$errors
));
}
else
{
$locationInfo = new LocationInfo;
if ($model->operation_mode === AdminGeneralHelper::OPERATION_MODE_UPDATE)
{
$locationInfo=LocationInfo::model()->findByPk($model->location_id);
}
$locationInfo->short_name = $model->short_name;
$locationInfo->town_name = $model->town_name;
$locationInfo->province_name = $model->province_name;
$locationInfo->save();
if ($model->operation_mode === AdminGeneralHelper::OPERATION_MODE_CREATION)
$_message = 'Create operation completed.';
if ($model->operation_mode === AdminGeneralHelper::OPERATION_MODE_UPDATE)
$_message = 'Update operation completed.';
if ($locationInfo->hasErrors())
{
$errors = '';
foreach ($locationInfo->getErrors() as $e) $errors .= implode($e).'<br>';
echo CJSON::encode(array(
'status'=>'failure',
'messages'=>$errors
));
}
echo CJSON::encode(array(
'status' => 'success',
'messages' => $_message,
));
}
exit;
}
}
else
{
echo "FALSE";
}
Yii::app()->end();
}
Below is the scenario:
I open the dialog for Adding a location. (Parameters are short_name, town, and province)
Location was Successfully added in the Grid View and DB.
I open the dialog for filter. It can only filter by Province.
When I take a look at the Dropdown lists, Location that was successfully added is not on the lists.
My question is how to update the dropdown lists of filter dialog after I successfully added a location from Add/Edit Dialog. Alternative solution is I need to refresh the browser then open the filter dialog. But it is not that user friendly. Its really a bug.

update or replace requires the response for the query to be html (see the source for CHtml::ajax() for more detail). Your query returns json. You have several options:
You can change the controller to return all the options for the dropdown as html and continue using update.
You can change the controller to return the full dropdown as html and use replace instead of update.
You can change controller to return the id and value of the newly added location and use a custom javascript function to add this option to the dropdown.

I tried the Option No.3 and its working.
Below is the working code from my Javascript file.
function submitActionJs() {
var fareCat = document.getElementById("name").value;
var newFareCat = toTitleCase(fareCat);
$.ajax({
url: 'registerFareCategory',
type: 'POST',
datatype: 'json',
data: $('form').serializeArray(),
timeout: 10000,
beforeSend: function(){
$('#dialog-msg').html('Processing...');
},
success: function(data){
var res = eval('(' + data + ')');
$('#dialog-msg').html(res.messages);
if (res.status == 'success'){
$("#message-label").html(res.messages);
$.fn.yiiGridView.update('fare-category-grid');
$("#dialog").dialog("close");
window.parent.$('#filter_name').append('<option value = "' + newFareCat + '">' + newFareCat + '</option>');
//sort fare category dropdownlist from filter dialog
$("#filter_name").html($('#filter_name option').sort(function(x, y) {
return $(x).text().toUpperCase() < $(y).text().toUpperCase() ? -1 : 1;
}));
$("#filter_name").get(0).selectedIndex = 0;
e.preventDefault();
}
},
error: function(){
$('#dialog-msg').html('Ajax Communication Error.');
}
}
);
}
Thanks #topher for your suggestion.

Related

Yii2 submit ajax insert twice data to my table

on Yii2 Advanced My form insert twice in table, if I click twice my submit button my form insert data to my table twice it's like I clicked two time on my submit button; I'm using ajax for submit my form; my form in view is
<script type="text/javascript">
$(document).ready(function (e) {
$("#upload-gallery").on('submit',(function(e) {
$form = $(this);
e.preventDefault();
$.ajax({
url: $form.attr('action'),
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
document.getElementById("upload-gallery").reset();
$.pjax.reload({container: '#some_pjax_id', async: false});
},
error: function(){}
});
}));
});
</script>
<div class="post-gallery-form">
<?php $form = ActiveForm::begin(['id' => 'upload-gallery', 'options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model_PstGlr, 'PGalleryFile[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
<?= $form->field($model_PstGlr, 'post_text')->textarea(['rows' => 2]) ?>
<?= $form->field($model_PstGlr, 'permission_id')->dropdownList($model_Permission->PermissionOn()) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
and my controller is
public function actionView($chn)
{
$model_Permission = new Permission;
$model_PstGlr = new PostGallery; $acc_PstGlr = new AxPostGallery;
if ($model_PstGlr->load(Yii::$app->request->post()) )
{
$acc_PstGlr->CreateGallery($model_PstGlr, $chn);
}
return $this->render('view', [
'model' => $this->findModel($chn),
'model_Permission' => $model_Permission,
'model_PstGlr' => $model_PstGlr,
]);
}
The upload gallery function is to upload images on my contents
--
public function CreateGallery ($MPGALLERY, $CHNID)
{
$PSTID = Yii::$app->params['PSTID'];
$USRID = Yii::$app->user->id;
$MPGALLERY->post_id = $PSTID;
$MPGALLERY->user_id = $USRID;
$MPGALLERY->channel_id = $CHNID;
$ly_lgIMGFolder = 'upload/gal/'. $CHNID . '/' . $PSTID . '/' .date('YzHis');
$GLRID = Yii::$app->params['GLRID'];
$MPGALLERY->PGalleryFile = UploadedFile::getInstances($MPGALLERY, 'PGalleryFile');
if( $MPGALLERY->save() )
{
mkdir($ly_lgIMGFolder, 0777, true);
foreach ($MPGALLERY->PGalleryFile as $GImage)
{
$MGALLERY = new Gallery;
$MGALLERY->post_id = $PSTID;
$GImage->saveAs($ly_lgIMGFolder ."/". $GLRID . '.' . $GImage->extension);
$MGALLERY->gallery_lgimage = $ly_lgIMGFolder ."/". $GLRID . '.' . $GImage->extension;
$MGALLERY->save(false);
}
}
}
Appatently, there are a few changes that you may need to make in your code.
For example, create the following function in your controller, and remove the code from your view.
public function actionSave(){
//This part is removed from the actionView, so that the request only saves and does nothing else;
//You can return it back if you test and see that it works
$model_PstGlr = new PostGallery; $acc_PstGlr = new AxPostGallery;
if ($model_PstGlr->load(Yii::$app->request->post()) )
{
$acc_PstGlr->CreateGallery($model_PstGlr, $chn);
}
}
Then on the view, modify your form initialization as follows
The reason for adding the forwad slash is to prevent apache from sending the request to a new URL that ends with the '/';
<?php $form = ActiveForm::begin(['action'=> 'id' => 'upload-gallery', 'options' => ['enctype' => 'multipart/form-data']]) ?>
I hope this one now helps;

update yii listview onchange of dropdown

I want to change pagesize of listview using dropdown. please help me to find solution.
I have read many article but not able to do this. can u find where I'm making mistake
I'm using following code.
code for index.php (view)
code for dropdownlist
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::dropDownList('CategoryMst_pagesize','20',
array('10'=>'10','20'=>'20','50'=>'50','100'=>'100'
),
array('class'=>'form-control',
/*'ajax'=>array(
'type'=>'GET',
'data'=>array('pagesize'=>'js:this.value'),
'ajaxUpdate':()
),*/
));
?>
<?php echo CHtml::endForm(); ?>
code for listview
<?php $this->widget('zii.widgets.CListView',array(
'id'=>'category_list',
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'summaryText'=>'{start} - {end} of {count} results',
));
?>
<?php
Yii::app()->clientScript->registerScript('category_update',
"$('#CategoryMst_pagesize').change(function(){
$.fn.yiiListView.update('category_list', {
data: $(this).serialize(),
}
);
});
return false;",
CClientScript::POS_READY);
?>
code in cotroller
public function actionIndex($pagesize=20)
{
$dataProvider=new CActiveDataProvider('CategoryMst',array(
'criteria'=>array(
),
'pagination'=>array(
'pageSize'=>$pagesize,
),
));
$this->render('index',array('dataProvider'=>$dataProvider));
}
You really should not be using $('#CategoryMst_pagesize').change use https://api.jquery.com/on/ instead.
Then from what I see you are not remembering the page size anywhere, after you change it 1 time, as soon as you go to another page it will revert back to what you had before. THis is how I do it:
1) First use something to remember the page size, because right now you do not. I personally recommend this one http://www.yiiframework.com/extension/esaverelatedbehavior/ as it is really, really, really good. It also remember your filters (priceless).
2) create a function for your controller that will just save the page size.
/**
* Saves the new page size for this particular model
*/
public function actionPageSize($pagesize)
{
\Yii::app()->user->setState($this->modelName() . '_pagesize', $pagesize);
}
3) create the dropdown for the pagesize, I use Select 2 but you can use a normal dropdown. same Idea
<?php $this->widget('MySelect2', array(
'name' => 'pageSize',
'data'=>array('10' => '10', '25' => '25', '50' => '50', '100' => '100'),
'options'=>array('allowClear' => false, 'minimumResultsForSearch' => 30),
'htmlOptions' => array(
'data-ajax-dropdown' => $this->createUrl('pageSize'),
'style' => 'width: 80px',
'options'=>array(
(Yii::app()->user->getState($this->modelName() . '_pagesize', Yii::app()->params['defaultPageSize']))=>array('selected'=>'selected')
))));?>
4) I autosubmit the dropdowns for the page size like you do, but I submit them to the function above not to the index page
/*==========================
AUTOSUBMIT DROPDOWNS FOR THE PAGE SIZE
==========================*/
$('#pageSize').live('change',function(e){
var element = $(this);
jQuery.ajax({
"type": "GET",
"url": $(this).attr("data-ajax-dropdown"),
"cache": false,
"data":{pagesize: $(this).val()}
})
.success(function ( response ) {
$.fn.yiiGridView.update(element.closest('.widget.table').find('div.grid-view').attr('id'));
$.jGrowl("Pagination changed", { life: 2000 });
});
});
PS: I know I should not use .live
5) In the search for the model just like you do I have
return new \CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>$this->getTableAlias(false,false) . '.name asc',
),
'pagination'=>array(
'pageSize'=> \Yii::app()->user->getState(get_class($this) . '_pagesize', \Yii::app()->params['defaultPageSize']),
),
));

How to Update textfield onchange of dropdownlist without refresh page in Yii?

I have a Yii dropdownlist and text field, when i select the dropdown list item, this name should be displayed in textfield. I tried this concept using ajax with But it updates after page refresh only.I have pasted my code here, please look-through and suggest me how to set
textfield after every immediate selection of drop down listed item.
The following code resides protected/views/form
<td>
<?php echo $form->labelEx( ScriptQuestion::model(),'Field'); ?></td><td>
<?php echo CHtml::activedropDownList( ScriptQuestion::model(),'crm_base_contact_form_field_id',$select_field,
array(
'id' => 'send_bcfield',
'class' => 'col_165',
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('DisplayMessage'),
'update' => '#question_editor',
'data' => array('bcfield' => 'js:this.value'),
'success'=> 'function(data) {$("#question_editor").empty();
$("#question_editor").val(data);
} ',
))
); ?>
</td>
<td>
<?php echo $form->textArea($model, 'message', array('id'=>'question_editor','maxlength'=>508, )); ?>
</td>
This is controller action:
public function actionDisplayMessage(){
$q = $_POST['bcfield'];
$model=ScriptQuestion::model()->findAll();
$sql = "SELECT name FROM crm_field WHERE crm_field_id=". $q ;
$command = Yii::app()->db->createCommand($sql);
$result= $command->queryScalar();
echo "%".$result."%";
$this->performAjaxValidation($model);
}
No need to Ajax, it's just a simple javascript/jQuery .
Just do this ( replace editor1 with your ckeditor instance name) :
<script>
$("#send_bcfield").change(function(){
var selected = $("#send_bcfield option:selected").val();
CKEDITOR.instances.editor1.setData(selected);
});
</script>
Or change your code to this :
<?php
echo CHtml::activedropDownList(ScriptQuestion::model(), 'crm_base_contact_form_field_id', $select_field, array(
'id' => 'send_bcfield',
'class' => 'col_165',
'onchange' => '$("#send_bcfield").change(function(){
var selected = $("#send_bcfield option:selected").val();
CKEDITOR.instances.editor1.setData(selected);
});',
)
);
?>
Update : I changed my code to changing a ckeditor value according to your comment below my answer.
probably you simply need to add this to CHtml::activedropDownList settings:
'onchange' => "$('question_editor').val($('#send_bcfield option:selected').text())"

Facing Issues With Ajax Update On Page Load

I'm having troubles getting content displayed on page load using ajax. The ajax is calling the right action in the respective controller. The first part of the action code where i update the database is working fine. But the part where i'm calling renderPartial is not working.
**EDIT***
Ok here is the controller action ::
public function actionUpdateProductData() {
Yii::import('application.components.DataScraper.*');
require_once('GetProductData.php');
$productRealTime = RealTime::model()->findAll();
if (count($productRealTime) === 0) {
$symbolData = new GetProductData();
$symbolData->getAmazonProductData();
} else {
echo CJSON::encode( array(
'status' => 'OK',
'div' => $this->renderPartial('_productDataGrid', array(
'model' => $productRealTime),
true, true ),
));
}
}
The if part is working fine. But the else portion is not working.
Here is the view index.php::
<?php
/*
* Include the ajax Stock update script
*
*/
$baseUrl = Yii::app()->baseUrl;
$cs = Yii::app()->getClientScript();
$cs->registerScriptFile($baseUrl . '/js/ajaxProductDataUpdate.js');
?>
<div>
<hr>
<ul class="breadcrumb">
<li>
Home <span class="divider">/</span>
</li>
<li>
Product Info
</li>
</ul>
<hr>
</div>
<div class="span-10">
<div id="section2">
</div>
</div>
Here is the partial view file _productDataGrid.php
<?php
$this->widget('bootstrap.widgets.TbGridView', array(
'id' => 'real-time-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
'id',
'name',
'category',
'price'
'rating'
array(
'class' => 'bootstrap.widgets.TbButtonColumn',
),
),
));
?>
And here is the jQuery file which is making the ajax request
var productParameters = {
ajaxUpdate: function() {
$.ajax({
url: "/ProductAnalysis/index.php/realTime/updateProductData",
type: "GET",
dataType:"json",
error: function(xhr, tStatus, e) {
if (!xhr) {
alert(" We have an error ");
alert(tStatus + " " + e.message);
} else {
alert("else: " + e.message); // the great unknown
}
},
success: function(data) {
$.fn.yiiGridView.update('real-time-grid', {
data: $(this).serialize()
});
}
});
}
};
$(document).ready(function() {
productParameters.ajaxUpdate();
});
Upon loading the page /realTime/index.php i'm getting an error which says
else:
undefined
Obviously the ajax call is failing, but i don't know how will i fix it. Also in Firebug, the echo date() function in the controller is working, but the Gridview is not working.
Please provide some help on how to solve this. Let me know where i'm doing wrong. I can't seem to make any headway around this.
Thanks in advance,
Maxx
Your actionUpdateStockData() is echoing the date before the actual JSON content is encoded. As a result you're not transmitting correct JSON, and XHR will fail.
Remove the echo date ... line and you should be fine. And as you're just at it - you should add some response for the case where count(RealTime::model()->findAll()) === 0.
Well it seems that the gridview widget won't work with findall(). So i changed the dataprovider to simple model and it works now.
Here is the working code ::
public function actionUpdateStockData() {
Yii::import('application.components.DataScraper.*');
require_once('GetStockData.php');
$productRealTime = new RealTime();
if (count($productRealTime->model()->findAll()) === 0) {
$symbolData = new GetproductData();
$symbolData->getAmazonProductData();
} else {
echo CJSON::encode( array(
'status' => 'success',
'div' => $this->renderPartial('_productDataGrid', array(
'model' => $productRealTime),
true, true ),
));
}
}

Passing parameter from controller to view in code igniter

I am new in code Igniter so I don't know how to do it. So what my problem is I have a form which I am submitting from ajax. So what I want to do is as the form submit successfully then a notification or a css div class will appear above the form and then disappear it.I don't know how can I perform this as after accepting the parameter from view page to controller I don't know how to send the parameter controller to view or how can I perform all this .Here is my controller:
class categoryController extends CI_Controller {
function index(){
$data['main_content'] = 'categoryView';
$this->load->view('dashboardTemplate/template',$data);
}
function addCategory(){
//getting parameters from view
$data = array(
'cat_name' => $this->input->post('cat_name')
);
$is_ajax = $this->input->post('ajax'); //or use this line
$this->load->model('categoryModel');
$query = $this->categoryModel->addCategories($data);
if ($query && $is_ajax){
$page['main_content'] = 'categoryView';
$page['v'] = '1'; // i dont know how this variable is not accessing in view page by echo $v
$this->load->view('dashboardTemplate/template',$page);
}
else
{
//
}
}}
Here is my view:
<?php
$attributes = array('id' => 'form-horizontal',
'class' => 'form-horizontal'
);
echo form_open('categoryController/addCategory', $attributes);
$cat_name = array(
'name' => 'cat_name',
'id' => 'cat_name',
'class' => 'cat_name');
$button = array(
'name' => 'button',
'id' => 'btn',
'class' => 'btn btn-primary',
'value' => 'submit',
'type' => 'submit',
'content' => 'Submit'
);
?>
<h3>Add Category</h3>
//here i want to do this .. that if form is submitted succesfully then this class will load only and the whole page remain the same
<div> class="alert-heading">sucess or not success!<div>
</div>
<div class="control-group">
<label for="basicround" class="control-label">Category Name:</label>
<div class="controls">
<?php echo form_input($cat_name); ?>
<div class="form-actions">
<?php echo form_button($button); ?></div>
<script type="text/javascript">
$('#btn').click(function() {
var cat_name = $('#cat_name').val();
if (!cat_name || cat_name == 'Name') {
alert('Please enter Category Name');
return false;
}
var form_data = {
cat_name: $('#cat_name').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('categoryController/addCategory'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
$('#message').html(msg);
}
});
return false;
});
</script>
Since it is an Ajax submit, So you need to pass JSON array from controller to view
echo json_encode($page);
Controller
$page['main_content'] = 'categoryView';
$page['v'] = '1'; // i dont know how this variable is not accessing in view page by echo $v
echo json_encode($page);
For the above step, you need to define
data-type:JSON
in your ajax function.
Ajax Function
$.ajax({
url: "<?php echo site_url('categoryController/addCategory'); ?>",
type: 'POST',
data: form_data,
data-type: "json",
success: function(msg) {
// Here you can access the values from controller like msg.v
$('#message').html(msg);
}
});
Based on the response, you can show the success message using
$(".alert-heading").show();

Categories