2amigos / yii2-gallery-widget

BlueImp Gallery Widget for Yii2
http://yiiwheels.com
Other
60 stars 37 forks source link

Create gallery from database. #22

Open djnordeen opened 6 years ago

djnordeen commented 6 years ago

Hello, I am having trouble creating a gallery from a database. Could you give me an example. I have passed data to the view but do not know how to format it for the widget. Database field are: id, url, src, options, imageOptions.

Thanks

rossaddison commented 5 years ago
//yii2 controller
<?php

namespace frontend\controllers;

use Yii;
use yii\helpers\Url;
use frontend\models\Carousal;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

/**
 * CarousalController implements the CRUD actions for Carousal model.
 */
class CarousalController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
           'access' => 
                            [
                            'class' => \yii\filters\AccessControl::className(),
                            'only' => ['index','create', 'update','delete','view'],
                            'rules' => [
                            [
                              'allow' => true,
                             // 'roles' => ['employee','admin']
                             'roles' => ['@'],
                            ],
                            [
                              'allow' => true,
                              'verbs' => ['POST']
                            ],  
                            ],
            ], 
        ];
    }

    /**
     * Lists all Carousal models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Carousal::find(),
        ]);
        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

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

    /**
     * Creates a new Carousal model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
        {

          $model = new Carousal();
          if ($model->load(Yii::$app->request->post())) {
              $uploadedFile = UploadedFile::getInstance($model, 'image');
              if (!is_null($uploadedFile)) {
                    $model->image_source_filename = $uploadedFile->name;
                    $model->image_web_filename = Yii::$app->security->generateRandomString().".".$uploadedFile->extension;
                    if ($model->validate()) {                
                        Yii::$app->params['uploadPath'] = dirname(Yii::$app->basePath) .'\images';
                        ///Yii::$app->params['uploadPath'] = Yii::$app->basePath .'\web\images';
                        $path = Yii::$app->params['uploadPath'] .'/'. $model->image_web_filename;   
                        $uploadedFile->saveAs($path); 
                    }                   
                  }
                if ($model->save())
                    {
                      return $this->redirect(['view', 'id' => $model->id]);
                    }

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

   public function actionUpdate($id)
        {
          if (!\Yii::$app->user->can('Update Carousal')) {
            throw new \yii\web\ForbiddenHttpException('You do not have permission to update the carousal.');
          }

          $model = $this->findModel($id);
          if ($model->load(Yii::$app->request->post())) {
              $uploadedFile = UploadedFile::getInstance($model, 'image');
              if (!is_null($uploadedFile)) {
                    $model->image_source_filename = $uploadedFile->name;
                    $model->image_web_filename = Yii::$app->security->generateRandomString().".".$uploadedFile->extension;
                    if ($model->validate()) {
                        Yii::$app->params['uploadPath'] = dirname(Yii::$app->basePath) .'\images';
                        //Yii::$app->params['uploadPath'] = Yii::$app->basePath .'\web\images';
                        $path = Yii::$app->params['uploadPath'] .'/'. $model->image_web_filename;   
                        $uploadedFile->saveAs($path); 
                    }                   
                  }
                if ($model->save())
                    {
                      return $this->redirect(['view', 'id' => $model->id]);
                    }

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

    protected function findModel($id)
    {
        if (($model = Carousal::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionDelete($id)
    {
        if (!\Yii::$app->user->can('Delete Carousal')) {
            throw new \yii\web\ForbiddenHttpException('You do not have permission to delete a carousal.');
        }

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

//yii2 model
<?php

namespace frontend\models;

use Yii;

class Carousal extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */

    public $image;

    public static function tableName()
    {
        return 'carousal';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            //[[ 'image_source_filename','image_web_filename', 'image','content_alt', 'content_title', 'content_caption'], 'required'],
            [['image'], 'safe'],
            //[['fontcolor'],'default','white'],
            [['fontcolor'],'string','max' => 20],
            [['image_source_filename','image_web_filename','content_alt', 'content_title', 'content_caption'], 'string', 'max' => 255],
            [['image'], 'file','skipOnEmpty' => true, 'maxSize' => 2000000,'tooBig' => 'The picture cannot be larger than 2MB.', 'extensions'=>'jpg, gif, png','wrongExtension' => 'The file must be a JPG, GIF or PNG.'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'image_source_filename' => 'Client-side Filename',
            'image_web_filename' => 'Server-side Filename',
            'content_alt' => 'Content Alt',
            'content_title' => 'Content Title',
            'content_caption' => 'Content Caption',
        ];
    }

//view 
<?php 
                $images = [];
                $images = Carousal::find()->all();
                $items = [];
                foreach ($images as $key => $value)
                    {
                    $items[$key]['url'] = '/images/'.$images[$key]['image_web_filename'];
                    $items[$key]['src'] = '/images/'.$images[$key]['image_web_filename'];
                    $items[$key]['imageOptions'] = ['height'=>100,'width'=>100];
                    $items[$key]['options'] = ['title'=>$images[$key]['content_title']];
                    }
            ?>

            <?= dosamigos\gallery\Gallery::widget(['items' => $items]);?>