Undefined variable: yii2

假如想象 提交于 2019-12-12 04:19:05

问题


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>";
        }
    }

}

回答1:


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
        ]);



回答2:


$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];
}



回答3:


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).




回答4:


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,
]) ?>



回答5:


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.



来源:https://stackoverflow.com/questions/34946322/undefined-variable-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!