yoyoma
yoyoma

Reputation: 3536

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 ?

Upvotes: 4

Views: 8264

Answers (2)

Christian Lescuyer
Christian Lescuyer

Reputation: 19253

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');

Upvotes: 2

topher
topher

Reputation: 14860

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');");

Upvotes: 5

Related Questions