Undefined variable: yii2

2019-09-09 16:41发布

enter image description here Getting error when I am trying to create dynamic form in using yii2-dynamicform. at the time of create method it is working fine but at the time of update showing the error. I have two tables one is 1.vendors & 2.vendors_more_categories

Relation is 1-* between vendors & vendors_more_categories I just refereed https://github.com/wbraganca/yii2-dynamicform this link.

<?php

namespace app\controllers;
namespace backend\controllers;
use Yii;
use app\models\Vendors;
use app\models\VendorsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\filters\AccessControl;
use app\models\VendorsMoreCategories;
use backend\models\Model;
use yii\web\Response;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
/**
 * VendorsController implements the CRUD actions for Vendors model.
 */
class VendorsController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['index','create', 'update', 'delete'],
                'rules' => [
                    [
                        'actions' => ['index','create', 'update', 'delete'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Vendors models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new VendorsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Vendors model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Vendors model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Vendors();
        $modelsVendorsMoreCategories = [new VendorsMoreCategories];
        if($model->load(Yii::$app->request->post())){        

            $modelsVendorsMoreCategories = Model::createMultiple(VendorsMoreCategories::classname());
            Model::loadMultiple($modelsVendorsMoreCategories, Yii::$app->request->post());


            // validate all models
            $valid = $model->validate();
            $valid = Model::validateMultiple($modelsVendorsMoreCategories) && $valid;

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();
                try {
                    if ($flag = $model->save(false)) {
                        foreach ($modelsVendorsMoreCategories as $modelVendorsMoreCategories) {
                            $modelVendorsMoreCategories->vmc_ven_id = $model->ven_id;
                            if (! ($flag = $modelVendorsMoreCategories->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }
                    }
                    if ($flag) {
                        $transaction->commit();

                        $model->file = UploadedFile::getInstance($model, 'file');
                        $save_file = '';
                        if($model->file){
                            $imagename = Vendors::find()->orderBy('ven_id DESC')->one();
                            $imagename=$imagename->ven_id+1;
                            $imagepath = 'images/imgvendors/'; // Create folder under web/uploads/logo
                            $model->ven_business_logo = $imagepath.$imagename.'.'.$model->file->extension;
                            $save_file = 1;
                        }
                        if ($model->save(false)) {
                            if($save_file){
                                $model->file->saveAs($model->ven_business_logo);
                            }
                            return $this->redirect(['view', 'id' => $model->ven_id]);
                        }                        
                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }            
        }else {
            return $this->render('create', [
                'model' => $model,
                'modelsVendorsMoreCategories' => (empty($modelsVendorsMoreCategories)) ? [new VendorsMoreCategories] : $modelsVendorsMoreCategories
            ]);
        }
    }

    /**
     * Updates an existing Vendors model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        //print_r($model->attributes);

        $modelsVendorsMoreCategories = $model->ven_id;   

        if($model->load(Yii::$app->request->post())){          
            $oldIDs = ArrayHelper::map($modelsVendorsMoreCategories, 'id', 'id');
            $modelsVendorsMoreCategories = Model::createMultiple(VendorsMoreCategories::classname(), $modelsVendorsMoreCategories);
            Model::loadMultiple($modelsVendorsMoreCategories, Yii::$app->request->post());
            $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsVendorsMoreCategories, 'id', 'id')));

            // validate all models
            $valid = $model->validate();
            $valid = Model::validateMultiple($modelsVendorsMoreCategories) && $valid;

            if ($valid) {
                $transaction = \Yii::$app->db->beginTransaction();
                try {
                    if ($flag = $model->save(false)) {
                        if (! empty($deletedIDs)) {
                            Address::deleteAll(['id' => $deletedIDs]);
                        }
                        foreach ($modelsVendorsMoreCategories as $modelVendorsMoreCategories) {
                            $modelVendorsMoreCategories->vmc_ven_id = $model->ven_id;
                            if (! ($flag = $modelVendorsMoreCategories->save(false))) {
                                $transaction->rollBack();
                                break;
                            }
                        }
                    }
                    if ($flag) {
                        $transaction->commit();
                        $model->file = UploadedFile::getInstance($model, 'file');
                        $save_file = '';
                        if($model->file){
                            $imagepath = 'images/imgvendors/'; // Create folder under web/uploads/logo
                            $model->ven_business_logo = $imagepath.$model->ven_id.'.'.$model->file->extension;
                            $save_file = 1;
                        }

                        if ($model->save(false)) {
                            if($save_file){
                                $model->file->saveAs($model->ven_business_logo);
                            }
                            return $this->redirect(['view', 'id' => $model->ven_id]);
                        }                        

                    }
                } catch (Exception $e) {
                    $transaction->rollBack();
                }
            }

        }else {
            return $this->render('update', [
                'model' => $model,
                'modelsVendorsMoreCategories' => (empty($modelsVendorsMoreCategories)) ? [new VendorsMoreCategories] : $modelsVendorsMoreCategories
            ]);
        }
    }

    /**
     * Deletes an existing Vendors model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Vendors model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Vendors the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Vendors::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    //Function used for deleting the images
    public function actionDeleteimg($id, $field)
    {

        $img = $this->findModel($id)->$field;
        if($img){
            if (!unlink($img)) {
                return false;
            }
        }

        $img = $this->findModel($id);
        $img->$field = NULL;
        $img->update();

        return $this->redirect(['update', 'id' => $id]);
    }
    //Function used for getting more sub categories for vendor
    public function actionGetSubCategories()
    {
        $mbcid=$_GET['ven_main_category_id'];
        $sbcid=$_GET['ven_sub_category_id'];
        echo $mbcid;
    }
    public function actionLists($id)
    {
        $countVendors = Vendors::find()->where(['ven_contact_person_id' => $id])->count();
        $vendors = Vendors::find()->where(['ven_contact_person_id' => $id])->all();
        if ($countVendors > 0) {
            foreach ($vendors as $vendor) {
                echo "<option value='" . $vendor->ven_id . "'>" . $vendor->ven_company_name . "</option>";
            }
        } else {
            echo "<option></option>";
        }
    }

}

5条回答
女痞
2楼-- · 2019-09-09 17:12

Check your create.php file in view folder, pass required variable on _form.php file from here as:-

 <?= $this->render('_form', [
    'model' => $model,
    'modelsAddress' => $modelsAddress,
]) ?>
查看更多
手持菜刀,她持情操
3楼-- · 2019-09-09 17:26

$modelsVendorsMoreCategories should contain the VendorsMoreCategories model in actionUpdate method. In this code ($modelsVendorsMoreCategories = $model->ven_id) $modelsVendorsMoreCategories contains $model->ven_id. It is an integer value, not the VendorsMoreCategories object.

The Vendors model should contain a relation on the VendorsMoreCategories model:

class Vendors extends \yii\db\ActiveRecord 
{
    ....
    public function getVendorsMoreCategories() 
    {
        return $this->hasMany(VendorsMoreCategories::className(), 'vendor_id'=>'id']);
    }
}

And then, you should use that relation in your actionUpdate method:

$model = $this->findModel($id);

$modelsVendorsMoreCategories = $model->vendorsMoreCategories;
if(!$modelsVendorsMoreCategories) {
    $modelsVendorsMoreCategories = [new VendorsMoreCategories];
}
查看更多
劳资没心,怎么记你
4楼-- · 2019-09-09 17:30

Check Your create file in view folder:

Controller: Controller pass the parameter into create.php

 return $this->render('create', [
            'model' => $model,
            'modelsVendorsMoreCategories' => (empty($modelsVendorsMoreCategories)) ? [new VendorsMoreCategories] : $modelsVendorsMoreCategories
        ]);

View:create.php

If You miss the parameter: 'modelsVendorsMoreCategories' =>$modelsVendorsMoreCategories. It shows the Undefined variable error in _form.php page.

<?= $this->render('_form', [
            'model' => $model,
            'modelsVendorsMoreCategories' =>$modelsVendorsMoreCategories
 ])?>

View:_form.php

$modelsVendorsMoreCategories[0];

the paramater not passing before now it passing.

查看更多
Animai°情兽
5楼-- · 2019-09-09 17:31

In your actionUpdate you have:

$modelsVendorsMoreCategories = $model->ven_id;

But you should have:

$modelsVendorsMoreCategories = $model->nameOfMyRelation;

To get what's the real name, go in your $model, and look for something like:

/**
 * @return \yii\db\ActiveQuery
 */
public function getNameOfMyRelation()
{
    return $this->hasMany(VendorsMoreCategories::className(), ['ven_id' => 'id']);
}

If you don't have any function making the relation of this two tables, write one. If you having trouble doing that, you can always use the gii's model generator and check the Vendors model (you dont need to replace it, just preview the code).

查看更多
The star\"
6楼-- · 2019-09-09 17:32

You accessing modelsVendorsMoreCategories[0] (as an element of an array )

  'model'=> $modelsVendorsMoreCategories[0], 

in your DinamicForm widget but when you update the model you pass as $modelsVendorsMoreCategories this value

   $modelsVendorsMoreCategories = $model->ven_id;  

(don't seems an array, you must be sure this object contain an array with a proper element in 0 index))

'modelsVendorsMoreCategories' => (empty($modelsVendorsMoreCategories)) ? 
       [new VendorsMoreCategories] : $modelsVendorsMoreCategories
        ]);
查看更多
登录 后发表回答