Yii2: How to get default form name? - javascript

I have a view with a simple form:
<?php $form = ActiveForm::begin(); ?>
...
<?php ActiveForm::end(); ?>
I need to know the default name of the form. I tried using JavaScript, jQuery or even PHP but I don't know ho to get it.

if the active form is created by gii by default Yii2 don't assign name but assign id tipically
id="w0"
If you need you could assign values using options
$form = ActiveForm::begin([
'id' => 'your-id-form',
'options' => ['class' => 'form-horizontal', 'name' => 'your-name],
]) ?>
http://www.yiiframework.com/doc-2.0/yii-bootstrap-activeform.html
http://www.yiiframework.com/doc-2.0/guide-input-forms.html

In jquery you can do this
$('form').prop('id');

Related

How do I pass JavaScript variables to PHP in yii2?

I am developing a recriment software and in Yii2 framework application form I want to check if applicant has already applied for same job using 'passport no', my form looks like
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'cnic')->textInput(['type' => 'number']) ?>
<?= Html::submitButton('Save and Continue', ['class' => 'btn btn-success']) ?>
<?php ActiveForm::end(); ?>
and I am unable to get the cnic value in php. my Javascript code is.
$('#applications-cnic').change(function(){
var data = $(this).val();
var validation = <?= $model->checkCNIC($postid, '<script>data</script>'?>. <?= ) ?>;
alert(validation);
if (validation == 'data_exist') {
alert("You have already applied for this job, use your tracking ID to check your applicaiton or contact HR");
}
});
it is not working and I am unable to pass this value I get from javascript to my php function.
public function checkCNIC($value , $cnic)
{
$query= Applications::find()
->where(['post_id' => $value])
->andWhere(['cnic' => $cnic])
->all();
if ($query) {
return 'data_exist';
}
else
return 'no_data';
}
Ajax is the recommended solution. You can still use javascript inside php using document.writeln
'<script>document.writeln(data)</script>`

How to Overcome Conflicts in JS

