Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create form in view from different model in yii2?

Tags:

php

yii2

Iam new to yii. I am developing customer project app. I have a view wherein iam displaying the data from both the models, customer and projects.

How do i create a form to add new projects? my project is here

To display project data in customer view, iam using

$query=Projects::find()
    ->where(['projects_clients_id'=> $model->customer_id]);    

       $dataProvider = new ActiveDataProvider([
        'query' => $query,        
        'pagination' => [
            'pageSize' => 20,
        ],
    ]);
    echo GridView::widget([
        'dataProvider' => $dataProvider,
    ]);
like image 416
Nuthan Raghunath Avatar asked Mar 14 '23 21:03

Nuthan Raghunath


2 Answers

You can render several model and/or dataProvider in a view (properly constructed)

eg:

    return $this->render('viewTestMulti', [
        'modelOne'                 =>$modelOne,
        'dataProviderTwo'                => $providerTwo,
        'dataProviderThree'      => $providerThree,
        'modeFour'                    => $modelFour,
    ]);

And then you can use a view with several gridView related to proper dataProvider and several forms everyone with a proper action so when you press the specified submit you invoke the proper controller action

<?php
    use yii\helpers\Html;
    use yii\widgets\ActiveForm;
?>


<?php $formOne = ActiveForm::begin(); 
      $formOne->action=  yii\helpers\Url::to('ControllerOne\create');
 ?>

<?= $formOne->field($modelOne, 'name') ?>

<?= $formOne->field($modelOne, 'email') ?>

<div class="form-group">
   <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>



<?php $formFour = ActiveForm::begin(); 
   $formFour->action= yii\helpers\Url::to('ControllerFour\create');
?>

<?= $formFour->field($modelFour, 'name_four') ?>

<?= $formFour->field($modelFour, 'email_four') ?>

<div class="form-group">
   <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>

I hope this could be useful

like image 154
ScaisEdge Avatar answered Mar 17 '23 09:03

ScaisEdge


You have all the documentation about ActiveForms and I recommend, if you are new in Yii2 to use The Definitive Guide to Yii 2.0, here the Forms Section

This is a basic form:

<?php
   use yii\helpers\Html;
   use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(); ?>

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

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

<div class="form-group">
    <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
like image 45
Sageth Avatar answered Mar 17 '23 09:03

Sageth