I would like to move the jQuery code to a separate file like you can see in the second code but if I do this the functionality of the code does not display on the page. The first code works properly and the second code does not work?
I turned off the caching plugin and still nothing.
There are other modules in this custom-woocommerce.js file and those work fine only code from this example shows some problems.
First Code
add_action('woocommerce_review_order_before_submit', 'cart_privacy_policy_checkbox', 5);
function cart_privacy_policy_checkbox()
{
woocommerce_form_field('privacy_policy', array(
'type' => 'checkbox',
'class' => array('form-row privacy'),
'label_class' => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
'input_class' => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
'required' => true,
'label' => sprintf(
__('<span class="woocommerce-terms-and-conditions-checkbox-text">Przeczytałem/am i akceptuję <strong>Regulamin</strong></span>'),
),
));
if (is_checkout()) {
wp_enqueue_script('sweetalert2', 'https://cdn.jsdelivr.net/npm/sweetalert2#11.6.15/dist/sweetalert2.all.min.js', array(), '11.6.15', false);
wp_enqueue_script('promise-polyfill', 'https://cdnjs.cloudflare.com/ajax/libs/promise-polyfill/8.2.3/polyfill.min.js', array(), '8.2.3', false);
?>
<script type="text/javascript">
jQuery(function($) {
var a = '#place_order',
b = '#privacy_policy',
c = '<?php echo wc_get_checkout_url(); ?>',
d = 'disabled';
// Set disable button state
$(a).addClass(d).prop('href', '#');
// On button click event
$('body').on('click', a, function(e) {
if (!$(b).prop('checked')) {
// Disable "Proceed to checkout" button
e.preventDefault();
// disabling button state
if (!$(a).hasClass(d)) {
$(a).addClass(d).prop('href', '#');
}
// Sweet alert 2
Swal.fire({
background: '#fff',
toast: false,
width: 'auto',
icon: 'error',
position: 'center',
title: 'Wystąpił błąd',
html: '<strong>Zaakceptowanie regulaminu jest wymagane,</strong> ' +
'aby kontynuować składanie zamówienia',
// text: ' ',
timer: 5000,
timerProgressBar: true,
showConfirmButton: false
});
}
});
// On checkbox change event
$(b).change(function() {
if ($(this).prop('checked')) {
if ($(a).hasClass(d)) {
$(a).removeClass(d).prop('href', c);
}
} else {
if (!$(a).hasClass(d)) {
$(a).addClass(d).prop('href', '#');
}
}
});
$('#privacy_policy').click(function() {
if ($(this).is(":checked")) {
$('.custom-download-info').fadeIn('300');
} else {
$('.custom-download-info').fadeOut('300');
}
})
});
</script>
<?php
}
}
Second code
add_action('woocommerce_review_order_before_submit', 'cart_privacy_policy_checkbox', 5);
function cart_privacy_policy_checkbox()
{
woocommerce_form_field('privacy_policy', array(
'type' => 'checkbox',
'class' => array('form-row privacy'),
'label_class' => array('woocommerce-form__label woocommerce-form__label-for-checkbox checkbox'),
'input_class' => array('woocommerce-form__input woocommerce-form__input-checkbox input-checkbox'),
'required' => true,
'label' => sprintf(
__('<span class="woocommerce-terms-and-conditions-checkbox-text">Przeczytałem/am i akceptuję <strong>Regulamin</strong></span>'),
),
));
if (is_checkout()) {
wp_enqueue_script('sweetalert2', 'https://cdn.jsdelivr.net/npm/sweetalert2#11.6.15/dist/sweetalert2.all.min.js', array(), '11.6.15', false);
wp_enqueue_script('promise-polyfill', 'https://cdnjs.cloudflare.com/ajax/libs/promise-polyfill/8.2.3/polyfill.min.js', array(), '8.2.3', false);
wp_enqueue_script('custom-woocommerce', '/path/to/custom-woocommerce.js', array(), '1.0.0.' . time(), false);
}
}
Related
I am having a problem with building JSON in PHP, as a response on Ajax call for populating dynamically datasets for ChartsJs.
In PHP I have an return of Ajax call that works for 1 ChartJs Dataset:
<?php
$returnData['line'] = array(
'type' => 'line',
'title' => $title,
'labels' => array('Jan','Feb','March','April','Mai'),
'datasets' => array(
array(
'data' => array(10,20,15,45,21),
'borderColor' => "#f7464a",
'label' => "Label 1",
'fill' => false
)
)
);
echo json_encode($returnData);
?>
JavaScript that builds the Chart:
$.ajax({
url: "div.php",
type: "POST",
dataType: 'json',
success: function(rtnData) {
$.each(rtnData, function(dataType, data) {
var ctx = document.getElementById("myChart").getContext("2d");
var config = {
type: data.type,
data: {
datasets: data.datasets,
labels: data.labels
},
options: {
responsive: true,
title: {
display: true,
text: data.title
},
legend: {
display: true,
position: 'right',
labels: {
fontColor: '#333'
}
}
}
};
window.myPie = new Chart(ctx, config);
});
},
error: function(rtnData) {
alert('error' + rtnData);
}
});
Now my question, when I have Data for 5 or more Datasets:
//Data
$title = "MyTitle";
$labels= array('Jan','Feb','March','April','Mai');
//Datasets
$linelabels= array('Line1','Line2','Line3','Line4','Line5');
$mydata1 = array(10,20,15,45,21);
$mydata2 = array(21,45,15,20,10);
$mydata3 = array(10,20,15,45,21);
$mydata4 = array(21,45,15,20,10);
$mydata5 = array(10,20,15,45,21);
$colors = array("#f7464a","#8e5ea2","#f7464a","#8e5ea2","#f7464a");
How can I build those Datasets dynamically in the JSON response? For example:
'datasets' => array(
for(i=0:i<5;i++)
{
array(
'data' => array($mydata1[i]),
'borderColor' => $colors[i],
'label' => $linelabels[i],
'fill' => false
),
}
)
SOLVED. To create dynamically Json for Ajax response for Charts, maybe can help someone out:
$returnData2['line'] = array(
'type' => 'line',
'title' => 'my Title',
'labels' => array('Jan','Feb','March','April','Mai'),
'datasets' => array(
array(
'data' => array(10,20,15,45,21),
'borderColor' => "#f7464a",
'label' => "Label 1",
'fill' => false
),
array(
'data' => array(21,45,15,20,10),
'borderColor' => "#8e5ea2",
'label' => 'Line2',
'fill' => false
),
array
(
'data' => array(10,20,15,45,21),
'borderColor' => "#f7464a",
'label' => 'Line3',
'fill' => false
),
array
(
'data' => array(21,45,15,20,10),
'borderColor' => "#8e5ea2",
'label' => 'Line4',
'fill' => false
),
array(
'data' => array(10,20,15,45,21),
'borderColor' => "#f7464a",
'label' => 'Line5',
'fill' => false
)
)
);
echo json_encode($returnData2);
I used this construct, I admit it is not the finest way, but it works. :)
$title = "MyTitle";
$labels= array('Jan','Feb','March','April','Mai');
$linelabels= array('Line1','Line2','Line3','Line4','Line5');
$mydata1 = array(10,20,15,45,21);
$mydata2 = array(21,45,15,20,10);
$mydata3 = array(35,24,20,18,11);
$mydata4 = array(18,5,34,17,42);
$mydata5 = array(23,17,34,12,45);
$colors = array("#E74C3C","#76448A","#148F77","#D4AC0D","#1ABC9C");
$returnData = new stdClass();
$returnData->line = new stdClass();
$returnData->line->type = 'line';
$returnData->line->title = 'my Title';
$returnData->line->labels = $labels;
$returnData->line->datasets = new stdClass();
$dataset = array();
for($i=0;$i<5;$i++)
{
$mydata = array();
if($i==0)
$mydata = $mydata1;
else if($i==1)
$mydata = $mydata2;
else if($i==2)
$mydata = $mydata3;
else if($i==3)
$mydata = $mydata4;
else if($i==4)
$mydata = $mydata5;
$datasets = new stdClass();
$datasets->data = $mydata;
$datasets->borderColor = $colors[$i];
$datasets->label = $linelabels[$i];
$datasets->fill = false;
$dataset[] = $datasets;
}
$returnData->line->datasets = $dataset;
echo json_encode($returnData);
Ajax response for bulding Charts:
$.ajax({
url: "div.php",
type: "POST",
dataType: 'json',
success: function(rtnData) {
$.each(rtnData, function(dataType, data) {
var ctx = document.getElementById("myChart").getContext("2d");
var config = {
type: data.type,
data: {
datasets: data.datasets,
labels: data.labels
},
options: {
responsive: true,
title: {
display: true,
text: data.title
},
legend: {
display: true,
position: 'right',
labels: {
fontColor: '#333'
}
}
}
};
window.myPie = new Chart(ctx, config);
});
},
error: function(rtnData) {
alert('error' + rtnData);
}
});
And the result in Canvas:
enter image description here
I want to display more than 1 information when searching, so I use select2 ajax & templates. It use json. I change the url and I make function on my controller. But I have a problem. It can not show anything. What's the problem? This is my code:
view
$formatJs = <<< 'JS'
var formatProduct = function (product) {
if (product.loading) {
return product.text;
}
var markup =
'<div class="row">' +
'<div class="col-sm-5">' +
'<b style="margin-left:5px">' + product.name + '</b>' +
'</div>' +
'<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + product.ean_no + '</div>' +
'<div class="col-sm-3"><i class="fa fa-star"></i> ' + product.desc + '</div>' +
'</div>';
return '<div style="overflow:hidden;">' + markup + '</div>';
};
var formatProductSelection = function (product) {
return product.name || product.text;
}
JS;
// Register the formatting script
$this->registerJs($formatJs, \yii\web\View::POS_HEAD);
// script to parse the results into the format expected by Select2
$resultsJs = <<< JS
function (data, params) {
params.page = params.page || 1;
return {
// Change `data.items` to `data.results`.
// `results` is the key that you have been selected on
// `actionJsonlist`.
results: data.results
};
}
JS;
Select2
echo Select2::widget([
'name' => 'kv-repo-template',
'value' => '14719648',
'initValueText' => 'kartik-v/yii2-widgets',
'options' => ['placeholder' => 'Search for a repo ...'],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 1,
'ajax' => [
'url' => Url::to(['/bom/product/productlist']),
'dataType' => 'json',
'delay' => 250,
'data' => new JsExpression('function(params) { return {q:params.term, page: params.page}; }'),
'processResults' => new JsExpression($resultsJs),
'cache' => true
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('formatProduct'),
'templateSelection' => new JsExpression('formatProductSelection'),
],
]);
controller
public function actionProductlist($search = NULL, $code = NULL)
{
header('Content-type: application/json');
$clean['more'] = false;
$query = new \yii\db\Query;
if(!is_Null($search))
{
$mainQuery = $query->select('code, name, description, volume')
->from('product');
$command = $mainQuery->createCommand();
$rows = $command->queryAll();
$clean['results'] = array_values($rows);
}
else
{
if(!is_null($code))
{
$clean['results'] = ['ean_no'=> $code, 'name' => Product::find($code)->nama,
'description' => Product::find($code)->description, 'volume' => Product::find($code)->volume];
}else
{
$clean['results'] = ['ean_no' => 123, 'name' => 'None found', 'description' => 'None found', 'volume' => 'None found'];
}
}
echo \yii\helpers\Json::encode($clean);
exit();
}
on mozilla when i open the inspect element console. there is an error message like this :
TypeError: data.slice is not a function
S2
Try to remove
'processResults' => new JsExpression($resultsJs),
I added Woocommerce Billing Adress a fields like 'field_x" as required from child theme's function.php. And then added radio buttons with two option 'A and B' same page. I want to do that:
if user select radio option A, my custom fields will be invisible and 'not required'
if user select radio option B, my custom fields will be visible and 'required'
My sample code:
<?
// Adding fields and radios
add_filter('woocommerce_billing_fields', 'some_woocommerce_billing_fields', 10, 1);
function some_woocommerce_billing_fields($fields) {
$fields['radio_select'] = array(
'label' => __('Please select', 'woocommerce'),
'required' => true,
'clear' => false,
'type' => 'radio',
'options' => array(
'op_a' => __('op A', 'woocommerce'),
'op_b' => __('op B', 'woocommerce')));
$fields['field_x'] = array(
'label' => __('Field X', 'woocommerce'),
'placeholder' => _x('Field X', 'placeholder', 'woocommerce'),
'required' => true,
'clear' => false);
return $fields;
}
// PHP functions for Ajax calls
add_action('wp_enqueue_scripts', 'majax_enqueue_scripts');
add_action('wp_ajax_f_remove_req', 'f_remove_req');
add_action('wp_ajax_nopriv_f_remove_req', 'f_remove_req');
function majax_enqueue_scripts() {
$nonce = wp_create_nonce("nonce_t");
wp_enqueue_script('url', true);
wp_localize_script('url', 'urlm', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => $nonce));
}
// Adding filter to remove require
function f_remove_req() {
if (!wp_verify_nonce($_POST['nonce'], 'nonce_t'))
die();
add_filter('woocommerce_process_myaccount_field_field_x', 'remove_reqs', 10, 1);
die();
}
// Removing require
function remove_reqs($field) {
$field['field_x']['required'] = false;
return $field;
}
// Add Ajax function
add_action('woocommerce_after_edit_account_address_form', 'address_script');
function address_script() {
?>
< script >
jQuery(document).ready(function () {
jQuery('#radio_select_op_a').change(function () {
jQuery('#field_x_field').hide();
jQuery.post(urlm.ajax_url, {
'action' : 'f_remove_req',
'nonce' : urlm.nonce
},
function (response) {
console.log(response);
});
});
jQuery('#radio_select_op_b').change(function () {
jQuery('#field_x_field').show();
jQuery.post(urlm.ajax_url, {
'action' : 'f_add_req',
'nonce' : urlm.nonce
},
function (response) {
console.log(response);
});
});
});
</ script>
<?
}
?>
i can add fields and ajax function is working.
But when i click "Save", php always sends filed_x->require option as true.
What is wrong? How can i do this?
Thank you.
Im Using
PHP language , yii-1.1.13 framework and MySQL DB.
Views code of Main Page.
<?php
/**
* The view for the trip schedules page.
* #uses ManageTripSchedulesForm $model
* #uses VoyageServiceClassInfo $voyageServiceClassInfo
* #uses LocationInfo $locationInfo
* #uses PierInfo $pierInfo
* #uses VesselInfo $vesselInfo
* #uses ServiceClassInfo $serviceClassInfo
* #uses FareSetInfo $fareSetInfo
* #uses SearchTripsForm $searchTripsForm
* #uses FerryOperatorInfo $ferryOperatorInfo
* #uses ManageTripSchedulesFilterForm $filterForm
*/
$this->setPageTitle(SystemConstants::SITE_NAME . ' - Trip Schedules');
$baseUrl = Yii::app()->getBaseUrl();
$cs = Yii::app()->getClientScript();
// --- POS_HEAD
// a plug-in used in manageTripSchedules.js
$cs->registerScriptFile($baseUrl . '/js/jquery.blockUI.js', CClientScript::POS_HEAD);
// for this view
$cs->registerCssFile($baseUrl . '/css/manageTripSchedules.css');
$cs->registerScriptFile($baseUrl . '/js/manageTripSchedules.js', CClientScript::POS_HEAD);
$this->endWidget('zii.widgets.jui.CJuiDialog');
/**
* Maintenance Dialog widget
*/
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'dialog',
'options' => array(
'title' => 'Trip Schedules',
'autoOpen' => false,
'modal' => true,
'resizable' => false,
'width' => 600,
'dialogClass' => 'tripschedules-dialog-class',
'show'=>array(
'effect'=>'drop',
'duration'=>500,
),
'hide'=>array(
'effect'=>'drop',
'duration'=>500,
),
),
));
/**
* Render the maintenance dialog view.
*/
echo $this->renderPartial('manageTripSchedulesDialog', array(
'model' => $model,
'ferryOperatorInfo' => $ferryOperatorInfo,
'locationInfo' => $locationInfo,
'pierInfo' => $pierInfo,
'vesselInfo' => $vesselInfo,
'serviceClassInfo' => $serviceClassInfo,
'fareSetInfo' => $fareSetInfo
));
$this->endWidget('zii.widgets.jui.CJuiDialog');
<div id="grid-container" class="grid-div">
<?php
$pageSize = 10;
$helper = new TripSchedulesGridHelper($this);
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'tripschedules-grid',
'dataProvider' => $voyageServiceClassInfo->searchTripSchedules(Yii::app()->user->ferry_operator_id, $filterForm, $pageSize),
'emptyText' => 'No data found.',
'selectableRows' => 0,
'template' => '{items}{pager}', // to remove summary header
'pager' => array(
'header' => '', // to remove 'Go to page:'
),
'cssFile' => $baseUrl . '/css/manageTripSchedulesGrid.css',
'columns' => array(
array(
'name' => 'id',
'value' => '$data->voyage_service_class_id',
'headerHtmlOptions' => array('style' => 'display:none'),
'htmlOptions' => array('style' => 'display:none'),
),
'voyage.ferry_operator.name::Operator',
array(
'name' => 'Origin',
'value' => array($helper, 'formatOriginTerminal'),
),
array(
'name' => 'Destination',
'value' => array($helper, 'formatDestinationTerminal'),
),
array(
'name' => 'DepartureTime',
'header' => 'Departure',
'value' => array($helper, 'formatDepartureDate'),
),
array(
'name' => 'ArrivalTime',
'header' => 'Arrival',
'value' => array($helper, 'formatArrivalDate'),
),
array(
'name' => 'TripHrs',
'header' => 'Trip Hrs',
'value' => array($helper, 'formatTripDuration'),
),
'voyage.vessel.name::Vessel',
'service_class.name::Service Class',
'fare_set.fare_type::Fare Set',
array(
'class' => 'CButtonColumn',
'template'=>'{update}{delete1}',
'buttons'=>array(
'update' => array(
'label'=>'Edit',
'imageUrl'=>Yii::app()->baseUrl.'/images/gridview/update.png',
'url'=>'"#"',
'click'=>'function(){updateTripScheduleJs($(this).parent().parent().children(":nth-child(1)").text());}',
),
'delete1' => array(
'label'=>'Delete',
'imageUrl'=>Yii::app()->baseUrl.'/images/gridview/delete.png',
'url'=>'"#"',
'click'=>'function(){deleteTripScheduleJs($(this).parent().parent().children(":nth-child(1)").text());}',
),
),
),
),
));
?>
</div>
Views code of Add/Edit Dialog.
<?php
echo $form->dropDownList($model, 'service_class_id',
$serviceClassInfo->getAllServiceClassesForSelection2($model->ferry_operator_id,
$this->_ferryOperatorId , true, 'Select class'),
array(
'id' => 'service_class_id',
'class' => 'selectbox',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('loadFareSet'),
'update'=>'#fare_set_id',
'data'=>array('service_class_id'=>'js:this.value'),
))
);
?>
In my Controller, below is my code.
<?php
class SiteController extends Controller
{
public $_ferryOperatorId;
public function actionRetrieveTripSchedule() {
$voyageServiceClassInfo = new VoyageServiceClassInfo;
if (isset($_POST['id']))
{
if (Yii::app()->request->isAjaxRequest)
{
$voyageServiceClassInfo = VoyageServiceClassInfo::model()->with('voyage')->findByPk($_POST['id']);
if ($voyageServiceClassInfo != null)
{
$this->_ferryOperatorId = '3';
$_json = array(
array('name'=>'voyage_service_class_id', 'value'=>$voyageServiceClassInfo->voyage_service_class_id),
array('name'=>'ferry_operator_id', 'value'=>$voyageServiceClassInfo->voyage->ferry_operator_id),
array('name'=>'origin_location_id', 'value'=>$voyageServiceClassInfo->voyage->origin_location_id),
array('name'=>'origin_pier_id', 'value'=>$voyageServiceClassInfo->voyage->origin_pier_id),
array('name'=>'destination_location_id', 'value'=>$voyageServiceClassInfo->voyage->destination_location_id),
array('name'=>'destination_pier_id', 'value'=>$voyageServiceClassInfo->voyage->destination_pier_id),
array('name'=>'departure_date', 'value'=>$voyageServiceClassInfo->voyage->departure_date),
array('name'=>'departure_time', 'value'=>$voyageServiceClassInfo->voyage->departure_time),
array('name'=>'arrival_date', 'value'=>$voyageServiceClassInfo->voyage->arrival_date),
array('name'=>'arrival_time', 'value'=>$voyageServiceClassInfo->voyage->arrival_time),
array('name'=>'vessel_id', 'value'=>$voyageServiceClassInfo->voyage->vessel_id),
array('name'=>'service_class_id', 'value'=>$voyageServiceClassInfo->service_class_id),
array('name'=>'fare_set_id', 'value'=>$voyageServiceClassInfo->fare_set_id),
);
echo CJSON::encode(array(
'status'=>'success',
'messages'=>"Target data is retrieved normally.",
'val'=>$_json,
));
}
else
{
echo CJSON::encode(array(
'status'=>'failure',
'messages'=>"Target data can not be retrieved from server.",
'val'=>$_json,
));
}
}
}
}
}
Models code of Service class drop down lists.
public function getAllServiceClassesForSelection2(
$operatorId = null, $operatorIdEdit = null, $addInstructionRow = false, $instruction = null)
{
$serviceClassArray = array();
if ($addInstructionRow) {
if ($instruction == null) {
$instruction = 'Select a ServiceClass';
}
$serviceClassArray += array('' => $instruction);
}
$criteria = new CDbCriteria;
$criteria->select = 'service_class_id, name';
if ($operatorId != null || $operatorId != '')
{
$criteria->condition = 'ferry_operator_id = ' . $operatorId;
}
if ($operatorIdEdit != null || $operatorIdEdit != '' && $model->operation_mode == AdminGeneralHelper::OPERATION_MODE_UPDATE)
{
$criteria->condition = 'ferry_operator_id = ' . $operatorIdEdit;
}
$criteria->order = 'name';
$servceClassInfos = $this->findAll($criteria);
foreach ($servceClassInfos as $servceClassInfo) {
$serviceClassArray += array(
$servceClassInfo->service_class_id => $servceClassInfo->name,
);
}
return $serviceClassArray;
}
In my JS file, below is my code.
function updateTripScheduleJs(id) {
// Get target data via controller and set values to fields of dialog.
$.blockUI({
message: "Loading data...",
});
$("#dialog-msg").html(""); // clear the message area of dialog
// Ajax request
$.ajax({
url: 'retrieveTripSchedule',
type: 'POST',
datatype: 'json',
data: $.parseJSON('{"id": '+id+'}'),
timeout: 20000,
beforeSend: function(){
},
success: function(data){
$.unblockUI();
var res = eval('(' + data + ')');
if (res.status == 'success'){
for (var idx in res.val){
if (res.val[idx].name == 'departure_time' || res.val[idx].name == 'arrival_time'){
$('#'+res.val[idx].name).attr('value',formatAMPM(res.val[idx].value));
} else {
$('#'+res.val[idx].name).attr('value',res.val[idx].value);
}
}
$("#operation_mode").attr('value','U'); // Set update mode
$(".submit-button").attr('value','Update Trip Schedule'); // Set submit button label
$(".update-only-div").css('display','block'); // Show columns for update
$(".create-only-div").css('display','none'); // Hide columns for update
$("#dialog").dialog("open");
} else {
alert("Trip Schedule does not exist. It may be deleted by other user");
$.fn.yiiGridView.update('tripschedules-grid'); // Refresh the list of service class.
}
},
error: function(){
$.unblockUI();
alert("Ajax Communication Error. Please contact system administrator.");
}
}
);
}
Below is the scenario:
I clicked the pencil icon, dialog will show. It will load all the
details depend on the selected row. This is correct.
It will load all the details. This is correct.
No. of values in Drop down lists for service class is wrong.
My expected output of service class is only 4 (based on DB) but in actual, all service class was displayed.
I found out that $this->_ferryOperatorId = '3' from controller that was used in views
($serviceClassInfo->getAllServiceClassesForSelection2($model->ferry_operator_id,
$this->_ferryOperatorId , true, 'Select class'))
has no value.
In my models code, if the ferryOperatorId = null, it will display all the
service class.
My question is what is the correct code for me to get the value of $this->_ferryOperatorId from controller
then used the value in views.
:(
Please help me to solve this.
I apply a zend captcha in my php page now i require to add captcha reload button. Please give answer according to zend.
Just two quick snippets but I think you will get the idea. Adjust the element name and the selectors for your needs.
In your controller add a method to generate a fresh captcha
public function refreshAction()
{
$form = new Form_Contact();
$captcha = $form->getElement('captcha')->getCaptcha();
$data = array();
$data['id'] = $captcha->generate();
$data['src'] = $captcha->getImgUrl() .
$captcha->getId() .
$captcha->getSuffix();
$this->_helper->json($data);
}
In your view script (I'm using mootools for the ajax-request)
document.addEvent('domready', function() {
$$('#contactForm img').addEvent('click', function() {
var jsonRequest = new Request.JSON({
url: "<?= $this->url(array('controller' => 'contact', 'action' => 'refresh'), 'default', false) ?>",
onSuccess: function(captcha) {
$('captcha-id').set('value', captcha.id);
$$('#contactForm img').set('src', captcha.src);
}
}).get();
});
});
Edit: Added pahan's jquery
$(document).ready(function() {
$('#refreshcaptcha').click(function() {
$.ajax({
url: '/contact/refresh',
dataType:'json',
success: function(data) {
$('#contactForm img').attr('src', data.src);
$('#captcha-id').attr('value', data.id);
}
});
});
});
#user236501 Actually it can be any type of Zend Form Element (for example Button). You're even able to put clickable refresh link as Zend_Form_Element_Captcha description option like this:
$captcha = new Zend_Form_Element_Captcha('captcha', array(
'label' => 'Some text...',
'captcha' => array(
'captcha' => 'Image',
'wordLen' => 6,
'timeout' => 300,
'font' => './fonts/Arial.ttf',
'imgDir' => './captcha/',
'imgUrl' => 'http://some_host/captcha/'
),
'description' => '<div id="refreshcaptcha">Refresh Captcha Image</div>'
));
but in that case Description decorator's options should be modified, for example:
$this->getElement('captcha')->getDecorator('Description')->setOptions(array(
'escape' => false,
'style' => 'cursor: pointer; color: #ED1C24',
'tag' => 'div'
));
It can be done in form's init() method.
Sorry for my english. Btw I'm not sure if I put my comment in the right place ;)
#Benjamin Cremer
thanks for the code, works like charm :)
after reading this
I did it using jquery.
$(document).ready(function() {
$('#refreshcaptcha').click(function() {
$.ajax({
url: '/contact/refresh',
dataType:'json',
success: function(data) {
$('#contactForm img').attr('src',data.src);
$('#captcha-id').attr('value',data.id);
}
});
});
});
In config/autoload/global.php add the following
'view_manager' => array(
'strategies' => array(
'ViewJsonStrategy','Zend\View\Strategy\PhpRendererStrategy'
),
),
in YourModule/src/YourModule create a new folder Ajax
Inside Yourmodule/Ajax create a file AjaxController.php
namespace YourModule\Ajax;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use YourModule\Forms\SignupForm;
class AjaxController extends AbstractActionController
{
public function refreshSignupCaptchaAction(){
$form = new SignupForm();
$captcha = $form->get('captcha')->getCaptcha();
$data = array();
$data['id'] = $captcha->generate();
$data['src'] = $captcha->getImgUrl().$captcha->getId().$captcha->getSuffix();
return new JsonModel($data);
}
}
Add route inside module.config.php
'yourmodule-ajax' =>array(
'type' => 'segment',
'options' => array(
'route' => '/yourmodule/ajax/:action',
'constraints' => array(
'action' => '\w+',
),
'defaults' => array(
'controller' => 'YourModule\Ajax\AjaxController',
)
),
),
last in your template, I assume you are using jquery
<div class="form-group">
<div id="captcha" class="control-group <?php echo count($form->get('captcha')->getMessages()) > 0 ? 'has-error' : '' ?>">
<?php echo $this->formLabel($form->get('captcha')); ?>
<div class="col-xs-12 col-sm-6">
<a id="refreshcaptcha" class="btn btn-default pull-right">Refresh</a>
<?php echo $this->formElement($form->get('captcha')); ?>
<?php echo $this->formElementErrors($form->get('captcha')); ?>
</div>
</div>
</div>
<script type="text/javascript">
$(function(){
$('#refreshcaptcha').click(function() {
$.ajax({
url: '<?php echo $this->url('yourmodule-ajax', array('action'=>'refreshSignupCaptcha')) ?>',
dataType:'json',
success: function(data) {
$('#captcha img').attr('src', data.src);
$('#captcha input[type="hidden"]').attr('value', data.id);
$('#captcha input[type="text"]').focus();
}
});
return false;
});
});
</script>