示例#1
3
 public function actionViewAdvert($id)
 {
     $model = Advert::findOne($id);
     $data = ['name', 'email', 'text'];
     $model_feedback = new DynamicModel($data);
     $model_feedback->addRule('name', 'required');
     $model_feedback->addRule('email', 'required');
     $model_feedback->addRule('text', 'required');
     $model_feedback->addRule('email', 'email');
     if (Yii::$app->request->isPost) {
         if ($model_feedback->load(Yii::$app->request->post()) && $model_feedback->validate()) {
             Yii::$app->common->sendMail('Subject Advert', $model_feedback->text);
         }
     }
     $user = $model->user;
     $images = Common::getImageAdvert($model, false);
     $current_user = ['email' => '', 'username' => ''];
     if (!Yii::$app->user->isGuest) {
         $current_user['email'] = Yii::$app->user->identity->email;
         $current_user['username'] = Yii::$app->user->identity->username;
     }
     $coords = str_replace(['(', ')'], '', $model->location);
     $coords = explode(',', $coords);
     $coord = new LatLng(['lat' => $coords[0], 'lng' => $coords[1]]);
     $map = new Map(['center' => $coord, 'zoom' => 15]);
     $marker = new Marker(['position' => $coord, 'title' => Common::getTitleAdvert($model)]);
     $map->addOverlay($marker);
     return $this->render('view_advert', ['model' => $model, 'model_feedback' => $model_feedback, 'user' => $user, 'images' => $images, 'current_user' => $current_user, 'map' => $map]);
 }
 public function testValidateAttribute()
 {
     $this->tester->haveInCollection(Number::collectionName(), ['number' => '9101234567']);
     $this->specify("Test validate", function ($number, $expected) {
         $this->model['number'] = $number;
         $this->model->validate(['number']);
         $this->tester->assertEquals($expected, $this->model->hasErrors());
     }, ['examples' => [['9101234567', false], ['1111111111', true], ['9121111111', true]]]);
 }
示例#3
0
 public function actionStock()
 {
     $debug = '';
     $model = new DynamicModel(['vins', 'diller']);
     $model->addRule('vins', 'string')->addRule('diller', 'integer')->addRule(['diller', 'vins'], 'required');
     $list = ArrayHelper::map(Mod\cats\Stock::find()->all(), 'id', 'name');
     $prompt = Yii::t('app', 'Select stock');
     $arrError = [];
     if ($model->load(Yii::$app->request->post()) && $model->validate()) {
         $arrvin = explode("\n", $model->vins);
         foreach ($arrvin as $vin) {
             if ($car = Mod\Car::findOne(['vin' => trim($vin)])) {
                 $status = Mod\CarStatus::findOne(['car_id' => $car->id]);
                 $status->stock_id = $model->diller;
                 $status->save();
             } else {
                 $arrError[] = $vin . ' не найден VIN';
             }
         }
         //			$debug = print_r($arrError, true);
         $debug = implode('<br>', $arrError);
         return $this->render('finish', ['debug' => $debug]);
     }
     $arrVars = ['model' => $model, 'list' => $list, 'prompt' => $prompt, 'selLabel' => 'Склад', 'title' => 'Пакетное перемещение'];
     return $this->render('index', $arrVars);
 }
 public function actionVerify()
 {
     $session = Yii::$app->session;
     $urlKey = $this->filter->buildKey('_url');
     $urls = $session->get($urlKey);
     if (is_array($urls) && isset($urls[0], $urls[1])) {
         $route = $urls[0];
         $returnUrl = $urls[1];
     } else {
         throw new \yii\base\InvalidCallException();
     }
     $key = $this->filter->buildKey($route);
     $field = 'f' . substr($key, 0, 10);
     $model = new DynamicModel([$field]);
     $model->addRule($field, 'required');
     if ($model->load(Yii::$app->getRequest()->post()) && $model->validate()) {
         if ($this->filter->isValid($model->{$field}, $route)) {
             $this->filter->setValid($route);
             return Yii::$app->getResponse()->redirect($returnUrl);
         } else {
             $model->addError($field, $this->filter->message);
         }
     }
     return $this->render($this->viewFile, ['model' => $model, 'field' => $field]);
 }
