public function up() { $data = (include Yii::getAlias('@common') . '/data/test-adverts.php'); $i = 0; while ($i++ !== 3) { foreach ($data as $one) { $advert = new Advert(); $advert->detachBehavior('timestamp'); $advert->setAttributes($one); $advert->user_id = rand(1, 50); $advert->created_at = time() - 3600 * 24 * rand(1, 31) - 3600 * rand(1, 24) + rand(1, 3600); $advert->updated_at = $advert->created_at; $advert->term_at = $advert->created_at + 3600 * 24 * rand(1, 31); if ($advert->save()) { echo "Advert for user №{$advert->user_id} created\n"; } else { print_r($advert->getErrors()); } } } foreach (User::find()->all() as $user) { $profile = new Profile(); $profile->user_id = $user->id; $profile->name = $user->username; if ($profile->save()) { echo "Profile of \"{$user->username}\" created\n"; } else { print_r($profile->getErrors()); } } }
protected function findModel($id) { if (($model = Advert::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } }
public function actionViewAdvert($id) { $this->layout = 'inner'; $model = Advert::findOne($id); $user = $model->user; $images = Common::getImageAdvert($model, false); return $this->render('view_advert', ['model' => $model, 'user' => $user, 'images' => $images]); }
/** * Creating model search query. * @return ActiveDataProvider|\yii\data\DataProviderInterface */ public function search($params = []) { $query = Advert::find()->with('owner.profile'); $dataProvider = new \roman444uk\yii\data\ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => \roman444uk\yii\widgets\WidgetPageSize::getPageSize()]]); if ($params && !($this->load($params) && $this->validate())) { return $dataProvider; } $this->buildQuery($query, $params); return $dataProvider; }
public function beforeAction($action) { $id = \Yii::$app->request->get('id'); $model = Advert::findOne($id); if (null == $model) { throw new HttpException(404, 'Unknown advert'); return false; } return parent::beforeAction($action); }
/** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Advert::find(); $dataProvider = new ActiveDataProvider(['query' => $query]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere(['idadvert' => $this->idadvert, 'price' => $this->price, 'fk_agent_detail' => $this->fk_agent_detail, 'badroom' => $this->badroom, 'livingroom' => $this->livingroom, 'parking' => $this->parking, 'kitchen' => $this->kitchen, 'hot' => $this->hot, 'sold' => $this->sold, 'recommend' => $this->recommend, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at]); $query->andFilterWhere(['like', 'address', $this->address])->andFilterWhere(['like', 'general_image', $this->general_image])->andFilterWhere(['like', 'description', $this->description])->andFilterWhere(['like', 'location', $this->location])->andFilterWhere(['like', 'type', $this->type]); return $dataProvider; }
public function up() { $this->upModules(); $tableOptions = null; if ($this->db->driverName === 'mysql') { $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB'; } // Advert table $this->createTable('advert', array('id' => 'pk', 'user_id' => 'int unsigned not null', 'city_id' => 'int unsigned', 'created_at' => 'int(11)', 'updated_at' => 'int(11)', 'type' => 'varchar(16)', 'category' => 'varchar(16)', 'content' => 'text default null', 'present' => 'tinyint(1) default 0', 'min_price' => 'int(11) default null', 'max_price' => 'int(11) default null', 'currency' => 'varchar(3)', 'term_at' => 'int(11)', 'views' => 'int(11) default 0', 'status' => 'enum("' . implode('","', Advert::getStatusList()) . '") default "' . Advert::STATUS_NEW . '"', 'likes' => 'int unsigned default 0', 'dislikes' => 'int unsigned default 0', 'published' => 'tinyint(1) default 0', 'is_templet' => 'tinyint(1) default 0', 'is_foreign' => 'tinyint(1) default 0'), $tableOptions); // Advert templet table $this->createTable('advert_templet', array('id' => 'pk', 'user_id' => 'int unsigned not null', 'advert' => 'text'), $tableOptions); // Category table $this->createTable('category', array('id' => 'pk', 'name' => 'varchar(64) not null', 'description' => 'varchar(128)', 'parent_id' => 'int unsigned not null'), $tableOptions); // City table $this->createTable('city', array('id' => 'pk', 'name' => 'varchar(64) not null', 'active' => 'tinyint(1) default 1'), $tableOptions); // User profile table $this->createTable('profile', array('id' => 'pk', 'user_id' => 'int unsigned not null', 'avatar_url' => 'varchar(256)', 'name' => 'varchar(64)'), $tableOptions); }
/** * Creating model search query. * @return ActiveDataProvider|\yii\data\DataProviderInterface */ public function search($params = []) { $query = Advert::find()->with('owner.profile', 'files'); // query city, bookmarks and likes $tableAdvert = self::tableName(); $tableBookmark = Yii::$app->getModule('bookmarks')->tableBookmark; $query->select("{$tableAdvert}.*, ({$tableAdvert}.id = {$tableBookmark}.target_id) as bookmarked, city.name as cityName"); $query->join('left join', $tableBookmark, "{$tableBookmark}.target_id = {$tableAdvert}.id"); $query->join('left join', 'city', 'advert.city_id = city.id'); // creating data provider $dataProvider = new \roman444uk\yii\data\ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => \roman444uk\yii\widgets\WidgetPageSize::getPageSize('advert-list')]]); if ($params && !($this->load($params) && $this->validate())) { return $dataProvider; } $this->buildQuery($query, $params); if ($this->search_bookmarks) { $query->andWhere(["{$tableAdvert}.id" => Yii::$app->getModule('bookmarks')->manager->getIdList($this->bookmark_user_id, ['Advert'], true)]); } return $dataProvider; }
public function actionFind($search = '', $price = '', $apartment = '') { $this->layout = 'sell'; $query = Advert::find(); $query->filterWhere(['like', 'address', $search])->orFilterWhere(['like', 'description', $search])->orFilterWhere(['type' => $apartment]); //$query->orFilterWhere(['type'=> $apartment]); if ($price) { $prices = explode("-", $price); if (isset($prices[0]) && isset($prices[1])) { $query->andWhere(['between', 'price', $prices[0], $prices[1]]); } else { $query->andWhere(['>=', 'price', $prices[0]]); } $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); $pages->setPageSize(1); $model = $query->offset($pages->offset)->limit($pages->limit)->all(); $request = Yii::$app->request; return $this->render('find', ['model' => $model, 'pages' => $pages, 'request' => $request]); } }
?> <div id="create-advert"> <!-- Advert form --> <?php $form = ActiveForm::begin(['id' => 'advert-form', 'enableClientValidation' => true, 'enableAjaxValidation' => true, 'validateOnBlur' => true, 'validationUrl' => Url::to(['validate', 'id' => $model->id]), 'fieldConfig' => ['template' => "{label}{input}"], 'clientEvents' => ['ajaxSubmitSuccess' => "function(data) {\n \$('a[data-update], a[data-view]').magnificPopup('close');\n return false;\n}"]]); ?> <div class="left"> <?php echo $form->field($model, 'city_id')->dropDownList(City::getList(), ['name' => $directPopulating ? 'city_id' : null, 'label' => 'City', 'emptyItem' => Yii::t('app', 'Empty city option')]); ?> <?php echo $form->field($model, 'type', [])->dropDownList(Advert::getTypesDropDownList(), ['name' => $directPopulating ? 'type' : null, 'emptyItem' => Yii::t('app', 'Empty type option')]); ?> <?php echo $form->field($model, 'category')->dropDownList(Category::getDropdownList(), ['name' => $directPopulating ? 'category' : null, 'emptyItem' => Yii::t('app', 'Empty category option')]); ?> <?php echo $form->field($model, 'term', ['template' => '{label}{input}'])->datepicker(['name' => $directPopulating ? 'term' : null, 'datepicker' => ['dateFormat' => Yii::$app->formatter->dateFormat, 'clientOptions' => ['maxDate' => "+1m", 'minDate' => "+1d", 'monthNamesShort' => DatepickerHelper::monthNamesShort()]]]); ?> <div class="range"> <label class="control-label" for="min_price"><?php echo Yii::t('app', 'Price'); ?> </label>
/** * @return array \common\models\Advert */ public function getAdverts() { return $this->hasMany(Advert::className(), ['user_id' => 'id']); }
/** * Test action. */ public function actionVk() { $wall = file_get_contents("https://api.vk.com/method/wall.get?owner_id=-120504421&filter=others"); $wall = json_decode($wall); foreach ($wall->response as $item) { if (is_object($item)) { $advert = new Advert(); $advert->setScenario(Advert::SCENARIO_CREATE_FROM_SERVICE); $advert->content = $item->text; $advert->created_at = $item->date; $advert->save(); if (isset($item->attachments)) { foreach ($item->attachments as $a) { $type = $a->type; $f = $a->{$type}; $file = new \common\models\Image(); $file->remote_url = $f->src_big; $file->created_at = $f->created; $file->save(); $file->attachOwner($advert->id, 'Advert', 'files'); } } } } }
<div class="col-sm-9"> <?php $form->field($model, 'content')->textarea([]); ?> <?php echo $form->field($model, 'content')->textarea(['name' => $directPopulating ? 'content' : null, 'rows' => 25]); ?> </div> <div class="col-sm-3"> <?php echo $form->field($model, 'city_id')->dropDownList(City::getList(), ['name' => $directPopulating ? 'city_id' : null, 'class' => 'form-control input-sm']); ?> <?php echo $form->field($model, 'type')->dropDownList(Advert::getTypesDropDownList(), ['name' => $directPopulating ? 'type' : null, 'class' => 'form-control input-sm']); ?> <?php echo $form->field($model, 'category')->dropDownList(Category::getDropdownList(), ['name' => $directPopulating ? 'category' : null, 'class' => 'form-control input-sm']); ?> <?php /*echo $form->field($model, 'term')->datepicker([ 'name' => ($directPopulating) ? 'term' : null, 'datepicker' => [ 'language' => 'ru', 'dateFormat' => 'dd.MM.yyyy' ] ])*/ ?>
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 = \frontend\components\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' => 20]); $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]); }
/** * * @param type $userId * @return type */ public static function getPublishedAdvertsCountSql() { if ($userId = Yii::$app->user->id) { $param = self::ADVERT_COUNT_ADDED_TODAY; $advertTable = Advert::tableName(); return $sql = <<<SQL select '{$param}' as param, count(*) as value from {$advertTable} where {$advertTable}.user_id = {$userId} SQL; } return null; }
/** * @inheritdoc */ public function extraFields() { // не обязательные поля return parent::extraFields(); }
<div class="col-sm-4 text-center"> {summary} </div> <div class="col-sm-4 text-right"> ' . WidgetPageSize::widget(['pjaxId' => 'advert-grid-pjax']) . ' </div> </div> {items} <div class="row"> <div class="col-sm-8"> {pager} </div> <div class="col-sm-4 text-right" style="padding-top: 20px"> ' . GridBulkActions::widget(['gridId' => 'user-grid']) . ' </div> </div>', 'columns' => [['class' => 'yii\\grid\\CheckboxColumn', 'options' => ['style' => 'width:10px']], ['class' => 'yii\\grid\\SerialColumn', 'options' => ['style' => 'width:10px']], ['attribute' => 'id', 'header' => '№', 'filterInputOptions' => ['class' => 'form-control input-sm']], ['attribute' => 'content', 'format' => 'raw', 'contentOptions' => ['style' => 'text-align: left'], 'filterInputOptions' => ['class' => 'form-control input-sm']], ['class' => 'roman444uk\\yii\\grid\\AjaxUpdateColumn', 'attribute' => 'status', 'fieldType' => AjaxUpdateColumn::FIELD_TYPE_DROPDOWN, 'fieldOptions' => ['class' => 'form-control input-sm', 'items' => Advert::getTranslatedStatusList()], 'filter' => Advert::getTranslatedStatusList(), 'filterInputOptions' => ['class' => 'form-control input-sm'], 'updateUrl' => function ($model, $key, $index) { return Yii::$app->urlManager->createUrl(['advert/update', 'id' => $key]); }, 'errorUpdate' => new JsExpression("function() {\n alert('error updating');\n }")], ['class' => 'roman444uk\\yii\\grid\\AjaxUpdateColumn', 'attribute' => 'category', 'fieldType' => AjaxUpdateColumn::FIELD_TYPE_DROPDOWN, 'fieldOptions' => ['class' => 'form-control input-sm', 'items' => Category::getDropdownList()], 'filter' => Category::getDropdownList(), 'filterInputOptions' => ['class' => 'form-control input-sm'], 'updateUrl' => function ($model, $key, $index) { return Yii::$app->urlManager->createUrl(['advert/update', 'id' => $key]); }, 'errorUpdate' => new JsExpression("function() {\n alert('error updating');\n }")], ['attribute' => 'city_id', 'header' => 'Город', 'value' => function ($model, $key, $index) { return $model->cityName; }, 'filter' => City::getList(), 'filterInputOptions' => ['class' => 'form-control input-sm'], 'format' => 'raw'], ['class' => 'yii\\grid\\DataColumn', 'attribute' => 'created_at', 'header' => 'Добавлено', 'format' => 'datetime', 'filter' => City::getList(), 'filterInputOptions' => ['class' => 'form-control input-sm']], ['class' => 'yii\\grid\\DataColumn', 'attribute' => 'updated_at', 'header' => 'Обновлено', 'format' => 'datetime', 'filter' => City::getList(), 'filterInputOptions' => ['class' => 'form-control input-sm']], ['class' => 'roman444uk\\yii\\grid\\StatusColumn', 'attribute' => 'published', 'filterInputOptions' => ['class' => 'form-control input-sm']], ['class' => 'roman444uk\\yii\\grid\\StatusColumn', 'attribute' => 'is_foreign', 'header' => 'Из сервиса', 'filter' => ['Да', 'Нет'], 'filterInputOptions' => ['class' => 'form-control input-sm']], ['class' => 'roman444uk\\yii\\grid\\ViewColumn', 'view' => '@backend/views/advert/_advert_grid_column', 'options' => ['style' => 'width:70px']], ['class' => 'yii\\grid\\ActionColumn', 'contentOptions' => ['style' => 'width:30px; text-align:center;'], 'buttons' => ['view' => function ($url, $model, $key) { return Html::a('<span class="glyphicon glyphicon-eye-open"></span><br>', $url, ['title' => Yii::t('yii', 'View'), 'data-pjax' => 0, 'data-view' => $key]); }, 'update' => function ($url, $model, $key) { return Html::a('<span class="glyphicon glyphicon-pencil"></span><br>', $url, ['title' => Yii::t('yii', 'Update'), 'data-pjax' => 0, 'data-update' => $key]); }]]]]); ?> <?php Pjax::end(); ?>