Yii2-无法将模型从控制器传递到视图

Yii2- Unable to pass model from controller to view

我正在研究 Yii2。我有一个控制器,我正在其中执行以下操作。

 /**
 * @param $id
 * @return string|\yii\web\Response
 * @throws NotFoundHttpException
 * @throws \Exception
 * @throws \yii\db\Exception
 * @throws \yii\db\StaleObjectException
 */

 public function actionViewcreated($id)// passed the id of my model which is created in the previous step
{
    $params = "";
    //print_r('hi');

    $model= $this->findModel($id); // this will find my model/record based on the id

    $sub_div = $model->sub_div;
    $meter_type = $model->meter_type;

    $query = /** @lang text */
        "SELECT DISTINCT m.`id` AS meter_id, ins.`meter_msn` AS Meter_Serial_Number, ins.`meter_type` AS Meter_Type, sd.`sub_div_code` AS Sub_Division_Code,sd.`name` AS Sub_Division_Name 
FROM `installations` ins 
INNER JOIN `meters` m ON ins.`meter_msn` = m.`meter_msn`
INNER JOIN `meter_acceptance_header` map ON ins.`meter_type` = map.`meter_type`
INNER JOIN `survey` sur ON ins.`ref_no` = sur.`ref_no` 
INNER JOIN `survey_hesco_subdivision` sd ON sur.`sub_division` = sd.`sub_div_code` 
WHERE ins.`meter_type` = '$meter_type' 
AND sd.`sub_div_code` = '$sub_div' 
AND m.`id` NOT IN (SELECT DISTINCT md.`meter_id` FROM 
`meter_acceptance_details` md WHERE md.`flag` IN (1))";


    $session = Yii::$app->session;
    $session->set('my_sql', $query);

    $sqlCount= /** @lang text */
        "SELECT COUNT(DISTINCT m.`id`)  
FROM `installations` ins 
INNER JOIN `meters` m ON ins.`meter_msn` = m.`meter_msn`
INNER JOIN `meter_acceptance_header` map ON ins.`meter_type` = map.`meter_type` 
INNER JOIN `survey` sur ON ins.`ref_no` = sur.`ref_no` 
INNER JOIN `survey_hesco_subdivision` sd ON sur.`sub_division` = sd.`sub_div_code` 
WHERE ins.`meter_type` = '$meter_type' 
AND sd.`sub_div_code` = '$sub_div' 
AND m.`id` NOT IN (SELECT DISTINCT md.`meter_id` FROM `meter_acceptance_details` md WHERE md.`flag` IN (1))";

    $params = Yii::$app->request->queryParams;
    //print_r(isset($params->Meter_Serial_Number));
    if(isset($params['Meter_Serial_Number']) && $params['Meter_Serial_Number']!==''){
        $query.="AND WHERE (ins.`meter_msn`='".$params['Meter_Serial_Number']."')";
        $sqlCount="AND WHERE (ins.`meter_msn`='".$params['Meter_Serial_Number']."')";
    }
    if(isset($params['Sub_Division_Name'])&&$params['Sub_Division_Name']!==''){
        $query.="AND WHERE (sd.`name`='".$params['Sub_Division_Name']."')";
        $sqlCount.="AND WHERE (sd.`name`='".$params['Sub_Division_Name']."')";
    }
    //print_r($query);
    $count = Yii::$app->db->createCommand($sqlCount)->queryScalar();

    $session = Yii::$app->session;
    $session->set('total', $count);


    if($count <= 0)
    {
        $this->findModel($id)->delete();

        \Yii::$app->getSession()->setFlash('errors', '
       <div class="alert alert-error alert-dismissable">
       <button aria-hidden="true" data-dismiss="alert" class="close" 
       type="button">×</button>
       <strong>There are no meters installed against the selected Sub Division!!!! </strong>Acceptance is not Created</div>');


        return $this->redirect(['index', 'id' => $model->id]);
    }
    else
    {
        $dataProvider = new SqlDataProvider([
            'sql' => $query,
            'totalCount' => $count,
            'pagination' => false,
        ]);


        return $this->render('viewcreated', [
            'dataProvider' => $dataProvider,
            'model' =>$model,
            'id' => $model->id

        ]);
    }
}

查看

$this->title = $model->id;
$this->title = 'Meter Acceptance Form';
$this->params['breadcrumbs'][] = $this->title;
.
.
.
<?php Pjax::begin(); ?>
        <?= DetailView::widget([
            'model' => $model,
            'attributes' => [

                [
                        'label'=>'Serial #',
                         'value' => function($d)
                         {
                             return $d->id;
                         }
                ],
                [
                    'label' => 'Meter Type',
                    'value' => function ($d) {
                        if(is_object($d))
                            return $d->meter_type;
                        return ' - ';
                    },


                ],
                'sub_div',
                [
                    'label' => 'Sub Division Name',
                    'value' => function ($d) {
                        if(is_object($d))
                            return $d->subDiv->name;
                        return '-';
                    },


                ],
                [
                    'label' => 'Prepared By',
                    'value' => function ($d) {
                        if(is_object($d))
                            return $d->prepared->name;
                    },


                ],
                'prepared_at',

                'status',


            ],
        ]) ?>
  .
  .
  .
<?php Pjax::end(); ?>
  .
  .
  .
<a href="<?= URL::toRoute(['meteracceptanceheader/viewprocess', 'id'=>$model->id])?>" name="redirect" class="btn btn-primary" id="myid">Submit</a>

当我按下 Submit 按钮时,出现以下错误

PHP Notice 'yii\base\ErrorException' with message 'Undefined variable: model'

in E:\xampp\htdocs\inventory-web\backend\views\meteracceptanceheader\viewcreated.php:17

而第 17 行是 $this->title = $model->id;

我怎样才能摆脱这个问题?

更新 1

通过 print_r($model); exit(); 我得到了以下结果

common\models\MeterAcceptanceHeader Object ( [_attributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 1 [sub_div] => 37111 [meter_type] => L.T.TOU [prepared_by] => 12 [prepared_at] => 2018-08-03 08:39:22 [updated_at] => [status] => Prepared ) [_oldAttributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 1 [sub_div] => 37111 [meter_type] => L.T.TOU [prepared_by] => 12 [prepared_at] => 2018-08-03 08:39:22 [updated_at] => [status] => Prepared ) [_related:yii\db\BaseActiveRecord:private] => Array ( ) [_errors:yii\base\Model:private] => [_validators:yii\base\Model:private] => [_scenario:yii\base\Model:private] => default [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( ) )

更新二:

查看进程控制器

/**
 * @param $id
 * @return \yii\web\Response
 * @throws NotFoundHttpException
 * @throws \Exception
 * @throws \yii\db\StaleObjectException
 */
public function actionViewprocess($id)
{
    $model = $this->findModel($id);
    $accpt_id = $model->id;
    $meter_type = $model->meter_type;
    $ogp_sub_div = $model->sub_div;


    if(Yii::$app->request->isAjax && Yii::$app->request->post())
    {
        $data = explode(',',$_POST['data']);

        foreach($data as $value)
        {

            $m = new MeterAcceptanceDetails;
            $m -> load(Yii::$app->request->post());

            $m->accpt_id = $accpt_id;
            $m->meter_type = $meter_type;
            $m->created_at = date('Y-m-d H:i:s');
            $m->meter_id = $value;
            $m->meter_msn = \common\models\Meters::idTomsn($value);
            $m->flag = 1;// 1 means created
            $m->ogp_sub_div = $ogp_sub_div;

            if($m->save())
            {
                $model->status = MeterAcceptanceHeader::$status_titles[1];
                $model->update();

            }
            else{
                $this->renderAjax('viewcreated');
            }
        }

    }
    else{
        $this->renderAjax('viewcreated');
    }
    $query = /** @lang text */
        "SELECT DISTINCT a.`id` AS Accpt_Id,u.`name` AS Prepared_By,b.`meter_msn` AS Meter_Serial_Number, b.`meter_type` AS Meter_Type, 
        sd.`name` AS Sub_Div_Name,DATE(b.`created_at`) AS 'Date' FROM 
        `meter_acceptance_header` a
        INNER JOIN `meter_acceptance_details` b ON a.`id` = b.`accpt_id`
        INNER JOIN `survey_hesco_subdivision` sd ON b.`ogp_sub_div` = sd.`sub_div_code`
        INNER JOIN `user` u ON a.`prepared_by` = u.`id` 
        WHERE b.`accpt_id` =$accpt_id AND b.`meter_type` = '$meter_type'";


    return $this->redirect(Url::toRoute(['meteracceptanceheader/viewprocess','id' => $model->id, 'model' => $this->findModel($id)]));

}

查看进程视图

$this->title = $model->id;
$this->title = 'Meter Acceptance';
$this->params['breadcrumbs'][] = $this->title;

<section class="content-header">
<h1>Meter Acceptance</h1>
</section>
<section class="content">
<div class="box">
    <div class="box-body">
      <?= GridView::widget([
         'dataProvider' => $dataProvider,
       'columns' => [

           ['class' => 'yii\grid\SerialColumn'],
           [
               'label'=>'Serial #',
               'value' => 'Accpt_Id'
           ],

           'Date',
           'Prepared_By',
           'Meter_Serial_Number',
           'Meter_Type',
           'Sub_Div_Name',
 ],
]); ?>
    </div>
</div>
</section>

非常感谢任何帮助。

您的模型很可能不包含包含字段描述的 phodoc 注释。 IE。在你的模型 class 之上,你应该有这样的评论:

/**
* This is the model class for table "applications".
*
* @property integer $id
* @property integer $someotherfield
*/

注意:您有 posted 控制器代码,但根据 MVC 原则,那里的功能属于模型。如果此评论没有帮助,请 post 还有您的型号代码。

您正在使用锚 link 提交给 viewprocess

<a href="<?= URL::toRoute(['meteracceptanceheader/viewprocess', 'id'=>$model->id])?>" name="redirect" class="btn btn-primary" id="myid">Submit</a>

解析为 GET 请求,然后在 actionViewprocess 中您正在检查

if(Yii::$app->request->isAjax && Yii::$app->request->post())

解析为 false,控制转到您调用

的 else 部分
$this->renderAjax('viewcreated') 

,这是主要问题,您没有通过所需的视图传递 $model,因此在第一行给您错误

$this->title = $model->id; 

这也是例外情况,如果您尝试从另一个操作呈现它,则应该传递视图的所有必需变量,或者 redirect 传递给该操作而不是使用 renderAjax()