Yii2: Fill form automatically only when triggered - yii2

How to fill a form automatically, but only when it is requested by the user.
That is, the fields are not populated when the form is generated.
Por example:
<?= $form->field($model, 'city')->textInput() ?>
When the form is accessed, the field is empty. And what I want is that there is a button, which when the user clicks, automatically the field is populated with the value of the "city" that is in the "User" table.
Form:
City : __________ | get my city |
After user clicked on button "get my city":
City : _London___ | get my city |

At last no ajax needed
<div class="row">
<div class="col-sm-12">
<?= Html::activeLabel($model, 'city') ?>
</div>
<div class="col-xs-9">
<?= $form->field($model, 'city')->textInput()->label(false) ?>
</div>
<div class="col-xs-3">
<?= \yii\helpers\Html::button('get my city', ['id' => 'get-user-city-btn']) ?>
</div>
</div>
<?php $this->registerJs("
$('#get-user-city-btn').on('click', function(){
$('#id-of-city-input-goes-here').val('"
. Yii::$app->user->identity->city
. "');
});
", $this::POS_END, 'get-user-city-script'); ?>

Related

How to change the field value in update form in Yii2

In my update form, I want to show the original value rather than it's id. Below is my _form.
<div class="mdc-meter-config-form">
<?php $form = ActiveForm::begin(['id'=>'con','options' => ['enctype' => 'multipart/form-data']]) ?>
<label class="control-label">Select Meters</label><br />
<input type="text" id="the-mter-id" class="form-control col-md-12" value="<?=$model->meter_id?>" />
<div style="clear: both;"></div>
<div id="selected_mters_container"></div>
<div style="clear: both;"></div>
<br/>
<?= $form->field($model, 'p_id')->dropDownList([''=>'Please Select']+\common\models\MdcProtocol::toArrayList()) ?>
<?= $form->field($model, 'time')
->dropDownList([''=>'Please Select','5' => '5', '10' => '10', '15' => '15','20'=>'20'])->label("Set Time (in seconds)") ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
In above view I want to change the 2 value to its actual one which is 4A60193390662
Dont know why you are not using the relation here for the meter to display the meter serial rather than the id.
Easiet way to avoid any further work as you want to just display it, 2 things you need to do
Assign the value to the input manually via relation.
Make the field disabled to exclude it out of the model collection array. (in case you use active form for the field).
I assume you have a relation to the meter in your current model with name getMeter() and the number you are trying to display 4A60193390662 is in field serial_number. You can change accordingly.
If you havent defined a relation than define one now
public function getMeter(){
return $this->hasOne(Meter::class,['id'=>'meter_id']);
}
Although you are using a custom html field you can still use the active form and mark the field disabled so that the activeform wont submit it with the model collection array and there wont be errors when saving the records like
meter_id should be an integer.
echo $form->field($model, 'meter_id')->textInput(['disabled' => 'disabled', 'value' => $model->meter->serial_number]);
try add an entry also for the field with value 4A60193390662 eg: $model->meter_name
<input type="text" id="the-mter-name" class="form-control col-md-12" value="<?=$model->meter_name?>" />
and if you don't want see the entry for meter_id .. you could use hidden input for this so mantain the related avlue for the model loading and popolation
And as suggested in comment by Michal Hyncica (sorry for improper charset ) you could wrap the input inside a check fo new record
<?php
if(!$model->isNewRecord) {
echo '<input type="text" id="the-mter-name" class="form-control col-md-12" value="' . $model->meter_name . '" />';
}

yii2 from validation on array form elements

I've a form containing array elements and I've to validate it. i cant validate it by using the in-built validation rules, because the elements are not present in the database. i'm serialising the data and save them in a single field in database. so i tried to do the validation with custom validation.
my actual problem is the array field is validating but it doesn't shows the validation error message in the corresponding field.
This is the form
<div class="col-md-6">
<?php Portlet::begin(['title' => t('Shipper')]) ?>
<?= $form->field($model, 'shipper[name]')
->textInput(['maxlength' => true])->label(t('Name'))?>
<div class="row">
<div class="col-md-8">
<?= $form->field($model, 'shipper[address_line1]')
->textInput(['maxlength' => true])->label(t('Address Line 1')) ?>
<?= $form->field($model, 'shipper[address_line2]')
->textInput(['maxlength' => true])->label(t('Address Line 2')) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'shipper[city]')
->textInput(['maxlength' => true])->label(t('City')) ?>
<?= $form->field($model, 'shipper[pin]')
->textInput(['maxlength' => true])->label(t('Pin Code')) ?>
</div>
</div>
Model
.....
['shipper', function ($attribute, $params) {
if (!filter_var($this->{$attribute}['email'], FILTER_VALIDATE_EMAIL)) {
$this->addError('shipper', 'The email format is invalid!');
}
}],
....
You could add attributes to your model class like the following:
class MyModel extends \yii\db\ActiveRecord {
public $shipperAddressLine1;
public $shipperAddressLine2;
public $shipperCity;
public $shipperPin;
...
}
Then you can add validation rules for them just like your database attributes.

Blank page on update after including if condition yii2

When I include if condition in update form I'm getting blank page.
Otherwise without if condition update works fine.
_form.php without if condition (this works fine)
<?= $form->field($model, 'certified')->radioList(['y'=>'YES', 'n'=>'NO']) ?>
<div class="row">
<div class="row">
<?= $form->field($modelcertificate, 'description')->dropDownList(
ArrayHelper::map(CertificateDescription::find()->all(),'description','description'),
[ 'prompt'=>'select desc',
]); ?>
</div>
<div class="row">
<?= $form->field($modelqm, 'q1')->textInput(['maxlength' => true]) ?>
</div>
</div>
For the same if I include If condition, after hitting update button blank page will be shown.
_form.php with if condition ( leads to blank page)
<?= $form->field($model, 'certified')->radioList(['y'=>'YES', 'n'=>'NO']) ?>
<div class="row">
<?php if ($model->certified == 'y') : ?>
<div class="row">
<?= $form->field($modelcertificate, 'description')->dropDownList(
ArrayHelper::map(CertificateDescription::find()->all(),'description','description'),
['prompt'=>'select desc', ]); ?>
</div>
<?php else: ?>
<div class="row">
<?= $form->field($modelqm, 'q1')->textInput(['maxlength' => true]) ?>
</div>
<?php endif; ?>
</div>
The problem was in Controller, so blank page is caused by missing return point.
For debug purposes it possible to use CRUD generated by gii, and improve it line by line to fit your personal needs.

How to use 'onchange' in Yii2 MaskedInput widget

I have an Yii2 app with advanced template. There is 2 fields on my form. 1st: MaskedInput and 2nd textInput with readonly attribute.
So, I wanted to fill 2nd textInput automatically right after I have filled MaskedInput. For this I tried to use onchange. But I got following error:
Unknown Property – yii\base\UnknownPropertyException
Setting unknown property: yii\widgets\MaskedInput::onchange
Here is my code:
<?php $form = ActiveForm::begin(); ?>
<div class="row">
<div class="col-xs-3">
<?= Html::label("Ser num")?>
<?= MaskedInput::widget(['name'=>'serNum',
'mask'=>'AA 9999999',
'onchange'=>'
$.post("index.php?r=act/actid&serNum='.'"+$(this).val(),function(data){
$("select#ser-sernum").html(data);
});
'
])?>
</div>
<div class="col-xs-3">
<?= $form->field($model, 'sernum')->textInput(['readonly'=>true]) ?>
</div>
<div class="col-xs-6">
<b id="actstatus"></b>
</div>
</div>
Try with options property:
<?= yii\widgets\MaskedInput::widget(['name'=>'serNum',
'mask'=>'AA 9999999',
'options' => [
'onchange'=>'
$.post("index.php?r=act/actid&serNum='.'"+$(this).val(),function(data){
$("select#ser-sernum").html(data);
});'
]
])?>

Login form requires second click to submit

My backend login form submits with a single click of the login button. It creates an <input type="hidden" name="login-button"> element then shortly thereafter submits. On the frontend the same is created on click but never posts the data until I click the button again.
Here is a sample of the view code:
<div id="login-form" class="col-sm-12">
<?php $form = ActiveForm::begin(['id' => 'login-form']); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<div class="col-sm-5 col-sm-offset-4 forgotPassword">
<?= $form->field($model, 'rememberMe')->checkbox() ?>
<div style="margin:auto;color:#fff;margin:1em 0;font-size:10px;">
if you forgot your password you can <?= Html::a('reset it', ['site/request-password-reset']) ?>
</div>
<div class="form-group">
<?= Html::submitButton('login', ['class' => 'btn btn-primary loginButton', 'name' => 'login-button']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
The only difference I am seeing between the two is that there are some additional <div> tags that have been added for styling purposes. I have even removed those and I am still seeing the same issues.
Any ideas would be appreciated.
It looks like the id on the form div was causing the issue. Removing this has cleared everything up.
It was causing a conflict because it had the same id as the form.
I just want to add that usually you assign model "formName" as your form id
<?php $form = ActiveForm::begin(['id' => $model->formName()]); ?>