Yii, javascript disables a certain field into Undefined Index - javascript

So I was having 2 dropDownLists in my _form.php and I have a radioButtonList which contains 2 options.
The problem I have is this, when I disable either one, one of the dropdown should be disabled. It did disable, BUT one of them will be turned into Undefined Index, whereas the other one is working fine when disabled.
This is my javascript:
$(document).ready(function(){
$('input[type=radio]').change(function(){
if(this.value == '0'){
$("#Booking_clientPackagedService_id").prop("disabled", false);
$("#Booking_service_id").prop("disabled", true);
$("#Booking_service_id").val('0');
}
else if(this.value == '1'){
$("#Booking_service_id").prop("disabled", false);
$("#Booking_clientPackagedService_id").prop("disabled", true);
$("#Booking_clientPackagedService_id").val('0');
}
});
})
Okay, so this is what happens. As you can see, IF I were to click on the option '1', the Booking_clientPackagedService_id will be disabled and to be submitted. But when I click on the button 'Save' in the form, it says
Error 500: Undefined index clientPackagedService_id
But If I were to choose on option '0' and submit, everything works just fine. service_id isn't giving any problem.
The below is my code to 2 dropDowns:
<div class="row">
<?php echo $form->labelEx($model,'clientPackagedService_id'); ?>
<?php $client = Client::model()->findByPk(1);?>
<?php echo $form->dropDownList($model, 'clientPackagedService_id', CHtml::listData($client->clientPackagedservices(array('condition'=>'client_id='.$client->id.' AND booking_id IS NULL')),'id','packagedServiceInfo')
,array(
'disabled'=>'disabled',
'prompt'=>'Select Packaged Service....',
'ajax' => array( 'type'=>'POST', //request type
'url'=>CController::createUrl('updateMasseuseAndStationListPSID'), //url to call.
'data'=>array('clientPackagedService_id'=>'js:this.value', 'dt'=>'js:$("#Booking_date").val()', 'timeStart'=>'js:$("#Booking_timeStart").val()'),
'dataType'=>'json',
'success'=>'js:function(data) {
var mass="#'.CHtml::activeId($model, 'masseuse_id').'";
$(mass).html(data.masseuse);
$(mass).trigger("chosen:updated");
$(mass+"_chzn").css("width","300px");
$(mass+"_chzn > .chzn-drop").css("width","298px");
var station="#'.CHtml::activeId($model, 'station_id').'";
$(station).html(data.station);
$(station).trigger("chosen:updated");
$(station+"_chzn").css("width","300px");
$(station+"_chzn > .chzn-drop").css("width","298px");
//alert(data.timeEnd);
var timeEnd="#'.CHtml::activeId($model, 'timeEnd').'";
$(timeEnd).val(data.timeEnd);
}',
)
)
); ?>
<?php echo $form->error($model,'clientPackagedService_id'); ?>
</div><!-- row -->
<div class="row">
<?php echo $form->labelEx($model,'service_id'); ?>
<?php echo $form->dropDownList($model, 'service_id', GxHtml::listDataEx(Service::model()->findAllAttributes(null, true)),
array(
//'disabled'=>'disabled',
'prompt' => 'Select Service....',
'ajax' => array( 'type'=>'POST', //request type
'url'=>CController::createUrl('updateMasseuseAndStationListSID'), //url to call.
'data'=>array('service_id'=>'js:this.value', 'dt'=>'js:$("#Booking_date").val()', 'timeStart'=>'js:$("#Booking_timeStart").val()'),
'dataType'=>'json',
'success'=>'js:function(data) {
//alert(data.masseuse);
var mass="#'.CHtml::activeId($model, 'masseuse_id').'";
$(mass).html(data.masseuse);
$(mass).trigger("chosen:updated");
$(mass+"_chzn").css("width","300px");
$(mass+"_chzn > .chzn-drop").css("width","298px");
var station="#'.CHtml::activeId($model, 'station_id').'";
$(station).html(data.station);
$(station).trigger("chosen:updated");
$(station+"_chzn").css("width","300px");
$(station+"_chzn > .chzn-drop").css("width","298px");
//alert(data.timeEnd);
var timeEnd="#'.CHtml::activeId($model, 'timeEnd').'";
$(timeEnd).val(data.timeEnd);
}',
)
));
?>
<?php echo $form->error($model,'service_id'); ?>
</div><!-- row -->
UPDATES After further debugging~
I found out the reason for it to behave that way.
$("#Booking_clientPackagedService_id").prop("disabled", true);
$("#Booking_clientPackagedService_id").val('0');
These 2 lines are the reason. Can anyone please advise me? Thanks~
UPDATES after further further debugging >.<~
I have a function in actionCreate():
$model->bookService($_POST['Booking']['clientPackagedService_id']);
basically, when the dropdown is disabled, this method wouldn't go through, thus, throwing an error 500 clientPackagedService_id Undefined index

Just add in a hidden duplicate field of the dropdownlist, in this case,
<?php echo $form->hiddenField($model, 'clientPackagedService_id'); ?>
Because disabled dropdownlists won't POST/GET to the PHP server side, therefore, adding in a hidden field will solve the problem