示例#5
0
    public function run()
    {
        $data = ['name', 'email', 'text'];
        $model_feedback = new DynamicModel($data);
        $model_feedback->addRule('name', 'required');
        $model_feedback->addRule('email', 'required');
        $model_feedback->addRule('text', 'required');
        $model_feedback->addRule('email', 'email');

        if (Yii::$app->request->isPost) {
            if ($model_feedback->load(Yii::$app->request->post()) && $model_feedback->validate()) {
                Yii::$app->common->sendMail('Subject Advert', $model_feedback->text);
            }
        }

        $current_user = ['email' => '', 'username' => ''];

        if (!Yii::$app->user->isGuest) {
            $current_user['email'] = Yii::$app->user->identity->email;
            $current_user['username'] = Yii::$app->user->identity->username;
        }

        return $this->render('feedback', [
            'model_feedback' => $model_feedback,
            'current_user' => $current_user
        ]);
    }
 public function actionData($file = false)
 {
     \Yii::$app->response->format = Response::FORMAT_JSON;
     if (\Yii::$app->request->isPost) {
         /**@var Module $module */
         $module = Module::getInstance();
         $model = new DynamicModel(['file' => null]);
         $model->addRule('file', 'file', ['extensions' => $module->expansions, 'maxSize' => $module->maxSize]);
         $model->file = UploadedFile::getInstanceByName('image');
         if ($model->validate()) {
             if (!is_dir(\Yii::getAlias($module->uploadDir))) {
                 FileHelper::createDirectory(\Yii::getAlias($module->uploadDir));
             }
             $oldFileName = $model->file->name;
             $newFileName = $module->isFileNameUnique ? uniqid() . '.' . $model->file->extension : $oldFileName;
             $newFullFileName = \Yii::getAlias($module->uploadDir) . DIRECTORY_SEPARATOR . $newFileName;
             if ($model->file->saveAs($newFullFileName)) {
                 return ['id' => $oldFileName, 'url' => \Yii::$app->request->getHostInfo() . str_replace('@webroot', '', $module->uploadDir) . '/' . $newFileName];
             }
         } else {
             \Yii::$app->response->statusCode = 500;
             return $model->getFirstError('file');
         }
     } elseif (\Yii::$app->request->isDelete && $file) {
         return true;
     }
     throw new BadRequestHttpException();
 }
