public function beforeSave() { if (Product::model()->exists('id = :product_id', [":product_id" => $this->product_id])) { $this->variant_ids = array_filter($this->variant_ids); // удаляем варианты, которые не были выбраны, старые не трогаем, чтобы оставить данные, на случай, если вариант был удален из системы foreach ($this->oldVariants as $key => $var) { if (!in_array($var['id'], $this->variant_ids)) { unset($this->oldVariants[$key]); } } $oldVariantIds = array_map(function ($x) { return $x['id']; }, $this->oldVariants); $newVariants = []; foreach ($this->variant_ids as $varId) { if (!in_array($varId, $oldVariantIds)) { /* @var $variant ProductVariant */ $variant = ProductVariant::model()->findByPk($varId); if ($variant) { // сохраняем информацию на случай удаления варианта из системы $newVariants[] = array_merge($variant->attributes, ['attribute_name' => $variant->attribute->name, 'attribute_title' => $variant->attribute->title, 'optionValue' => $variant->getOptionValue()]); } } } $combinedVariants = array_merge($this->oldVariants, $newVariants); $this->variants = serialize($combinedVariants); } return parent::beforeSave(); }
public function beforeValidate() { if (!$this->slug) { $this->slug = yupe\helpers\YText::translit($this->name); } return parent::beforeValidate(); }
protected function beforeSave() { if ($this->isNewRecord) { $this->sort = Yii::app()->db->createCommand()->select('MAX(sort) + 1')->from($this->tableName())->queryScalar(); } return parent::beforeSave(); }
protected function loadModel($value) { $model = YModel::model($this->modelClass)->findByAttributes([$this->attribute => $value]); if (!$model) { throw new CHttpException(404, $this->getErrorMessage()); } return $model; }
/** * @return bool */ public function beforeSave() { $this->update_time = new CDbExpression('NOW()'); if ($this->getIsNewRecord()) { $this->create_time = $this->update_time; } $this->user_id = Yii::app()->hasComponent('user') ? Yii::app()->getUser()->getId() : null; return parent::beforeSave(); }
/** * @return bool */ public function beforeSave() { $this->update_time = new CDbExpression('NOW()'); if ($this->getIsNewRecord()) { $this->create_time = $this->update_time; } // Пользователя можно получить только для веб-приложения $this->user_id = Yii::app()->hasComponent('user') ? Yii::app()->getUser()->getId() : null; return parent::beforeSave(); }
public function beforeValidate() { if ($this->attribute_option_id) { $option = AttributeOption::model()->findByPk($this->attribute_option_id); $this->attribute_value = $option ? $option->value : null; } if (!$this->attribute_value) { $this->addErrors(['attribute_value' => Yii::t('StoreModule.store', 'You must specify the attribute value')]); } return parent::beforeValidate(); }
/** * @param $params * @param $module * @param $user * @param null $request * @return bool|Comment * @throws CException */ public function create($params, $module, $user, $request = null) { if ($user->isAuthenticated()) { $params = CMap::mergeArray($params, ['user_id' => $user->getId(), 'name' => $user->getState('nick_name'), 'email' => $user->getProfileField('email')]); } $comment = new Comment(); $comment->setAttributes($params); $comment->status = (int) $module->defaultCommentStatus; if ($module->autoApprove && $user->isAuthenticated()) { $comment->status = Comment::STATUS_APPROVED; } /** * Реализована проверка прав на возможность добавления комментария в конкретную модель * Для того чтобы осушествить проверку у модели должен быть public метод: commitValidation() * Если метод вернет значение: false, то предполагается что для данной сушности добавление комментария запрещено **/ $model = YModel::model($comment->model)->findByPk($comment->model_id); if ($model instanceof ICommentAllowed && $model->isCommentAllowed() === false) { throw new CException(Yii::t('CommentModule.comment', 'Not have permission to add a comment!')); } $transaction = Yii::app()->getDb()->beginTransaction(); try { Yii::app()->eventManager->fire(CommentEvents::BEFORE_ADD_COMMENT, new CommentEvent($comment, $user, $module, $request)); $root = null; $parentId = (int) $comment->parent_id; // Если указан parent_id просто добавляем новый комментарий. if ($parentId) { $root = Comment::model()->approved()->findByPk($parentId); if (null === $root) { throw new CException(Yii::t('CommentModule.comment', 'Root comment not found!')); } } else { // Иначе если parent_id не указан... $root = $comment->createRootOfCommentsIfNotExists($comment->model, $comment->model_id); if (null === $root) { throw new CException(Yii::t('CommentModule.comment', 'Root comment not created!')); } } if ($comment->appendTo($root)) { Yii::app()->eventManager->fire(CommentEvents::SUCCESS_ADD_COMMENT, new CommentEvent($comment, $user, $module)); $transaction->commit(); return $comment; } throw new CException(Yii::t('CommentModule.comment', 'Error append comment to root!')); } catch (Exception $e) { $transaction->rollback(); Yii::app()->eventManager->fire(CommentEvents::ERROR_ADD_COMMENT, new CommentEvent($comment, $user, $module)); Yii::log($e->__toString(), CLogger::LEVEL_ERROR, 'comment'); return false; } }
public function beforeSave() { $this->change_date = new CDbExpression('NOW()'); if ($this->isNewRecord) { $this->creation_date = $this->change_date; } if (!isset($this->user_id)) { $this->user_id = Yii::app()->user->getId(); } if ($this->user_id !== Yii::app()->user->getId()) { $this->user_id = Yii::app()->user->getId(); } return parent::beforeSave(); }
public function beforeSave() { $this->change_date = new CDbExpression('NOW()'); if ($this->isNewRecord) { $this->creation_date = $this->change_date; } // Пользователя можно получить только для веб-приложения if (YII_APP_TYPE == 'web') { $this->user_id = Yii::app()->user->getId(); } else { $this->user_id = null; } return parent::beforeSave(); }
/** * */ public function afterDelete() { Yii::app()->eventManager->fire(StoreEvents::CATEGORY_AFTER_DELETE, new Event($this)); parent::afterDelete(); }
public function afterSave() { // удаляем старые значения AttributeOption::model()->deleteAllByAttributes(['attribute_id' => $this->id]); if (in_array($this->type, [Attribute::TYPE_DROPDOWN])) { $newOptions = explode("\n", $this->rawOptions); $newOptions = array_filter($newOptions, function ($x) { return strlen(trim($x)); }); foreach (array_values((array) $newOptions) as $key => $op) { $option = new AttributeOption(); $option->attribute_id = $this->id; $option->value = trim($op); $option->position = $key; $option->save(); } } parent::afterSave(); }
protected function beforeSave() { // Сохраняем путь к файлу $this->file = $this->file_name; return parent::beforeSave(); }
/** * Returns the static model of the specified AR class. * @return Type the static model class */ public static function model($className = __CLASS__) { return parent::model($className); }
/** * */ public function afterSave() { Yii::app()->eventManager->fire(StoreEvents::CATEGORY_AFTER_SAVE, new Event($this)); return parent::afterSave(); }
/** * @return bool */ public function beforeValidate() { $settings = ['brands' => $this->brands, 'categories' => $this->categories, 'shop_name' => $this->shop_name, 'shop_company' => $this->shop_company, 'shop_url' => $this->shop_url, 'shop_platform' => $this->shop_platform, 'shop_version' => $this->shop_version, 'shop_agency' => $this->shop_agency, 'shop_email' => $this->shop_email, 'shop_cpa' => $this->shop_cpa]; $this->settings = json_encode($settings); return parent::beforeValidate(); }
public function afterSave() { if ($this->type == Attribute::TYPE_DROPDOWN) { // список новых значений опций атрибута, не пустые, без лишних пробелов по бокам, уникальные $newOptions = array_unique(array_filter(array_map('trim', explode("\n", $this->rawOptions)))); // в нижнем регистре, чтобы не надо было переназначать привязку атрибутов в товарах $newOptionsLower = array_map(function ($x) { return mb_strtolower($x, 'utf-8'); }, $newOptions); $oldOptionsLower = []; // список имен опций, которые уже сохранены // удалим те из них, которых нет, в остальных обновим значение и позицию foreach ((array) $this->options as $option) { /* @var $option AttributeOption */ $position = array_search(mb_strtolower($option->value), $newOptionsLower); // опция была удалена if ($position === false) { $option->delete(); } else { $oldOptionsLower[] = mb_strtolower($option->value, 'utf-8'); $option->value = $newOptions[$position]; // если поменяли регистр опции $option->position = $position; $option->save(); } } // добавим оставшиеся foreach (array_diff($newOptionsLower, $oldOptionsLower) as $position => $value) { $option = new AttributeOption(); $option->attribute_id = $this->id; $option->value = $newOptions[$position]; $option->position = $position; $option->save(); } } parent::afterSave(); }