Related

Submit ajax request form on select change wordpress

I have a select option to filter posts by category. On select change I want the ajax request to be sent and load the posts of the category selected. I currently have this working using a submit button, but I need this to work on select option change, but I cannot get it to work just using a select.
Below is the script and form i'm working with that works on submit using a button.
<form action="<?php echo site_url(); ?>/wp-admin/admin-ajax.php" method="POST" id="filter" class="ghost-select">
<?php
if( $terms = get_terms( 'category', 'orderby=name' ) ) :
echo '<select id="categoryfilter" name="categoryfilter"><option>Select category...</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>';
endforeach;
echo '</select>';
endif;
?>
<!-- <button>Apply filter</button> -->
<input type="hidden" name="action" value="myfilter">
<!-- onchange="this.form.submit();" -->
</form>
$('#filter').submit(function(){
var filter = $('#filter');
$.ajax({
url:filter.attr('action'), // ajax
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
// filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
// filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
I have tired changing the initial submit function to the following, but it doesn't do anything:
$('#filter select').on('change', function() {
I've also tried adding onchange="this.form.submit();" to the select itself, but this submits the form and takes you away from the page to the url of the form action so I now know this isn't the right way to go.
I'm not sure what i'm missing so any help with this would be greatly appreciated!
Thanks

Show div element after reCaptcha validation

I am using Googles reCaptcha API for form validation.
I have opted to have the submit button show once the validation has been complete by using a little bit of JS.
<?php
if(isset($_POST['Login'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = '6LerNA0UAAAAAEReb9rS5JXjtvNSYlMjKiocUv_O';
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true){
//show submit button
echo '<script type=\"text/javascript\">
function myFunction() {
document.getElementById("logDiv").style.visibility="visible";
}
</script>';
}
else{ // stay hidden
'<script type=\"text/javascript\">
function myFunction() {
document.getElementById("logDiv").style.visibility="hidden";
}
</script>';
}
}
?>
<div id='logDiv' style='visibility:hidden')
<?php
echo $form->add('Login',array('type' => 'submit'));
?>
</div>
Currently, the solution isn't working; when the Captcha is validated the div remains hidden.
Is this a result of a syntax error or have a made a logical error?
What is the bug in my code?
Are there any more robust solutions?
Why not simply use a php condition to show the div? I think your JS isn´t working because you never call myFunction().
Try something like this but it will become complex over time and amount of code:
if(isset($data->success) AND $data->success==true){
$showButton = true;
}
......
if($showButton) { ?>
<div id='logDiv' style='visibility:hidden'
<?php echo $form->add('Login',array('type' => 'submit'));
?> </div> <?php }
......
Or a simple Solution:
if(is_bool($data -> success) && $data -> success){
echo '<div id="logDiv">'.$form->add('Login',array('type' => 'submit')).'</div>';
}
Echo the HTML Elements only if validition was successful otherwise simply dont ouput any HTML for the Div.
Hope this Helps.

Yii value from javascript

i need to get the value of a variable in a javascript function to put it in a textfiled.
Javascripts function:
function obtenerArrendatario(){
arrendatario_id = $.fn.yiiGridView.getSelection('arrendatario');
alert(arrendatario_id);
}
The alert give me the id of the selected row but i need to put the id in the textfield to save/create the form
Gridview
<div class="row">
<?php echo $form->labelEx($model,'zf_arrendatarios_arrendatario_id'); ?>
<?php
$arrendatarios = new ZfArrendatarios;
$this->widget('bootstrap.widgets.TbGridView',
array(
'id'=>'arrendatario',
'selectableRows'=>1,
'selectionChanged'=>'obtenerArrendatario',
'type'=>'striped bordered condensed',
'dataProvider'=>$arrendatarios->search(),
'filter' => $arrendatarios,
'template'=>"{items}\n{pager}",
'columns'=>array(
array('name'=>'arrendatario_id_personal', 'header'=>'DNI',),
array('name'=>'arrendatario_nombre', 'header'=>'Nombre'),
array('name'=>'arrendatario_email', 'header'=>'Email'),
),
));
?>
<?php
echo $form->textfield($model,'zf_arrendatarios_arrendatario_id',array('class'=>'input input_r input_pryk', 'value'=>$arrendatario));
?>
<?php echo $form->error($model,'zf_arrendatarios_arrendatario_id'); ?>
</div>
So i need that id that the function capture to fill my textfield.
I tried
$arrendatario= "<script> document.write(arrrendatario_id) </script>";
But it print me the string not the value.
For your requirement, you can set the textfield value in below js function
function obtenerArrendatario(){
arrendatario_id = $.fn.yiiGridView.getSelection('arrendatario');
$(".input_pryk").val(arrendatario_id );// input_pryk should be class for this text field alone.
}
Then you will get in controller while submitting the form.

How can I pass the name of the field in form_error ()

It's part of my view. Me need transmit input name in on which i click.
Below is a script that will get the name input after click
<div class="form_hint"><?=form_error('this get value from javascript after click')?></div>
<?php echo form_open("onenews/" . $onenews['id'] . "#signup", $form_reg['main_form']); ?>
<?php echo form_input($form_reg['login'], $this->form_validation->set_value('login')) ?>
<?php echo form_input($form_reg['email'], $this->form_validation->set_value('email')) ?>
<?php echo form_input($form_reg['password']) ?>
<?php echo form_input($form_reg['conf_password']) ?>
<?= MY_Controller:: create_captcha(); ?>
<?php echo form_input($form_reg['captcha']) ?>
<?php echo form_input($form_reg['submit']) ?>
<?php echo form_close(); ?>
</div>
</div>
jq
<script type="text/javascript">
$(function(){
var curInput = '';
$('#form_reg').find('input').on('click', function(){
curInput = $(this).attr("name");
});
})
</script>
Or i must use ajax?
Thanks!
Your question is not clear at all, but I assume you want to dynamically change the content of the form_hint div. You can't do that with PHP. Once PHP renders the page, it shuts down and does nothing more. So the only way to make PHP show that message is after the form submit, but then you lose your click data. There is a way to save the clicked element in a session for example, but that would be a really bad solution.
So the best solution would probably be to list all the hints in a JavaScript variable, and call the appropriate one upon the click event, and fill the form_hint div with it.
$('.form_hint').text(yourAppropriateMessageHere);
An example with a hidden div for the login input field with exactly how you described would be:
<div class="form_text_login"><?=form_error('login')?></div>
JS
var loginMessage = $('.form_text_login').text();
// list others here
// then make a tree with switch/case or if/else
if (curInput == 'login') {
$('.form_hint').text(loginMessage);
}
else if (curInput == 'email') {
// do the same with the email message, etc.
}

Wordpress Custom Post Type Popup—jquery and ajax?

I'm trying to use jquery (bpopup)to load a custom post type post into a popup window. An example of what I'm trying to do is at http://outpost.la —just click on any of the images to see the popup.
I think I ultimately need to write a function to do this, but I'm not sure about how to do that. So far I just have two snippets of code—"button that triggers popup" and "element to pop up"—in my page template. The first snippet is doing what I want: displaying the series of custom post type titles as buttons. But the second snippet which is supposed to display the custom post type content in the popup is showing the titles + content of all of the custom post types.
Screenshot of the Popup w/ buttons in the background:
http://cl.ly/image/1f0G0c2s2J3U
Code:
`
<!-- Button that triggers the popup -->
<?php
$args = array(
'post_type' => 'portfolio_project',
'posts_per_page' => -1 );
$loop = new WP_Query( $args );
$i = 0;
echo'<button class="my-button">';
while ( $loop->have_posts() ) : $loop->the_post();
if ($i % 0 == 0 && $i > 0) {
echo '</button>' . "\n" . '<button class="my-button">';
};
?>
<?php the_title(); ?>
<?php
$i++;
endwhile;
echo '</button>';
?>
<!-- Element to pop up -->
<div id="element_to_pop_up">
<?php
// the query
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<!-- pagination here -->
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; ?>
<!-- end of the loop -->
<!-- pagination here -->
<?php wp_reset_postdata(); ?>
<?php else: ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
<!-- end custom post type loop -->
</div>
<!-- END Element to pop up -->
<script>
// Semicolon (;) to ensure closing of earlier scripting
// Encapsulation
// $ is assigned to jQuery
;(function($) {
// DOM Ready
$(function() {
// Binding a click event
// From jQuery v.1.7.0 use .on() instead of .bind()
$('.my-button').bind('click', function(e) {
// Prevents the default action to be triggered.
e.preventDefault();
// Triggering bPopup when click event is fired
$('#element_to_pop_up').bPopup({
appendTo: 'body'
, position: ['auto','0']
, positionStyle: 'fixed'
, scrollBar: 'false'
});
});
});
})(jQuery);
</script>
`
Actually Wordpress uses a different approach for ajax request. You have to understand that first. So, the simple prototype is something like this
// In your functions.php file
add_action( 'wp_ajax_nopriv_ MyAjaxAction', 'MyAjaxFunction' );
add_action( 'wp_ajax_ MyAjaxAction', 'MyAjaxFunction' );
function MyAjaxFunction() {
// do query for your posts
// process it
// echo it
die();
}
In your client side/jQuery code
$(function(){
$('.myButton').on('click', function(e){
e.preventDefault();
// other code
$.ajax({
'url':'/wp-admin/admin-ajax.php', // admin-ajax.php will handle the request
'type':'post',
'data': {
// this is the action hook to call the handler "MyAjaxFunction"
'action': 'MyAjaxAction',
// pass some data to post variblr to use in php/wordpress (optional)
'id':'someId' // you can retrieve this using $_POST['id'];
},
'success':function(data){
// returned data by wordpress
}
});
});
});
This is the proper way to handle ajax request in WordPress, read this article for more help and as a bonus download this book.

Categories