本文整理汇总了PHP中yii\base\DynamicModel类的典型用法代码示例。如果您正苦于以下问题:PHP DynamicModel类的具体用法?PHP DynamicModel怎么用?PHP DynamicModel使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DynamicModel类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: run
/**
* @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'));
}
}
示例2: actionViewAdvert
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]);
}
示例3: actionStock
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);
}
示例4: addFormValidators
/**
* 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);
});
}
}
}
}
示例5: actionIndex
/**
* 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('lg-postman@lukison.com')
->setTo('piter@lukison.com')
->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(['postman@lukison.com' => 'LG-ERP-POSTMAN'])->setTo('piter@lukison.com')->setSubject('daily test email')->setTextBody($ok)->send();
/* \Yii::$app->mailer->compose()
->setFrom('postman@lukison.com')
->setTo('piter@lukison.com')
->setSubject('test subject')
->send(); */
}
示例6: actionVerify
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]);
}
示例7: run
/**
* @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'));
}
}
示例8: actionUpdate
/**
* 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]);
}
示例9: actionData
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();
}
示例10: run
/**
*
* @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');
}
}
示例11: run
/**
* @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;
}
示例12: savePhoto
/**
* 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);
}
}
示例13: actionUpload
/**
* 上传示例
*
* @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]);
}
示例14: actionLanguage
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]);
}
示例15: run
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);
}
}