示例#7
0
 /**
  * 
  * @return type
  * @throws BadRequestHttpException
  */
 public function run()
 {
     if (Yii::$app->request->isPost) {
         if (!empty($this->getParamName) && Yii::$app->getRequest()->get($this->getParamName)) {
             $this->paramName = Yii::$app->getRequest()->get($this->getParamName);
         }
         $file = UploadedFile::getInstanceByName($this->paramName);
         $model = new DynamicModel(compact('file'));
         $model->addRule('file', $this->_validator, $this->validatorOptions);
         if ($model->validate()) {
             if ($this->unique === true) {
                 $model->file->name = uniqid() . (empty($model->file->extension) ? '' : '.' . $model->file->extension);
             }
             $result = $model->file->saveAs($this->path . $model->file->name) ? ['key' => $model->file->name, 'caption' => $model->file->name, 'name' => $model->file->name] : ['error' => 'Can\'t upload file'];
         } else {
             $result = ['error' => $model->getErrors()];
         }
         if (Yii::$app->getRequest()->isAjax) {
             Yii::$app->response->format = Response::FORMAT_JSON;
         }
         return $result;
     } else {
         throw new BadRequestHttpException('Only POST is allowed');
     }
 }
 /**
  * 上传示例
  *
  * @return string
  */
 public function actionUpload()
 {
     $model = new DynamicModel(['image' => '']);
     // 动态添加验证规则!
     $model->addRule(['image'], 'file', ['extensions' => 'jpeg,jpg, gif, png']);
     //  $model->addRule(['image',], 'required', ['message' => '亲 上传一个文件呢?',]);
     // post 请求才可能上传文件
     if (Yii::$app->request->getIsPost()) {
         if ($model->validate()) {
             // 验证通过了 在上传
             /*
              * 参考官方的解决方案
              * @see http://flysystem.thephpleague.com/recipes/
              *
             $file = UploadedFile::getInstanceByName($uploadname);
             
             if ($file->error === UPLOAD_ERR_OK) {
                 $stream = fopen($file->tempName, 'r+');
                 $filesystem->writeStream('uploads/'.$file->name, $stream);
                 fclose($stream);
             }
             */
             $file = UploadedFile::getInstance($model, 'image');
             if ($file->error === UPLOAD_ERR_OK) {
                 $stream = fopen($file->tempName, 'r+');
                 $fileName = 'files/' . time() . $file->name;
                 Yii::$app->fs->writeStream($fileName, $stream);
                 fclose($stream);
                 $result = '';
                 // 是否上传成功?
                 if (Yii::$app->fs->has($fileName)) {
                     /**
                      * $file = file_get_contents('d:/a.jpg');
                      * header('Content-type: image/jpeg');
                      * echo $file;
                      */
                     // 图片文件的内容嵌入到img 中: http://stackoverflow.com/search?q=html+image+data+base64
                     // @see http://stackoverflow.com/questions/1124149/is-embedding-background-image-data-into-css-as-base64-good-or-bad-practice
                     // TODO 这里文件的mime 可以用它文件系统组件来探测!
                     $img = Html::img('data:image/gif;base64,' . base64_encode(Yii::$app->fs->read($fileName)), ['width' => '300px']);
                     // 删除掉所上传的文件
                     // 轻轻的我走了正如我轻轻的来 挥一挥手 不留下一点垃圾!
                     Yii::$app->fs->delete($fileName);
                     $result = '上传的图片: ' . $img . '<br/>上传成功 文件已被删除了';
                 } else {
                     $result = '上传失败 ';
                 }
                 $result .= '<br/> ' . Html::a('重新上传', [''], []);
                 // 演示renderContent方法
                 return $this->renderContent($result);
             }
         }
     }
     return $this->render('upload', ['model' => $model]);
 }
示例#9
0
 public function actionLanguage()
 {
     $model = new DynamicModel(['language']);
     $model->addRule(['language'], 'required');
     $model->setAttributes(['language' => Yii::$app->session->get('language', 'en')]);
     if ($model->load(Yii::$app->request->post()) && $model->validate()) {
         Yii::$app->session->set('language', $model->language);
         return $this->redirect(['db-config']);
     }
     return $this->render('language', ['languages' => InstallerHelper::getLanguagesArray(), 'model' => $model]);
 }
