/** * @inheritdoc */ public function run() { if (Yii::$app->request->isPost) { $file = UploadedFile::getInstanceByName($this->uploadParam); $model = new DynamicModel(compact($this->uploadParam)); $model->addRule($this->uploadParam, 'file', ['maxSize' => $this->maxSize, 'tooBig' => Yii::t('upload', 'TOO_BIG_ERROR', ['size' => $this->maxSize / (1024 * 1024)]), 'extensions' => explode(', ', $this->extensions), 'checkExtensionByMimeType' => false, 'wrongExtension' => Yii::t('upload', 'EXTENSION_ERROR', ['formats' => $this->extensions])])->validate(); if ($model->hasErrors()) { $result = ['error' => $model->getFirstError($this->uploadParam)]; } else { $model->{$this->uploadParam}->name = uniqid() . '.' . $model->{$this->uploadParam}->extension; $request = Yii::$app->request; $image_name = $this->temp_path . $model->{$this->uploadParam}->name; $image = Image::crop($file->tempName . $request->post('filename'), intval($request->post('w')), intval($request->post('h')), [$request->post('x'), $request->post('y')])->resize(new Box($this->width, $this->height))->save($image_name); // watermark if ($this->watermark != '') { $image = Image::watermark($image_name, $this->watermark)->save($image_name); } if ($image->save($image_name)) { // create Thumbnail if ($this->thumbnail && ($this->thumbnail_width > 0 && $this->thumbnail_height > 0)) { Image::thumbnail($this->temp_path . $model->{$this->uploadParam}->name, $this->thumbnail_width, $this->thumbnail_height)->save($this->temp_path . '/thumbs/' . $model->{$this->uploadParam}->name); } $result = ['filelink' => $model->{$this->uploadParam}->name]; } else { $result = ['error' => Yii::t('upload', 'ERROR_CAN_NOT_UPLOAD_FILE')]; } } Yii::$app->response->format = Response::FORMAT_JSON; return $result; } else { throw new BadRequestHttpException(Yii::t('upload', 'ONLY_POST_REQUEST')); } }
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 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); }
/** * Creates validation rules for $model property * * @param \yii\base\DynamicModel $model */ public function addFormValidators(&$model) { //add validators for basic table filter $model->addRule(['table'], 'required'); $model->addRule(['table'], function () use($model) { return $this->checkTableExists($model); }); //add validators declared in config file foreach (Yii::$app->controller->module->filters as $property => $params) { $model->addRule($property, 'default'); if (!isset($params['rules'])) { continue; } foreach ($params['rules'] as $rule) { $options = isset($rule['options']) ? $rule['options'] : []; $validator = $rule['validator']; if (is_string($validator)) { $model->addRule($property, $validator, $options); } else { $model->addRule($property, function () use($model, $validator, $options) { return call_user_func([$validator['class'], $validator['method']], $model, $options); }); } } } }
/** * ACTION INDEX */ public function actionIndex() { /* variable content View Employe Author: -ptr.nov- // $searchModel_Dept = new DeptSearch(); //$dataProvider_Dept = $searchModel_Dept->search(Yii::$app->request->queryParams); Yii::$app->Mailer->compose() ->setFrom('*****@*****.**') ->setTo('*****@*****.**') ->setSubject('Message subject') ->setTextBody('Plain text content') //->setHtmlBody('<b>HTML content</b>') ->send(); //return $this->render('index'); */ $form = ActiveForm::begin(); $model = new DynamicModel(['TextBody', 'Subject']); $model->addRule(['TextBody', 'Subject'], 'required'); $ok = 'Test LG ERP FROM HOME .... GOOD NIGHT ALL, SEE U LATER '; $form->field($model, 'Subject')->textInput(); ActiveForm::end(); Yii::$app->mailer->compose()->setFrom(['*****@*****.**' => 'LG-ERP-POSTMAN'])->setTo('*****@*****.**')->setSubject('daily test email')->setTextBody($ok)->send(); /* \Yii::$app->mailer->compose() ->setFrom('*****@*****.**') ->setTo('*****@*****.**') ->setSubject('test subject') ->send(); */ }
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]); }
/** * @inheritdoc */ public function run() { if (Yii::$app->request->isPost) { $file = UploadedFile::getInstanceByName($this->uploadParam); $model = new DynamicModel(compact($this->uploadParam)); $model->addRule($this->uploadParam, 'image', ['maxSize' => $this->maxSize, 'tooBig' => Yii::t('cropper', 'TOO_BIG_ERROR', ['size' => $this->maxSize / (1024 * 1024)]), 'extensions' => explode(', ', $this->extensions), 'wrongExtension' => Yii::t('cropper', 'EXTENSION_ERROR', ['formats' => $this->extensions])])->validate(); if ($model->hasErrors()) { $result = ['error' => $model->getFirstError($this->uploadParam)]; } else { $model->{$this->uploadParam}->name = uniqid() . '.' . $model->{$this->uploadParam}->extension; $request = Yii::$app->request; $width = $request->post('width', $this->width); $height = $request->post('height', $this->height); $image = Image::crop($file->tempName . $request->post('filename'), intval($request->post('w')), intval($request->post('h')), [$request->post('x'), $request->post('y')])->resize(new Box($width, $height)); if ($image->save($this->path . $model->{$this->uploadParam}->name)) { $result = ['filelink' => $this->url . $model->{$this->uploadParam}->name]; } else { $result = ['error' => Yii::t('cropper', 'ERROR_CAN_NOT_UPLOAD_FILE')]; } } Yii::$app->response->format = Response::FORMAT_JSON; return $result; } else { throw new BadRequestHttpException(Yii::t('cropper', 'ONLY_POST_REQUEST')); } }
/** * Updates an existing AuthRule model. * If update is successful, the browser will be redirected to the 'view' page. * @param string $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); $dynamicModel = new DynamicModel(['ruleNamespace']); $dynamicModel->addRule(['ruleNamespace'], function ($attribute, $params) use($dynamicModel) { $this->validateClass($dynamicModel, $attribute, ['extends' => \yii\rbac\Rule::className()]); }); $dynamicModel->addRule(['ruleNamespace'], 'required'); if ($model->data && ($ruleNamespace = unserialize($model->data)) !== false) { if (method_exists($ruleNamespace, 'className')) { $dynamicModel->ruleNamespace = $ruleNamespace::className(); } } $post = Yii::$app->request->post(); if ($model->load($post) && $dynamicModel->load($post)) { if ($model->validate() && $dynamicModel->validate()) { $ruleModel = new $dynamicModel->ruleNamespace(); $time = time(); $ruleModel->createdAt = $time; $ruleModel->updatedAt = $time; $model->data = serialize($ruleModel); if ($model->save(false)) { Yii::$app->getSession()->setFlash('success', Adm::t('', 'Data successfully changed!')); return Adm::redirect(['update', 'id' => $model->name]); } } } return $this->render('update', ['model' => $model, 'dynamicModel' => $dynamicModel]); }
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(); }
/** * * @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'); } }
/** * @inheritdoc */ public function run() { $result = ['err' => 1, 'msg' => 'swfupload init']; if (Yii::$app->request->isPost) { $data = Yii::$app->request->get('data'); $data = Json::decode(base64_decode($data)); $url = $data['url']; $path = $data['path']; $params = $data['params']; $callback = $data['callback']; $file = UploadedFile::getInstanceByName('FileData'); $model = new DynamicModel(compact('file')); $model->addRule('file', 'image', [])->validate(); if ($model->hasErrors()) { $result['msg'] = $model->getFirstError('file'); } else { if ($model->file->extension) { $model->file->name = uniqid() . '.' . $model->file->extension; } if ($model->file->saveAs($path . $model->file->name)) { $result['err'] = 0; $result['msg'] = 'success'; $result['url'] = $model->file->name; $result['params'] = $params; $result['callback'] = $callback; } else { $result['msg'] = $model->getFirstError('file save error!'); } } } Yii::$app->response->format = Response::FORMAT_JSON; return $result; }
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]]]); }
/** * Save photo * * @param \app\models\UserProfile $profile * @param string $photo * @return void */ private function savePhoto($profile, $photo) { $file = $this->makeUploadedFile($photo); $model = new DynamicModel(compact('file')); $model->addRule('file', 'image', $profile->fileRules('photo', true))->validate(); if (!$model->hasErrors()) { $profile->createFile('photo', $file->tempName, $model->file->name); } }
/** * 上传示例 * * @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]); }
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]); }
public function run() { $file = UploadedFile::getInstanceByName($this->inputName); if (!$file) { return $this->response(['error' => Yii::t('filemanager-yii2', 'An error occured, try again later…')]); } $model = new DynamicModel(compact('file')); $model->addRule('file', $this->type, $this->rules)->validate(); if ($model->hasErrors()) { return $this->response(['error' => $model->getFirstError('file')]); } else { return $this->upload($file); } }
public function actionIndex() { $model = new DynamicModel(['created_at' => time()]); $model->attachBehavior('format', ['class' => DateConverter::className(), 'logicalFormat' => 'php:d/m/Y', 'physicalFormat' => 'php:time', 'attributes' => ['createAt' => 'created_at']]); var_dump($model->createAt); $model->createAt = '10/59/2015'; var_dump($model->created_at); print_r([$model->created_at, time()]); echo str_repeat('=', '5'); $model->created_at = time(); print_r([$model->createAt, $model->created_at]); die(__METHOD__); // return $this->render('index'); }
/** * Register new theme. * Theme zip uploaded to temporary directory and extracted there. * Check the theme directory and move the first directory of the extracted theme. * If registration is successful, the browser will be redirected to the 'index' page. * * @return string */ public function actionUpload() { $errors = []; $model = new DynamicModel(['file']); $model->addRule(['file'], 'required')->addRule(['file'], 'file', ['extensions' => 'zip']); if (!is_dir($this->_dir)) { FileHelper::createDirectory($this->_dir, 0755); } if (!is_dir($this->_tmp)) { FileHelper::createDirectory($this->_tmp, 0755); } if (!is_dir($this->_thumbDir)) { FileHelper::createDirectory($this->_thumbDir, 0755); } if (($model->file = UploadedFile::getInstance($model, 'file')) && $model->validate()) { $themeTempPath = $this->_tmp . $model->file->name; if (!$model->file->saveAs($themeTempPath)) { return $this->render('upload', ['model' => $model, 'errors' => [Yii::t('writesdown', 'Failed to move uploaded file')]]); } $zipArchive = new \ZipArchive(); $zipArchive->open($themeTempPath); if (!$zipArchive->extractTo($this->_tmp)) { $zipArchive->close(); FileHelper::removeDirectory($this->_tmp); return $this->render('upload', ['model' => $model, 'errors' => [Yii::t('writesdown', 'Failed to extract file.')]]); } $baseDir = substr($zipArchive->getNameIndex(0), 0, strpos($zipArchive->getNameIndex(0), '/')); $zipArchive->close(); if (is_dir($this->_dir . $baseDir)) { FileHelper::removeDirectory($this->_tmp); $errors[] = Yii::t('writesdown', 'Theme with the same directory already exist.'); } else { rename($this->_tmp . $baseDir, $this->_dir . $baseDir); FileHelper::removeDirectory($this->_tmp); if (is_file($this->_dir . $baseDir . '/screenshot.png')) { copy($this->_dir . $baseDir . '/screenshot.png', $this->_thumbDir . $baseDir . '.png'); } foreach (ArrayHelper::getValue($this->getConfig($baseDir), 'upload', []) as $type) { try { Yii::createObject($type); } catch (Exception $e) { } } Yii::$app->getSession()->setFlash('success', Yii::t('writesdown', 'Theme successfully uploaded')); return $this->redirect(['index']); } } return $this->render('upload', ['model' => $model, 'errors' => $errors]); }
/** * 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]); }
private function runGet() { $request = Yii::$app->getRequest(); $model = DynamicModel::validateData(['id' => $request->get('id'), 'screen_name' => $request->get('screen_name'), 'count' => $request->get('count'), 'newer_than' => $request->get('newer_than'), 'older_than' => $request->get('older_than')], [[['id'], 'exist', 'targetClass' => Battle::className(), 'targetAttribute' => 'id'], [['screen_name'], 'exist', 'targetClass' => User::className(), 'targetAttribute' => 'screen_name'], [['newer_than', 'older_than'], 'integer'], [['count'], 'default', 'value' => 10], [['count'], 'integer', 'min' => 1, 'max' => 100]]); if (!$model->validate()) { return $this->formatError($model->getErrors(), 400); } $query = Battle::find()->innerJoinWith('user')->with(['user', 'user.userStat', 'lobby', 'rule', 'map', 'weapon', 'weapon.subweapon', 'weapon.special', 'rank', 'battleImageResult', 'battleImageJudge'])->orderBy('{{battle}}.[[id]] DESC')->limit((int) $model->count); if ($model->id != '') { $query->andWhere(['{{battle}}.[[id]]' => $model->id]); } if ($model->screen_name != '') { $query->andWhere(['{{user}}.[[screen_name]]' => $model->screen_name]); } if ($model->newer_than > 0) { $query->andWhere(['>', '{{battle}}.[[id]]', $model->newer_than]); } if ($model->older_than > 0) { $query->andWhere(['<', '{{battle}}.[[id]]', $model->older_than]); } $list = $query->all(); if ($model->id != '') { return empty($list) ? null : $this->runGetImpl(array_shift($list)); } $resp = Yii::$app->getResponse(); $resp->format = 'json'; return array_map(function ($model) { return $model->toJsonArray(); }, $list); }
/** * 发送短信 * @param string $receiveMobileTel 接收手机号,多个号码可以使用;号分隔 * @param string $message 消息 * @param string $actionMark 功能点标识 * @throws InvalidConfigException 初始化配置错误 * @throws InvalidParamException 参数错误 * @throws InvalidCallException 调用短信服务发短信出错 */ public function send($receiveMobileTel, $message, $actionMark = '') { if (!$this->validate()) { throw new InvalidConfigException(implode(" ", $this->firstErrors)); } $modeTemp = DynamicModel::validateData(compact('receiveMobileTel', 'message'), [[['message', 'receiveMobileTel'], 'filter', 'filter' => 'trim'], [['receiveMobileTel', 'message'], 'required']]); if ($modeTemp->hasErrors()) { throw new InvalidParamException(implode(' ', $modeTemp->firstErrors)); } $sendResult = explode(',', $this->sendSms($receiveMobileTel, $message), 2); $code = is_int($sendResult[0] + 0) ? $sendResult[0] + 0 : -127; $msgId = isset($sendResult[1]) ? $sendResult[1] : ''; try { $log = new SmsSendLog(); $log->receive_mobile_tel = $receiveMobileTel; $log->message = $message; $log->action_mark = $actionMark; $log->result = $code; $log->msg_ids = $msgId; $log->save(); } catch (\Exception $ex) { Yii::error($ex); } if ($code <= 0) { throw new InvalidCallException($this->getSendErrorMsg($code)); } }
public function Run() { $resArray = []; $objPHPExcel = @\PHPExcel_IOFactory::load($this->filePath); if ($objPHPExcel) { $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true); $headerArray = $sheetData[1]; unset($sheetData[1]); foreach ($sheetData as $k => $itemArray) { $itemArray = @array_combine($headerArray, $itemArray); if ($itemArray) { try { $model = DynamicModel::validateData($itemArray, [[['id', 'type', 'available', 'bid', 'price', 'currencyId', 'categoryId', 'name', 'ISBN'], 'required']]); } catch (UnknownPropertyException $e) { continue; } if (isset($model) && !$model->hasErrors()) { $resArray[] = $itemArray; } } } } $this->response = $resArray; unlink($this->filePath); return $this; }
/** * Defines an attribute. * @param string $name the attribute name * @param mixed $value the attribute value * @param string $label the attribute label */ public function defineAttribute($name, $value = null, $label = null) { if ($label) { $this->_attributeLabels[$name] = $label; } parent::defineAttribute($name, $value); }
/** * Create jobs from recived data * * ```php * $_POST = [ * 'callback' => 'http://www.bn.ru/../', // Callback url * 'name' => 'www.bn.ru', * 'data' => [ * [ * 'command' => 0, * 'object_id' => '772dab1a-4b4f-11e5-885d-feff819cdc9f', * 'url' => 'http://www.bn.ru/images/photo/2015_08/201508252016081835551362b.jpg', * 'file_id' => 'a34c0e31-aaf8-43d9-a6ca-be9800dea5b7', * ], * [ * 'command' => 1, * 'object_id' => 'c1b270c4-4b51-11e5-885d-feff819cdc9f', * 'url' => 'http://www.bn.ru/images/photo/2015_08/201508252016121946987850b.jpg', * 'file_id' => '92d05f7c-c8fb-472f-9f9a-b052521924e1', * ], * ], * ]; * ``` * * @return string JSON */ public function actionCreate() { $return = ['status' => false]; $errors = []; $name = \Yii::$app->request->post('name', null); $callback = \Yii::$app->request->post('callback', null); $data = \Yii::$app->request->post('data', null); $config = [[['name', 'callback', 'data'], 'required'], ['callback', 'url', 'enableIDN' => true, 'message' => \Yii::t('yii', "{attribute} is not a valid URL: '{$callback}'!")]]; $model = \yii\base\DynamicModel::validateData(compact('name', 'callback', 'data'), $config); if ($model->hasErrors()) { throw new BadRequestHttpException(json_encode($model->getErrors())); } $name = $name . '::' . microtime(true); $sources = array_chunk($data, $this->maxPostCount); $countJobs = 0; $jobsModel = static::$component->jobsModel(); foreach ($sources as $source) { static::$component->addSource($name, $source); if (static::$component->addJob($name, $callback, $jobsModel::STATUS_WAIT)) { ++$countJobs; } } if ($countJobs) { $return['status'] = true; } else { throw new BadRequestHttpException(\Yii::t('yii', 'Error create project!')); } return $return; }
/** * @inheritdoc */ public function run() { if (Yii::$app->request->isPost) { $file = UploadedFile::getInstanceByName($this->incomingFieldName); $model = DynamicModel::validateData(compact('file')); $model->addRule('file', $this->isImage ? 'image' : 'file', $this->validationOptions); if ($model->hasErrors()) { return $this->getResult(false, implode('; ', $model->getErrors('file'))); } else { if ($this->isUseUniqueFileNames) { $filename = uniqid($this->isUseFileNamesAsPrefix ? $file->baseName : $this->customPrefix) . '.' . $file->extension; } else { $filename = $file->baseName . '.' . $file->extension; } if (@$file->saveAs($this->savePath . $filename)) { return $this->getResult(true, '', ['access_link' => $this->accessUrl . $filename]); } return $this->getResult(false, 'File can\'t be placed to destination folder'); } } else { throw new BadRequestHttpException('Only Post request allowed for this action!'); } $uploads_dir = '/var/tmp'; if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) { $tmp_name = $_FILES["file"]["tmp_name"]; $name = $_FILES["file"]["name"]; move_uploaded_file($tmp_name, "{$uploads_dir}/{$name}"); } return ['success' => true, 'value' => '/uploads/some.file.txt']; }
public function actionImport() { $field = ['fileImport' => 'File Import']; $modelImport = DynamicModel::validateData($field, [[['fileImport'], 'required'], [['fileImport'], 'file', 'extensions' => 'xls,xlsx', 'maxSize' => 1024 * 1024]]); if (Yii::$app->request->post()) { $modelImport->fileImport = \yii\web\UploadedFile::getInstance($modelImport, 'fileImport'); if ($modelImport->fileImport && $modelImport->validate()) { $inputFileType = \PHPExcel_IOFactory::identify($modelImport->fileImport->tempName); $objReader = \PHPExcel_IOFactory::createReader($inputFileType); $objPHPExcel = $objReader->load($modelImport->fileImport->tempName); $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true); $baseRow = 2; while (!empty($sheetData[$baseRow]['A'])) { $model = new Mahasiswa(); $model->nama = (string) $sheetData[$baseRow]['B']; $model->nim = (string) $sheetData[$baseRow]['C']; $model->save(); //die(print_r($model->errors)); $baseRow++; } Yii::$app->getSession()->setFlash('success', 'Success'); } else { Yii::$app->getSession()->setFlash('error', 'Error'); } } return $this->redirect(['index']); }
public function formName() { if ($this->formName) { return $this->formName; } else { return parent::formName(); } }
/** * @param ConfigurableInterface $component * @return DynamicModel */ public function getComponentConfigModel($component) { $editableAttributes = $component->getEditableAttributes(); $model = new DynamicModel(array_keys($editableAttributes)); $model->addRule(array_keys($editableAttributes), 'safe'); foreach ($editableAttributes as $attribute => $settings) { if (isset($settings['rules'])) { foreach ($settings['rules'] as $rule) { if (!is_array($rule)) { $rule = [$rule]; } $model->addRule($attribute, array_shift($rule), $rule); } } } return $model; }
public function testBeginHasErrorAndRequired() { $this->helperModel->addError($this->attributeName, "Error Message"); $this->helperModel->addRule($this->attributeName, 'required'); $expectedValue = '<div class="form-group field-dynamicmodel-attributename required has-error">'; $actualValue = $this->activeField->begin(); $this->assertEquals($expectedValue, $actualValue); }
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 ]); }