public function run() { $ids = array_reverse(Yii::app()->{$this->_type}->getPositions()); $totalCount = count($ids); $criteria = new CDbCriteria(); $criteria->addInCondition('t.id', $ids); if (!empty($ids)) { $criteria->order = 'FIELD(t.id, ' . implode(',', $ids) . ')'; } $collections = Collection::model()->published()->with('series:published')->findAll(); foreach ($collections as $collectionKey => &$collection) { $seriesArr = $collection->series; foreach ($seriesArr as $seriesKey => $series) { $series->goods = Good::model()->published()->series($series->id)->findAll($criteria); if (empty($series->goods)) { unset($seriesArr[$seriesKey]); } } $collection->series = $seriesArr; if (empty($collection->series)) { unset($collections[$collectionKey]); } } $this->render($this->view, array('collections' => $collections)); }
public function loadModel($id) { if (($model = Good::model()->findByPk($id)) === null) { throw new CHttpException(404, 'Страница не найдена'); } return $model; }
/** * Show good info * @param $id good id */ public function actionView($id) { $good = Good::model()->with(array('category' => array('select' => 'id,name,alias'), 'goodAttrVals' => array('select' => 'value,attr_value_id,attr_id'), 'goodAttrVals.attrValue', 'goodAttrVals.attr' => array('select' => 'name,type,template,attr_group_id'), 'goodAttrVals.attr.attrGroup', 'ratings' => array('select' => 'id,value'), 'goodImages'))->findByPk($id, '', array('order' => 'attrGroup.pos, attr.pos')); if ($good === null) { throw new CHttpException(404, 'Запрашиваемая вами страница не найдена.'); } $this->render('good', array('good' => $good)); }
/** * Set good quantity in shopping card */ public function actionSetGoodQuantity() { if (!isset($_POST['good_id']) || !isset($_POST['quantity'])) { echo 'fail'; return; } $good = Good::model()->findByPk($_POST['good_id']); Yii::app()->shoppingCart->update($good, $_POST['quantity']); echo 'success'; }
public function actionRemove($id) { $id = (int) $_GET['id']; $model = Good::model()->findByPk($id); if ($model !== null) { Yii::app()->favorite->remove($model->getId()); } if (Yii::app()->getRequest()->getIsAjaxRequest()) { //$this->renderPartial('_favorite', $data, false, true); Yii::app()->ajax->success(); } else { $this->redirect($model->url); } }
protected function beforeAction($action) { $actions = array('index', 'create'); if (in_array($action->id, $actions)) { $this->item_id = (int) Yii::app()->getRequest()->getParam('item_id'); if (!$this->item_id) { throw new CHttpException(400, 'Не установлен ID товара'); } if (($this->item = Good::model()->findByPk($this->item_id)) === null) { throw new CHttpException(404, 'Товар не найден'); } } return parent::beforeAction($action); }
public function actionShow($alias) { $good = Good::model()->published()->with('series', 'material', 'color', 'technique', 'producer')->findByAlias($alias); if (!$good) { throw new CHttpException(404); } // Определяем следующий товар $nextProduct = $good->getNextProduct(); // Определяем предыдущий товар $prevProduct = $good->getPrevProduct(); Yii::app()->watched->put($good); $this->currentCollection = $good->series->collection; $this->render('good', array('model' => $good, 'nextProduct' => $nextProduct, 'prevProduct' => $prevProduct)); }
public function run() { $ids = array_reverse(Yii::app()->{$this->_type}->getPositions()); $totalCount = count($ids); if ($this->limit > 0) { $ids = array_slice($ids, 0, $this->limit); } $criteria = new CDbCriteria(); $criteria->addInCondition('t.id', $ids); $criteria->limit = $this->limit; if (!empty($ids)) { $criteria->order = 'FIELD(t.id, ' . implode(',', $ids) . ')'; } $models = Good::model()->published()->findAll($criteria); $this->render($this->view, array('models' => $models, 'totalCount' => $totalCount)); }
public function run() { if (empty($this->model) || $this->model->related_products == '') { return; } $relatedProducts = explode(',', $this->model->related_products); array_walk($relatedProducts, function ($data) { return (int) trim($data); }); $criteria = new CDbCriteria(); $criteria->addInCondition('t.id', $relatedProducts); $criteria->order = 't.series_id ASC, t.sort ASC'; if ($this->limit > 0) { $criteria->limit = (int) $this->limit; } $models = Good::model()->published()->findAll($criteria); $this->render($this->view, array('models' => $models, 'model' => $this->model)); }
/** * Возвращает модель по указанному идентификатору * Если модель не будет найдена - возникнет HTTP-исключение. * @param integer идентификатор нужной модели */ public function loadModel($id) { $model = Good::model()->findByPk($id); if ($model === null) { throw new CHttpException(404, Yii::t('CatalogModule.catalog', 'Page was not found!')); } return $model; }
/** * Return 3 random goods * @return Good[] random goods */ public function similar() { $goods = Good::model()->with(array('goodImages'))->findAll(array('condition' => 'price <> 0', 'order' => 'RAND()', 'limit' => 3)); return $goods; }
/** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer the ID of the model to be loaded */ public function loadModel($id) { $model = Good::model()->findByPk((int) $id); if ($model === null) { throw new CHttpException(404, 'The requested page does not exist.'); } return $model; }
/** * Show all user reviews for good */ public function actionAllReviews() { if (Yii::app()->request->isAjaxRequest && isset($_POST['good_id'])) { $time_start = microtime(); if ($this->beginCache('good-reviews-all' . $_POST['good_id'], array('dependency' => array('class' => 'system.caching.dependencies.CDbCacheDependency', 'sql' => 'SELECT MAX(id) FROM review WHERE good_id=' . $_POST['good_id']), 'duration' => 3600))) { $good = Good::model()->findByPk($_POST['good_id']); foreach ($good->reviews as $review) { $this->renderPartial('review', array('review' => $review)); } $this->endCache(); } $time_end = microtime(); if (YII_DEBUG) { echo $time_end - $time_start; } $sql_stats = YII::app()->db->getStats(); if (YII_DEBUG) { echo '<div>' . $sql_stats[0] . ' запросов к БД, время выполнения запросов - ' . $sql_stats[1] . '</div>'; } } }
/** * Search goods */ public function actionSearch() { if (!isset($_POST['feature'])) { echo 'Категория пуста'; return; } //print_r($_POST); $catId = $_POST['category_id']; if (isset($_POST['brand'])) { foreach ($_POST['brand'] as $key => $value) { $brands[] = $key; } } $price = $_POST['price']; $res = array(); $first_step = true; foreach ($_POST['feature'] as $featureId => $feature) { if (!empty($feature) || $feature == '0') { $attr = Attr::model()->cache(3600)->findByPk($featureId); if ($attr->type == '2' && $feature == '2') { continue; } if ($attr->type == '3' && empty($feature['min']) && empty($feature['max'])) { continue; } $criteria = new CDbCriteria(); $criteria->compare('category_id', $catId, false); if (!empty($brands)) { $criteria->compare('brand_id', $brands, false); } if (!empty($price) && !empty($price['min'])) { $criteria->condition .= ' AND price >= ' . $price["min"]; } if (!empty($price) && !empty($price['max'])) { $criteria->condition .= ' AND price <= ' . $price["max"]; } $criteria->join = 'left join good_attr_val v ON v.good_id=t.id'; if ($attr->type == '1') { $values = array(); foreach ($feature as $key => $value) { if ($value == '1') { $values[] = $key; } } $criteria->compare('v.attr_value_id', $values); } if ($attr->type == '2') { $criteria->condition .= ' AND v.value=' . $feature . ' and v.attr_id=' . $attr->id; } if ($attr->type == '3') { if (!empty($feature['min']) && !empty($feature['max'])) { $criteria->condition .= ' AND v.value>=' . $feature['min'] . ' AND v.value<=' . $feature['max'] . ' AND v.attr_id =' . $attr->id; } elseif (!empty($feature['min']) && empty($feature['max'])) { $criteria->condition .= ' AND v.value>=' . $feature['min'] . ' AND v.attr_id =' . $attr->id; } elseif (empty($feature['min']) && !empty($feature['max'])) { $criteria->condition .= ' AND v.value<=' . $feature['max'] . ' AND v.attr_id =' . $attr->id; } } $goods = Good::model()->with(array('goodImages'))->findAll($criteria); $good_ids = array(); foreach ($goods as $good) { $good_ids[] = $good->id; } //echo 'id=' . $featureId . '<br>'; if (empty($res) && $first_step) { //print_r($good_ids);echo '<br>'; $res = $good_ids; if (empty($res) && !$first_step) { echo 'Ничего не найдено по этим критериям'; return; } $first_step = FALSE; continue; } if (empty($good_ids)) { echo 'Ничего не найдено по этим критериям'; return; } foreach ($res as $good_id) { if (!in_array($good_id, $good_ids)) { unset($res[array_search($good_id, $res)]); } } } } if ($first_step) { $criteria = new CDbCriteria(); $criteria->compare('category_id', $catId, false); if (!empty($brands)) { $criteria->compare('brand_id', $brands, false); } if (!empty($price) && !empty($price['min'])) { $criteria->condition .= ' AND price >= ' . $price["min"]; } if (!empty($price) && !empty($price['max'])) { $criteria->condition .= ' AND price <= ' . $price["max"]; } if (!empty($_POST['order'])) { $criteria->order = $_POST['order'] . ' '; } $count = Good::model()->count($criteria); $pages = new CPagination($count); $pages->pageSize = 10; $pages->setCurrentPage($_POST['page']); $pages->applyLimit($criteria); $goods = Good::model()->with(array('goodImages'))->findAll($criteria); } else { if (count($res) == 0) { echo 'Ничего не найдено по этим критериям'; return; } $new_res = array(); foreach ($res as $value) { $new_res[] = $value; } $count = count($new_res); $criteria = new CDbCriteria(); $pages = new CPagination($count); $pages->pageSize = 10; $pages->setCurrentPage($_POST['page']); $pages->applyLimit($criteria); $criteria->compare('id', $new_res); if (!empty($_POST['order'])) { $criteria->order = $_POST['order'] . ' '; } $goods = Good::model()->with(array('goodImages'))->findAll($criteria); } $this->renderPartial('search-result', array('goods' => $goods, 'pages' => $pages, 'count' => $count)); }
public function getPrevProduct($filter = array()) { // Условие выборки по порядку $criteria = new CDbCriteria(); $criteria->addCondition('t.series_id = :series_id AND t.sort <= :sort AND t.id <> :id'); $criteria->params = array(':series_id' => $this->series_id, ':sort' => $this->sort, ':id' => $this->id); $criteria->order = 't.sort DESC'; $prevProduct = Good::model()->published()->find($criteria); if ($prevProduct === null) { $criteria = new CDbCriteria(); $criteria->compare('t.series_id', $this->series_id); $criteria->order = 't.sort DESC'; $prevProduct = Good::model()->published()->find($criteria); } return $prevProduct; }
/** * Fill good rating by random data * @return void */ public function actionRandomData() { $users = array(1, 2, 3); $all_goods = Good::model()->findAll(); foreach ($all_goods as $good) { $sum = 0; $count = 0; foreach ($users as $user) { if (rand(1, 5) == 5) { continue; } $count++; $user_mark = rand(1, 5); $sum += $user_mark; $user_rating = new Rating(); $user_rating->good_id = $good->id; $user_rating->user_id = $user; $user_rating->value = $user_mark; $user_rating->save(); } if ($count != 0) { $good->rating = round($sum / $count * 100); $good->update(array('rating')); } echo $good->id . '<br>'; flush(); } }
public function actionIndex() { $dataProvider = new CActiveDataProvider(Good::model()->published(), array('criteria' => new CDbCriteria(array('limit' => self::GOOD_PER_PAGE, 'order' => 't.create_time DESC')))); $this->render('index', array('dataProvider' => $dataProvider)); }
/** * Отправление подтверждения пользователю и уведомления админу * @param DictionaryData $type * @return FeedbackForm $feedbackForm */ protected function _processForm($type) { if ($type->id == Feedback::TYPE_CALLBACK) { $feedbackForm = new CallbackForm('insert'); } elseif ($type->id == Feedback::TYPE_ORDER) { $feedbackForm = new OrderForm('insert'); } elseif ($type->id == Feedback::TYPE_REVIEW) { $feedbackForm = new ReviewForm('insert'); } else { $feedbackForm = new FeedbackForm('insert'); } $formName = get_class($feedbackForm); $this->performAjaxValidation($feedbackForm); if (Yii::app()->getRequest()->getIsPostRequest() && !empty($_POST[$formName])) { $feedbackForm->setAttributes($_POST[$formName]); // Проверка if ($feedbackForm->validate()) { $feedback = new Feedback(); $feedback->type_id = $type->id; $feedback->type = $type; $feedback->setAttributes($feedbackForm->getAttributes()); if ($type->id == Feedback::TYPE_ORDER && isset($_POST['productId']) && !empty($_POST['productId'])) { Yii::import("application.modules.catalog.models.Good"); $product = Good::model()->findByPk((int) $_POST['productId']); if (is_null($product)) { throw new CHttpException('404'); } $feedback->theme = 'Заявка на товар "' . $product->title . '"'; $feedback->text = '<p>Ссылка на товар: ' . CHtml::link($product->title, $product->getPermaLink()) . '</p>'; } // Сохранение if ($feedback->save()) { // Отправка уведомлений if (Yii::app()->getModule('feedback')->sendConfirmation) { $this->_feedbackConfirmationEmail($feedback); } $successMessage = $type->id == Feedback::TYPE_ORDER ? 'Ваше сообщение отправлено! Спасибо! В ближайшее время наши менеджеры свяжутся с Вами!' : 'Ваше сообщение отправлено! Спасибо!'; if (Yii::app()->getRequest()->getIsAjaxRequest()) { Yii::app()->ajax->success($successMessage); } else { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::SUCCESS_MESSAGE, $successMessage); } } else { var_dump($feedback->getErrors()); exit; // Ошибка сохранения if (Yii::app()->getRequest()->getIsAjaxRequest()) { Yii::app()->ajax->failure(Yii::t('FeedbackModule.feedback', 'There is an error when trying to send message! Please try later!')); } else { Yii::app()->user->setFlash(yupe\widgets\YFlashMessages::ERROR_MESSAGE, Yii::t('FeedbackModule.feedback', 'There is an error when trying to send message! Please try later!')); } } // Обновляем страницу $this->refresh(); } else { // Ошибка валидации if (Yii::app()->getRequest()->getIsAjaxRequest()) { Yii::app()->ajax->failure('Пожалуйста, проверьте правильность заполнения формы'); } } } return $feedbackForm; }
?> "> <img height="16" border="0" width="16" src="/images/duru.gif" title="Каталог товаров" alt="*!*"><?php echo $model->name; ?> </a> <span style="font-size: 87%;"><?php $cat = Category::model()->findByPk($model->id); if ($cat->isLeaf()) { echo Good::model()->count('category_id=' . $cat->id); } else { $categories = $cat->descendants()->findAll(); $sum = 0; foreach ($categories as $category) { if ($category->isLeaf()) { $sum = $sum + Good::model()->count('category_id=' . $category->id); } } echo $sum; } ?> </span> <div class="subcat"> <?php if (!$cat->isLeaf()) { $categories = $cat->children()->findAll(); $i = 0; foreach ($categories as $category) { echo CHtml::link($category->name, $this->createUrl('catalog/view', array('name' => $category->alias))); $i++; if ($i > 7) {
/** * Список программ: **/ public function getItemsList() { return CHtml::listData(Good::model()->findAll(), 'id', 'title'); }