示例#10
0
 /**
  * Lists all Post models.
  * @return mixed
  */
 public function actionIndex()
 {
     $postSearchForm = new DynamicModel(['search']);
     $postSearchForm->addRule('search', 'string', ['length' => [3, 255], 'tooShort' => 'Поиск должен содержать минимум 3 символа.']);
     $query = Post::find()->distinct()->joinWith('categories')->where(['post.status' => 1])->orderBy('created DESC');
     $request = Yii::$app->request;
     $query->filterWhere(['category_id' => $request->getQueryParam('category')]);
     if ($postSearchForm->load($request->queryParams, '') && $postSearchForm->validate()) {
         $query->andFilterWhere(['OR', ['LIKE', 'title', $request->getQueryParam('search')], ['LIKE', 'anotation', $request->getQueryParam('search')], ['LIKE', 'text', $request->getQueryParam('search')]]);
     }
     $countQuery = clone $query;
     $pages = new Pagination(['totalCount' => $countQuery->count(), 'pageSize' => 3]);
     $models = $query->offset($pages->offset)->limit($pages->limit)->all();
     return $this->render('index', ['models' => $models, 'pages' => $pages, 'postSearchForm' => $postSearchForm]);
 }
 /**
  * Lists all Setting models.
  * @return mixed
  */
 public function actionIndex()
 {
     $tabs = (new Query())->select('group')->from('{{%core_setting}}')->orderBy('key_order')->distinct()->column();
     $attributes = (new Query())->select('key')->from('{{%core_setting}}')->orderBy('key_order')->column();
     //var_dump($tabs);
     $model = new DynamicModel($attributes);
     $settings = [];
     foreach ($attributes as $attribute) {
         $setting = Setting::find()->where(['key' => $attribute])->asArray()->one();
         $settings[$setting['group']][$attribute] = $setting;
         $model->{$attribute} = $setting['value'];
         //$model->la
         if (!empty($rules = json_decode($setting['rules'], true))) {
             foreach ($rules as $rule => $conf) {
                 //var_dump($conf);
                 $model->addRule($attribute, $rule, $conf);
             }
         } else {
             $model->addRule($attribute, 'required');
         }
     }
     if ($model->load(Yii::$app->request->post()) && $model->validate()) {
         foreach ($attributes as $attribute) {
             $s = Setting::findOne($attribute);
             $s->value = $model->{$attribute};
             if ($s->save(false)) {
                 Yii::$app->session->setFlash('success', Yii::t('app', 'Settings saved successfully.'));
             } else {
                 Yii::$app->session->setFlash('error', Yii::t('app', 'Sorry, something went wrong. {ERRORS}.', ['ERRORS' => json_encode($s->errors)]));
                 break;
             }
         }
         return $this->redirect(['index']);
     }
     return $this->render('index', ['model' => $model, 'settings' => $settings, 'tabs' => $tabs]);
 }
示例#12
0
 public function actionViewAdvert($id)
 {
     $model = Advert::findOne($id);
     $data = ['name', 'email', 'text'];
     $model_feedback = new DynamicModel($data);
     $model_feedback->addRule('name', 'required');
     $model_feedback->addRule('email', 'required');
     $model_feedback->addRule('text', 'required');
     $model_feedback->addRule('email', 'email');
     if (\Yii::$app->request->isPost) {
         if ($model_feedback->load(\Yii::$app->request->post()) && $model_feedback->validate()) {
             \Yii::$app->common->sendMail('Subject Advert', $model_feedback->text);
         }
     }
     $user = $model->user;
     $images = Common::getImageAdvert($model, false);
     $current_user = ['email' => '', 'username' => ''];
     if (!\Yii::$app->user->isGuest) {
         $current_user['email'] = \Yii::$app->user->identity->email;
         $current_user['username'] = \Yii::$app->user->identity->username;
     }
     return $this->render('view_advert', ['model' => $model, 'model_feedback' => $model_feedback, 'user' => $user, 'images' => $images, 'current_user' => $current_user]);
 }
示例#13
0
 public function actionTempFile()
 {
     $model = new DynamicModel(['nama', 'file_id']);
     // behavior untuk upload file
     $model->attachBehavior('upload', ['class' => 'mdm\\upload\\UploadBehavior', 'attribute' => 'file', 'savedAttribute' => 'file_id']);
     // rule untuk model
     $model->addRule('nama', 'string')->addRule('file', 'file', ['extensions' => 'txt']);
     if ($model->load(Yii::$app->request->post()) && $model->validate()) {
         if ($model->saveUploadedFile() !== false) {
             Yii::$app->session->setFlash('success', 'Upload Sukses');
         }
     }
     return $this->render('upload-manifest', ['model' => $model]);
 }