In form, I want the function to take data from form one to another form automatically and automatic calculations run together. but here only one function can be run.
in my foto I want when I select LAO, it will automatically retrieve data from other forms and appear in the Posisi Awal textfield. then when I fill the Persen textfield, then automatically calculates and fills in the data from the calculation of the Posisi Awal with Persen in the Target Awal textfield. The problem is the automatic calculation works but retrieving data from the form to another form does not work.
<?= $form->field($model, 'posisi_awal')->textInput(['id'=>'posisi_awal','onkeyup'=>'sum();','type' => 'number','maxlength' => true])->label('Posisi Awal') ?>
when I omit 'id' => 'posisi_awal' in this code. for the function of retrieving data from another location it can run, but for automatic calculations it cannot
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use app\models\Resumes;
use dosamigos\datepicker\DatePicker;
/* #var $this yii\web\View */
/* #var $model app\models\Monitoring */
/* #var $form yii\widgets\ActiveForm */
$model->tgl = date('Y-m-d');
?>
<script>
function sum() {
var txtThirdNumberValue = document.getElementById('posisi_awal').value;
var txtFourNumberValue = document.getElementById('persen').value;
var result1 = parseInt(txtThirdNumberValue) / 100 * parseInt(txtFourNumberValue);
var hasil1 = Math.ceil(result1);
if (!isNaN(hasil1)) {
document.getElementById('target_awal').value = hasil1;
}
}
</script>
<div class="monitoring-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'kode_lao')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Resumes::find()->all(),'resumes_id',function($model){return ($model->lao.' ('.$model->tgl.')');}),
'theme' => Select2::THEME_BOOTSTRAP,
'language' => 'en',
'options' => ['placeholder' => 'Pilih LAO (Tanggal)','required' => true,'style'=>'width:500px','maxlength' => true,'id'=>'lao'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?= $form->field($model, 'tgl')->textInput(['readOnly'=>true,'style'=>'width:500px','maxlength' => true]) ?>
<?= $form->field($model, 'posisi_awal')->textInput(['id'=>'posisi_awal','onkeyup'=>'sum();','type' => 'number','maxlength' => true])->label('Posisi Awal') ?>
<?= $form->field($model, 'persen')->textInput(['id'=>'persen','onkeyup'=>'sum();','type' => 'number','maxlength' => true])->label('Persen') ?>
<?= $form->field($model, 'target_awal')->textInput(['id'=>'target_awal','onkeyup'=>'sum();','type' => 'number','maxlength' => true])->label('Target Awal') ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$script = <<< JS
$('#lao').change(function(){
var laoId = $(this).val();
$.get('index.php?r=resumes/get-persen-eom',{ laoId : laoId },function(data){
var data = $.parseJSON(data);
$('#monitoring-tgl').attr('value',data.tgl);
$('#monitoring-posisi_awal').attr('value',data.tgt_pergeseran);
});
});
JS;
$this->registerJs($script);
?>
$('#monitoring-tgl').attr('value',data.tgl);
$('#monitoring-posisi_awal').attr('value',data.tgt_pergeseran);
You don't have fields with those ID's on that page.
Also if you change some input value then you need to trigget a change event on that input for other code that is reliant on that fields onchange event to trigger.
Why are you changing value of an input using attr? jQuery has .val(value) method for this: http://api.jquery.com/val/
So correct usage would be something like this:
$('#monitoring-tgl').val(data.tgl).trigger("change");
$('#monitoring-posisi_awal').val(data.tgt_pergeseran).trigger("change");
Or maybe even like this. As I think you are refering to the #posisi_awal input there actually. But I dont have a clue about #monitoring-tgl input. Does not seem to exist on that page.
$('#monitoring-tgl').val(data.tgl).trigger("change");
$('#posisi_awal').val(data.tgt_pergeseran).trigger("change");

How to pass a PHP variable into a Javascript cookie on submit of form?

I am setting up a custom form to be used in my wordpress site. What I would like to do is grab the AUTO_INCREMENT ID of that submission and pass it into a Javascript cookie when the form is submitted. Currently the ID is working, but because the ID isn't grabbed until after the form is submitted, I'm having trouble figuring out how I can pass the variable into the cookie immediately after the form has been submitted(currently I have to submit the form twice before the cookie with the ID is created, and its 1 number lower than it should be since it's a submission behind).
Here's what I have currently:
<?php
if(isset($_POST["submit"])) {
$name = $_POST['full_name'];
$city = $_POST['city'];
$state = $_POST['state'];
$email = $_POST['email'];
$wpdb->insert(
'reps',
array(
'name' => stripslashes($name),
'city' => stripslashes($city),
'state' => stripslashes($state),
'email' => stripslashes($email)
)
);
$lastid = $wpdb->insert_id;
}
?>
<script>
$('#dealer-form').submit(function() {
var repID = '<?php echo $lastid ?>';
setCookie('ID', repID);
});
</script>
As I mentioned this code works on the second submission(since the variable has no value on the first submission), and the ID is 1 number behind because it is grabbing the ID of the previous submission before reassigning the variable value.
PHP, being a server-side scripting language, is executed before the data is sent to your browser. JavaScript, a client-side scripting language, is executed as soon as the script is encountered by the browser.
Your approach is forgetting this separation between front- and back-end.
To accomplish what you're trying to do, simply output the setCookie call when you've submitted your form in php:
<?php
if(isset($_POST["submit"])) {
$name = $_POST['full_name'];
$city = $_POST['city'];
$state = $_POST['state'];
$email = $_POST['email'];
$wpdb->insert(
'reps',
array(
'name' => stripslashes($name),
'city' => stripslashes($city),
'state' => stripslashes($state),
'email' => stripslashes($email)
)
);
$lastid = $wpdb->insert_id;
printf( '<script>setCookie("ID", %d);</script>', $lastid );
}
?>

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.

cakephp form not submitted correctly after JS added a new field

The View
<?php echo $this->Form->create('Practice');
echo $this->Form->input('title',array('value'=>'test value'));
echo $this->Js->submit('Ajax Submit', array(
'update' => '#left',
'url'=>'/practices/content',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
));
?> <?php echo $this->Form->end(); ?>
the form works fine before the Ajax submit. the ajax submit actually return a new form field of the same model. below is the view of which the form is being sent firstly for ajax
echo $this->Form->input('Practice.options',array('value'=>'regex value'));
the new field value is not being submit with the form
I was doing two mistakes first the new ajax returned fields were not inside form tag second I needed to bypass the cakephp security check
function beforeFilter() {
parent::beforeFilter();
$this->Security->blackHoleCallback = 'blackhole';
$this->Security->csrfCheck = false;
$this->Security->validatePost = false;
$this->set('contentLayout', 'admin_dashboard');
}
Make sure that your put at the end of your form
<?php echo $this->Form->end(); ?>
and you unlock the current action for the SecurityComponent

Categories