Yii value from javascript - 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.

Related

Need to display a value in string format in CodeIgniter view

I am trying to display a value $raw which is in an array format to a textbox in a CodeIgniter view
This is the function I am using in my controller:
public function pricing($raw='array')
{
if ($raw === 'array')
{
return $this->result_array();
}
}
I tried this but still getting message:array to string conversion
I am using $raw in my view 'add_calendar.php':`
<?php echo(['name'=>'tohr','class'=>'form-control','placeholder'=>'Enter total hire rate','value'=>'$raw'])?>
You can not echo an array because echo expects string as its parameter. Since you are trying to echo the values to a textbox you may want to do this.
When you load your view pass $raw to your view.
$data = array('raw'=>$raw);
$this->load->view('add_calendar', $data);
Then in your view use form_input to create a textbox.
echo form_input(['name'=>'tohr','class'=>'form-control','placeholder'=>'Enter total hire rate','value'=>$raw]);
Pass the array from the controller to view
$raw is a variable don't use single quotes ' for it
$data['record'] = array('name'=>'tohr','class'=>'form-control','placeholder'=>'Enter total hire rate','value'=> $raw);
return $this->load->view('file', $data);
View
You can use these values with or without HTML tags
Without HTML tags
<?= $name ?> //tohar
<?= $class ?> //form-control
<?= $raw ?>
With HTML tags
<td><?= $name ?></td>
<p><?= $name ?></p>
<h3><?= $name ?></h3>

Output value in javascript from php loop

I'm not sure how to search this, but I have an array in php numbered 1 to 20. I have a foreach loop to output the values and have the user be able to click on the numbers. After clicking the number, the page would then output the number clicked.
HTML:
<div id="chapters" onclick="getChapter()">
$array = range(1,20);
foreach($array as $chapter) {
?>
<p class="getChapter" id="currChapter">Chapter <?php echo $chapter;?></p>
<?php
}
?>
</div>
Javascript
function getChapter() {
chapter = document.getElementById("currChapter").id;
document.write(chapter);
}
I'm not able to output the number that the user clicks on.
I have tried putting
id=<?php $chapter?>
, but that does not work as well as replacing id with value and name.
I would recommend passing the $chapter as parameter of a function "Onclick" event :
<div id="chapters">
<?php
$array = range(1,20);
foreach($array as $chapter) {
?>
<p class="getChapter" onClick="getChapter(<?php echo $chapter;?>)">Chapter <?php echo $chapter;?></p>
<?php
}
?>
and the Javascript:
function getChapter(chapterNumber) {
alert(chapterNumber);
}
I don't really understand what you want to do, seems you explanation just a example, but may be this will help. You can call function getChapter with parameter ( onClick="getChapter(<?php echo $chapter;?>) ) :
$array = range(1,20);
foreach($array as $chapter) {
?>
<p class="getChapter" id="currChapter" onClick="getChapter(<?php echo $chapter;?>)">Chapter <?php echo $chapter;?></p>
<?php
}
function getChapter(chapter) {
document.write(chapter);
}

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, javascript disables a certain field into Undefined Index

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

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.
}

Categories