Putra
Putra

Reputation: 79

How to set a different label for tabular input - Yii2

I have followed this guide http://www.yiiframework.com/doc-2.0/guide-input-tabular-input.html to build a tabular input. But in my case, I want to add a different label for each input. How can I do that?

Update action:

public function actionUpdate()
{
    $emailModel = EMAIL::find()->indexBy('ID')->all();

    if (Model::loadMultiple($emailModel, Yii::$app->request->post()) && Model::validateMultiple($emailModel)) {
        foreach ($emailModel as $email) {
            $email->save(false);
        }
        return $this->redirect('update');
    }

    return $this->render('update', ['emailModel' => $emailModel]);
}

Update View

<?php $form = ActiveForm::begin(); ?>
        <?php foreach ($emailModel as $index => $email) { ?>
            <?= $form->field($email, "[$index]CONTENT")->textArea(['maxlength' => true])->label(false) ?>
        <?php } ?>
        <div class="form-group">
            <?= Html::submitButton('Save', ['class' => 'btn btn-primary']) ?>
        </div>
 <?php ActiveForm::end(); ?>

I'm on learning Yii2. Thank you.

Upvotes: 1

Views: 911

Answers (2)

vishuB
vishuB

Reputation: 4261

Add label(label name) used as per Tabular Input

<?php $form = ActiveForm::begin(); ?>
    <?php foreach ($emailModel as $index => $email) { ?>
        <?= $form->field($email, "[$index]CONTENT")->textArea(['maxlength' => true])->label('Email '.$index+1) ?>
    <?php } ?>
    <div class="form-group">
        <?= Html::submitButton('Save', ['class' => 'btn btn-primary']) ?>
    </div>
<?php ActiveForm::end(); ?>

Refer the Docs Yii2 Active Field

Upvotes: 0

arogachev
arogachev

Reputation: 33538

Changing the label for multiple models is the same as for one model.

1) To retrieve it from attributeLabels() or generate automatically based on according database column name (in case it's ActiveRecord and there is no according entry in attributeLabels()) just omit ->label(false) call:

<?= $form->field($email, "[$index]CONTENT")->textArea(['maxlength' => true]) ?>

2) To apply custom label just for this form:

<?= $form->field($email, "[$index]CONTENT")->textArea(['maxlength' => true])->label('Your custom label') ?>

3) To have different label for each $model in a set just create helper function and call it in the loop:

function getCustomLabel($model, $index) 
{
    $number = $index + 1;
    return "Content for model number $number";
}

<?= $form->field($email, "[$index]CONTENT")->textArea(['maxlength' => true])->label(getCustomLabel($model, $index)) ?>

Check the official docs:

Upvotes: 3

Related Questions