Jass
Jass

Reputation: 4103

How to add custom new field in yii2 gii generated crud

I have made one CRUD in YII2 using Gii having 10 fields. In my mysql table there was logo column so Gii generated text field for it. I converted it to file field using the following code.

$form->field($model, 'manufacturer_logo')->fileInput()

Now I am not getting any clue where I can write controller side code so that I can save logo in folder and DB like other fields. There is no saving code in Gii generated controller. I tried to follow this but it also did not work.

In my model rules, I have written following line for valid image file.

public function rules()
    {
        return [
            [['manufacturer_description', 'manufacturer_status','manufacturer_logo'], 'string'],
            [['manufacturer_name','manufacturer_status','manufacturer_logo'], 'required'],
            [['manufacturer_logo'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
            [['created_at', 'updated_at'], 'safe'],
            [['manufacturer_name'], 'string', 'max' => 255],
        ];
    }

Now when I fill all fields and browse image as well and press submit then it gives me error "Please upload a file", here you can see so I am not able to upload image and save its name in DB column like other fields.

For further doing RND, Now image is saving in folder but not in database, Here I changed controller code.

public function actionCreate()
    {
        $model = new Manufacturers();
       
        if ($model->load(Yii::$app->request->post())) {

            //upload logo
            $base_path = Yii::getAlias('@app');
            //$model = new UploadForm();

            $imageFile = UploadedFile::getInstance($model,'manufacturer_logo');
            $logoName = "";
            if (isset($imageFile->size)) {
                $imageFile->saveAs($base_path . '/web/uploads/' . $imageFile->baseName . '.' . $imageFile->extension);
                $logoName = $imageFile->baseName . '.' . $imageFile->extension;
            }
            
            if(trim($logoName)!='') {
                $model->manufacturer_logo = trim($logoName);
            }
            
            $model->save(false);
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

Upvotes: 0

Views: 167

Answers (0)

Related Questions