I have theese three acf_form. I want to show these form one by one as well as I want to save every form on button click through ajax without page refresh. Right now it's refreshing page whenever I update.
I will show through display none & block using js.
<div class="SetupNew">
<h2>Setup Deals To Attract New Clientele</h2>
<p>Example: buy $15 get $30 for services</p>
<p id="newDealsTxt">[Click Here To Setup] </p></div>
<?php acf_form($args = array(
'post_id' => $post_id,
'field_groups' => array(2029),
'form_attributes' => array(
'id'=>'newDeals'
),
)); ?>
<div class="SetupEx">
<h2>Setup Deals To Bring In Clientele During Nonpeak Hours</h2>
<p>Example: buy $15 get $30 for services Tue-Thur 9am - 2pm.</p>
<p id="exDealsTxt">[Click Here To Setup]</p></div>
<?php acf_form($args = array(
'post_id' => $post_id,
'field_groups' => array(2047),
'form_attributes' => array(
'id'=>'exDeals'
),
)); ?>
<div class="SetupFb">
<h2>Setup $5 Off Coupon To Increase Testimonials And Sharing</h2>
<p>Example: Leave a testimonial and get $5 off your next service.</p>
<p id="fbDealsTxt">[Click Here To Setup] </p></div>
<?php acf_form($args = array(
'post_id' => $post_id,
'field_groups' => array(2123),
'form_attributes' => array(
'id'=>'fbDeals'
),
)); ?>
<h2 id="backk">Back << </h2>
This comes pretty late, but I had the same problem today. For reference, here's my javascript:
// call this function on document ready or when your ajax page is loaded
function renderPage() {
// initialize the acf script
acf.do_action('ready', $('body'));
// will be used to check if a form submit is for validation or for saving
let isValidating = false;
acf.add_action('validation_begin', () => {
isValidating = true;
});
acf.add_action('submit', ($form) => {
isValidating = false;
});
$('.acf-form').on('submit', (e) => {
let $form = $(e.target);
e.preventDefault();
// if we are not validating, save the form data with our custom code.
if( !isValidating ) {
// lock the form
acf.validation.toggle( $form, 'lock' );
$.ajax({
url: window.location.href,
method: 'post',
data: $form.serialize(),
success: () => {
// unlock the form
acf.validation.toggle( $form, 'unlock' );
}
});
}
});
}
Related
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.
I use the following select2 Yii widget in my view to populate a drop-down list. Since the data necessary for the preparation of the select list consists of more than 2K records I use select2 with minimumInputLength parameter and an ajax query to generate partial result of the list based on user input. If I create a new record I have no problem at all. It populates everything fine and I can save data to my database. However I don't know how to load saved data back to this drop-down during my update action. I read somewhere that initselection intended for this purpose but I couldn't figure out how to use it.
Can someone help me out on this?
My view:
$this->widget('ext.select2.ESelect2', array(
'selector' => '#EtelOsszerendeles_osszetevo_id',
'options' => array(
'allowClear'=>true,
'placeholder'=>'Kérem válasszon összetevőt!',
'minimumInputLength' => 3,
'ajax' => array(
'url' => Yii::app()->createUrl('etelOsszerendeles/filterOsszetevo'),
'dataType' => 'json',
'quietMillis'=> 100,
'data' => 'js: function(text,page) {
return {
q: text,
page_limit: 10,
page: page,
};
}',
'results'=>'js:function(data,page) { var more = (page * 10) < data.total; return {results: data, more:more }; }',
),
),
));?>
My controller's action filter:
public function actionFilterOsszetevo()
{
$list = EtelOsszetevo::model()->findAll('nev like :osszetevo_neve',array(':osszetevo_neve'=>"%".$_GET['q']."%"));
$result = array();
foreach ($list as $item){
$result[] = array(
'id'=>$item->id,
'text'=>$item->nev,
);
}
echo CJSON::encode($result);
}
I use initSelection to load existing record for update in this way (I replaced some of your view code with ... to focus in main changes). Tested with Yii 1.1.14. Essentially, I use two different ajax calls:
View:
<?php
$this->widget('ext.select2.ESelect2', array(
'selector' => '#EtelOsszerendeles_osszetevo_id',
'options' => array(
...
...
'ajax' => array(
'url' => Yii::app()->createUrl('client/searchByQuery'),
...
...
'data' => 'js: function(text,page) {
return {
q: text,
...
};
}',
...
),
'initSelection'=>'js:function(element,callback) {
var id=$(element).val(); // read #selector value
if ( id !== "" ) {
$.ajax("'.Yii::app()->createUrl('client/searchById').'", {
data: { id: id },
dataType: "json"
}).done(function(data,textStatus, jqXHR) { callback(data[0]); });
}
}',
),
));
?>
Now in your controller you should receive parameters for ajax processing: query (q), as string, when inserting; id (id) as int when updating. Parameter names must be same as ajax data parameters (in this sample insert q; in update id) when read in $_GET. Code is not refactored/optimized:
Controller:
public function actionSearchByQuery(){
$data = Client::model()->searchByQuery( (string)$_GET['q'] );
$result = array();
foreach($data as $item):
$result[] = array(
'id' => $item->id,
'text' => $item->name,
);
endforeach;
header('Content-type: application/json');
echo CJSON::encode( $result );
Yii::app()->end();
}
public function actionSearchById(){
$data = Client::model()->findByPk( (int) $_GET['id'] );
$result = array();
foreach($data as $item):
$result[] = array(
'id' => $item->id,
'text' => $item->name,
);
endforeach;
header('Content-type: application/json');
echo CJSON::encode( $result );
Yii::app()->end();
}
Model - custom query and a little of order / security / clean :)
public function searchByQuery( $query='' ) {
$criteria = new CDbCriteria;
$criteria->select = 'id, ssn, full_name';
$criteria->condition = "ssn LIKE :ssn OR full_name LIKE :full_name";
$criteria->params = array (
':ssn' => '%'. $query .'%',
':full_name' => '%'. $query .'%',
);
$criteria->limit = 10;
return $this->findAll( $criteria );
}
EDIT:
It works out of box when update is preloaded with traditional HTTP Post (synchronous, for example with Yii generated forms). For async/Ajax updates, for example with JQuery:
Event / Trigger:
$('#button').on("click", function(e) {
...
... your update logic, ajax request, read values, etc
...
$('#select2_element').select2('val', id_to_load );
});
With this, initSelection will run again in async way with new id_to_load value, reloading record by id.
In your case and for your needs, initSelection could be complete different to avoid load record from db or you can use formatResult and formatSelection custom functions (are described in Load Remote Data sample source code). Reading documentation, I understand that initSelection's callback need JSON data with id and text elements to load properly or you could try to combine both concepts (this initSelection with your custom JS event/trigger call) (not tested):
'initSelection'=>'js:function(element,callback) {
// here your code to load and build your values,
// this is very basic sample
var id='myId';
var text='myValue';
data = {
"id": id,
"text": text
}
callback(data);
}',
Or directly on Trigger call:
$('#button').on("click", function(e) {
...
... ...
$("#select2_element").select2("data", {id: "myId", text: "MyVal"});
});
Hope that helps.
I tried doing that way, but couldn't do it
the solution I came up to get my record filled and selected was:
In case of the attribute having some data(in update mode or default value), I wrote some javascript that after document ready event, would fill the select with my data (just selected it ind pushed html in it), and made it selected, and then I rest( or update) the select to show my work.
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']),
),
));
I am trying to append text to CJuiDialog widget in Js code, In CJuiDialog content i have two buttons ,
Dialog Widget code,
<?php
$this->beginWidget('zii.Widgets.jui.CJuiDialog',array(
'id'=>'update_tasks',
'options'=>array(
'title'=>'Create Tasks',
'autoOpen'=>false,
'modal'=>false,
'width'=>500,
'height'=>300,
),
));
?>
<table cellspacing="20">
<tr>
<td><?php echo CHtml::button('Add to Current Pending Tasks',array('id'=>'AddPendingTasks'));?></td><td style = "width : 20px"></td>
<td><?php echo CHtml::button('Add to Tasks',array('id'=>'AddTasks'));?></td>
</tr>
</table>
<?php $this->endWidget();?>
Am opening this dialog inside JS code on another button action,
$('.updatetask_btn').click(function(){
var filterid = $(this).closest('tr').find('select')[0].options[$(this).closest('tr').find('select')[0].selectedIndex].value;
var filtername = $(this).closest('tr').find('select')[0].options[$(this).closest('tr').find('select')[0].selectedIndex].text;
document.getElementById('filter-id').value = filterid;
var div = document.getElementById('update_tasks');
div.innerHTML = '<label><b>'+$('#camp-name').val()+' - '+filtername+'</b></label><br>'+div.innerHTML ;
//----- Here am appending text to the dialog dynamically ---
$('#update_tasks').dialog('open');
});
Appending text blocks the two button actions in CjuiDialog content . both button onclick action not working when i append text here. Please give me any idea.
Actually I didn't fully understood your needs but I always do this way:
You need to understand and adapt to your needs.
In main view
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
Yii::app()->clientScript->scriptMap['jquery.min.js'] = false;
Yii::app()->clientScript->scriptMap['jquery-ui.js'] = false;
Yii::app()->clientScript->scriptMap['jquery-ui.min.js'] = false;
....
$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
'id'=>'addot-dialog',
'options'=>array(
'title' => 'Aggiungi OT',
'autoOpen' => false,
'width' => 600,
'height' => 'auto',
'closeOnEscape' => true,
// 'close' => 'js:function() { $("table.items").find("tbody tr div.log-active").removeClass("log-active").addClass("log-inactive"); }'
)
));
$this->endWidget('zii.widgets.jui.CJuiDialog');
?>
.....
$loadurlvendita = Yii::app()->createUrl("/otpos/otVendita/",
array("idot" => $this->idot, "codfis" => $this->codfis));
....
on click here I open and fill let dialog with .load() from another view with render partial
CHtml::link('','',
array('class'=>'be-icon vendita','style'=>'display:block;float:right;padding-right:6px;',
'onClick'=>'$("#venditaot-'.$this->idot.'").dialog("open").load(\''.$loadurlvendita.'\');'
)).
controller
public function actionOtVendita($idot, $codfis) {
$proprietari = Otpos::model()->getOtposProprietari($idot);
$this->renderPartial('vendita', array('idot' => $idot, 'codfis' => $codfis, 'proprietari' => $proprietari), false, true);
}
I hoe it'll help in some way other wise clear better your needs.
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 ),
));
}
}