Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 Add a Form field not in model

As we know,

<?= $form->field($model, 'name_field')->textInput() ?>

Adds a text field connected to 'name_field' in the model/table.

I want to add a field NOT in the model/table, and then run some JS when it loses focus to calculate the other fields.

How firstly do you add a free text field not connected to the model ? Second, does anyone have any examples of adding JS/Jquery to the _form.php ?

like image 836
yoyoma Avatar asked Mar 16 '23 03:03

yoyoma


2 Answers

The Html class contains the functions for generation of fields. In fact, your code above ends up calling Html::textInput(). To add a field

<?= Html::textInput("name", $value) ?>

To add javascript to a view just use registerJs():

$this->registerJs("alert('true');");
like image 152
topher Avatar answered Mar 26 '23 16:03

topher


You can have the field rendered the same way as the ActiveField, with a label and classes. For example, let’s add a Cc field to a Mail form.

First display the To: field (in the model):

<?= $form->field($model, 'to')->textInput() ?>

Let’s add the Cc field (not in the model):

<?= Html::beginTag('div', ['class' => 'form-group field-mail-cc']) ?>
<?= Html::label('Cc:', 'mail-cc', ['class' => 'control-label']) ?>
<?= Html::textInput('Mail[cc]', '', ['id' => 'mail-cc', 'class' => 'form-control']) ?>
<?= Html::endTag('div') ?>

The class and id names mail-cc and field-mail-cc follow the ActiveForm naming pattern. The input name Mail[cc] adds your field to the ActiveForm group, so you can easily retrieve it with the usual

$form = Yii::$app->request->post('Mail');
like image 28
Christian Lescuyer Avatar answered Mar 26 '23 16:03

Christian Lescuyer