D
D
DragonChris2017-08-16 17:01:43
Yii
DragonChris, 2017-08-16 17:01:43

How to properly pass model to layout in yii2?

I have a feedback form in layout, and I need to pass the model there.
I was looking for options and the option with the widget seems to me the most correct, but I don’t know how to return the model from the widget or I simply don’t understand how it should work.
Here is the widget code:

<?php

namespace frontend\widgets;

use yii\base\Widget;
use yii\helpers\Html;
use common\models\Callback;

class LModel extends Widget {
    public $lModel;
    public function init()
    {   
        parent::init();
    }

    public function run()
    {   
        $lModel = new Callback();
        return $lModel;
    }
}

I already understood that the widget returns a string (swears that I am passing an object).
Tell me how to correctly transfer the model to the layout, because I don’t really want to call it there.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis A., 2017-08-16
@DragonChris

public function run() {
    
    
    return $this->render('callbackform', [
      'model' => new Callback(),
    ]);
  }

in frontend/widgets/views make a view with a callbackform.php form like this
<?php
use yii\helpers\Url;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>

<div id="callback">
    <?php $form = ActiveForm::begin([
      'id' => 'callback-form',
      'enableAjaxValidation' => true,
      'action' => Url::to(['site/callback']),
      'validationUrl' => Url::to(['site/callback']),
  ]); ?>
  
        <?= $form->field($model, 'name')->textInput([
      'placeholder' => 'Имя',
    ])->label(''); ?>
    
    <?= $form->field($model, 'phone')->textInput([
      'placeholder' => 'Телефон',
    ])->label(''); ?>
    
     <?= Html::submitButton('Отправить', ['class' => 'btn btn-primary']) ?>

    <?php $form->end(); ?>
</div>

in the site/callback controller validation and dispatch

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question