255], [['image'], 'safe'], [['product_id'], 'exist', 'skipOnError' => true, 'targetClass' => Product::className(), 'targetAttribute' => ['product_id' => 'product_id']], [['image'], 'file', 'extensions'=>'jpg, gif, png'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'product_image_id' => Yii::t('product', 'Product Image ID'), 'product_id' => Yii::t('product', 'Product ID'), 'image' => Yii::t('product', 'Image'), 'alt' => Yii::t('product', 'Alt'), 'title' => Yii::t('product', 'Title'), ]; } /** * @return \yii\db\ActiveQuery */ public function getProduct() { return $this->hasOne(Product::className(), ['product_id' => 'product_id']); } /** * @inheritdoc * @return ProductImageQuery the active query used by this AR class. */ public static function find() { return new ProductImageQuery(get_called_class()); } /** * fetch stored image file name with complete path * @return string */ public function getImageFile() { return isset($this->image) ? Yii::$app->params['uploadPath'] . $this->image : null; } /** * fetch stored image url * @return string */ public function getImageUrl() { // return a default image placeholder if your source image is not found $image = isset($this->image) ? $this->image : 'default.jpg'; return Yii::$app->params['uploadUrl'] . $image; } /** * Process upload of image * * @return mixed the uploaded image instance */ public function uploadImage() { // get the uploaded file instance. for multiple file uploads // the following data will return an array (you may need to use // getInstances method) $image = UploadedFile::getInstance($this, 'image'); // if no image was uploaded abort the upload if (empty($image)) { return false; } // store the source file name $this->filename = $image->name; $ext = end((explode(".", $image->name))); // generate a unique file name $this->image = Yii::$app->security->generateRandomString().".{$ext}"; // the uploaded image instance return $image; } /** * Process deletion of image * * @return boolean the status of deletion */ public function deleteImage() { $file = $this->getImageFile(); // check if file exists on server if (empty($file) || !file_exists($file)) { return false; } // check if uploaded file can be deleted on server if (!unlink($file)) { return false; } // if deletion successful, reset your file attributes $this->image = null; $this->filename = null; return true; } }