4

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 ?

1
  • 1
    I usually don't use an ActiveRecord-instance but put a special form-model in between (can be a simple Model), especially for that sort of things. You can add as many custom fields as you want, add special form-only validation rules. Commented May 8, 2015 at 13:17

2 Answers 2

5

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');");
Sign up to request clarification or add additional context in comments.

1 Comment

I'm getting undefined variable:value. Please help.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.