Search code examples
yii2yii2-advanced-appyii2-model

How to add an input field on the index page in Yii2


I am working on a project in yii2. I need to place an input field on the index page. This field should be similar to the form field. i.e. the type of the field that is used in the form while creating a record. For this, I have done the following

 public function actionIndex()
{
    $model = MdcmetercustRel::className();// this is the class whose data field I want to get
    $searchModel = new MdcmetersdataSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
        'model' => $model,

    ]);
}

My index

 <?=

  $form = ActiveForm::begin();
  $relModel=$model->getModels()[0]; print_r($relModel['cust_id']);
   $form->field($relModel, 'cust_id')->textInput()


  ?>

When I refresh my page I am getting

Object of class yii\widgets\ActiveForm could not be converted to string

How can I achieve this?

Any help would be highly appreciated


Solution

  • Your mistake is <?=which is trying to output the whole script and you cant echo $form or ActiveForm::begin()

    change it to

    <?php 
    
      $form = ActiveForm::begin();
      $relModel=$model->getModels()[0]; print_r($relModel['cust_id']);
      echo $form->field($relModel, 'cust_id')->textInput()
    ?>
    

    Also you need to change the

    $model = MdcmetercustRel::className();
    

    to

    $model = new MdcmetercustRel();
    

    otherwise there wont be an object in $model but a string i.e class namespace.