本文整理汇总了PHP中yii\base\DynamicModel::addRule方法的典型用法代码示例。如果您正苦于以下问题:PHP DynamicModel::addRule方法的具体用法?PHP DynamicModel::addRule怎么用?PHP DynamicModel::addRule使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类yii\base\DynamicModel
的用法示例。
在下文中一共展示了DynamicModel::addRule方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: 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]);
}
示例2: 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'));
}
}
示例3: 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);
});
}
}
}
}
示例4: run
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
]);
}
示例5: 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();
}
示例6: 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');
}
}
示例7: 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]);
}
示例8: 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]);
}
示例9: 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);
}
示例10: 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'));
}
}
示例11: 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(); */
}
示例12: 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;
}
示例13: testBeginHasErrorAndRequired
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);
}
示例14: getComponentConfigModel
/**
* @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;
}
示例15: 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);
}
}