示例#14
0
 public function actionBook($id)
 {
     $model = new Booking();
     $bookingModelAttributes = ['group_num', 'agency_id'];
     $customFieldsAttributes = array_map(function ($item) {
         return 'field' . $item['id'];
     }, $this->findModel($id)->getFields()->all());
     $dynamicModelAttributes = array_merge($bookingModelAttributes, $customFieldsAttributes);
     $dynamicModel = new DynamicModel($dynamicModelAttributes);
     $dynamicModel->addRule($dynamicModelAttributes, 'required');
     if ($dynamicModel->load(Yii::$app->request->post()) && $dynamicModel->validate()) {
         $attributes = $dynamicModel->getAttributes($bookingModelAttributes);
         $model->link('tour', $this->findModel($id));
         $model->agency_id = $attributes['agency_id'];
         $model->group_num = $attributes['group_num'];
         $model->time = time();
         if ($model->validate()) {
             $fields = [];
             $keys = ['booking_id', 'tour_id', 'field_id', 'value'];
             foreach ($dynamicModel->getAttributes($customFieldsAttributes) as $key => $field) {
                 if (in_array($key, $customFieldsAttributes)) {
                     $fields[] = [$model->id, $id, str_replace('field', '', $key), $field];
                 }
             }
             if (!empty($fields)) {
                 Yii::$app->db->createCommand()->batchInsert('booking_fields', $keys, $fields)->execute();
                 $model->save();
                 return $this->redirect('/booking');
             }
         } else {
             var_dump($model);
             $model->delete();
         }
     }
     return $this->render('book', ['model' => $dynamicModel, 'tourModel' => $this->findModel($id)]);
 }
示例#15
0
 public function actionUploadAvatar()
 {
     if (Yii::$app->user->isGuest) {
         throw new NotFoundHttpException(Yii::t('yii', 'Page not found.'));
     }
     Yii::$app->response->format = Response::FORMAT_JSON;
     $model = new DynamicModel(['image']);
     $model->addRule('image', 'file', ['skipOnEmpty' => false, 'extensions' => 'png, jpg']);
     if (Yii::$app->request->isPost) {
         $model->image = UploadedFile::getInstanceByName('image');
         if ($model->validate()) {
             try {
                 return AvatarHelper::saveAvatar($model->image);
             } catch (Exception $exc) {
                 Yii::$app->response->statusCode = 400;
                 return Yii::t('yee', 'An unknown error occurred.');
             }
         } else {
             $errors = $model->getErrors();
             Yii::$app->response->statusCode = 400;
             return $model->getFirstError(key($errors));
         }
     }
     return;
 }
 public function testValidateOperatorGreaterOrEqual()
 {
     $compareErrorText = Yii::t('app', '{attribute} must be greater than or equal to "{compareValue}".', ['attribute' => 'Date From', 'compareValue' => '2016-01-02']);
     $model = new DynamicModel(['date_from' => '2016-01-01', 'date_to' => '2016-01-02']);
     $model->addRule(['date_from', 'date_to'], 'required');
     $model->addRule(['date_from'], DateTimeCompareValidator::className(), ['compareAttribute' => 'date_to', 'format' => 'Y-m-d', 'operator' => '>=']);
     $model->validate();
     $errorText = $model->getFirstError('date_from');
     $this->assertEquals($errorText, $compareErrorText);
     $model = new DynamicModel(['date_from' => '2016-01-01', 'date_to' => '2016-01-01']);
     $model->addRule(['date_from', 'date_to'], 'required');
     $model->addRule(['date_from'], DateTimeCompareValidator::className(), ['compareAttribute' => 'date_to', 'format' => 'Y-m-d', 'operator' => '>=']);
     $model->validate();
     $errorText = $model->getFirstError('date_from');
     $this->assertNull($errorText);
     $model = new DynamicModel(['date_from' => '2016-01-02', 'date_to' => '2016-01-01']);
     $model->addRule(['date_from', 'date_to'], 'required');
     $model->addRule(['date_from'], DateTimeCompareValidator::className(), ['compareAttribute' => 'date_to', 'format' => 'Y-m-d', 'operator' => '>=']);
     $model->validate();
     $errorText = $model->getFirstError('date_from');
     $this->assertNull($errorText);
 }