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

时间:2018-08-03 05:33:32

标签: php model yii2 undefined yii2-advanced-app

我正在研究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通知“ yii \ base \ ErrorException”,并显示消息“未定义变量:模型”

     

在   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 ( ) )

更新2:

查看流程控制器

/**
 * @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>

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您正在使用锚点链接提交到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(),则应该传递视图所需的所有变量。

答案 1 :(得分:-2)

您的模型很可能不包含包含字段描述的phodoc注释。就是在模型类的顶部,您应该有这样的注释:

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

注意:您已经发布了控制器代码,但是根据MVC原理,那里的功能属于模型。如果此评论没有帮助,请同时发布您的模型代码。