I am new to yii2.I have created model,separate search model,views and controller using gii.There is search in my index form and it is not working.
Should i modify the code generated by gii to make it working?
My index view code is like this:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'user_name',
'eng_full_name',
'phone',
'mobile',
'email:email',
[
'label' => 'Status',
'attribute' => 'status',
'value' => 'userStatus.cv_lbl',
],
[
'class' => 'yii\grid\ActionColumn',
'contentOptions' => [
'style' => 'width:80px;',
],
],
],
]) ?>
My controller:
public function actionIndex()
{
$searchModel = new UserSearch();
$dataProvider = $searchModel->search([Yii::$app->request->queryParams]);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
My search model is:
public function rules()
{
return [
[['user_id', 'br_id', 'role_id', 'designation', 'created_by', 'updated_by', 'update_count', 'status', 'type'], 'integer'],
[['user_name'],'string'],
[['user_name', 'user_password', 'eng_full_name', 'nep_full_name', 'phone', 'mobile', 'email', 'remarks', 'created_dt', 'updated_dt'], 'safe'],
];
}
public function search($params)
{
$query = UserAccounts::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => array('pageSize' => 50),
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andFilterWhere([
'designation' => $this->designation,
'status' => $this->status,
'type' => $this->type,
]);
$query->andFilterWhere(['like', 'user_name', $this->user_name])
->andFilterWhere(['like', 'user_password', $this->user_password])
->andFilterWhere(['like', 'eng_full_name', $this->eng_full_name])
->andFilterWhere(['like', 'phone', $this->phone])
->andFilterWhere(['like', 'mobile', $this->mobile])
->andFilterWhere(['like', 'email', $this->email])
->andFilterWhere(['like', 'remarks', $this->remarks]);
return $dataProvider;
}
My userAccounts model:
class UserAccounts extends ActiveRecord implements IdentityInterface
{
public $username;
public $user_password_repeat;
public $old_password;
public static function tableName()
{
return 'user_accounts';
}
public function rules()
{
return [
[['user_name', 'user_password', 'role_id', 'eng_full_name', 'designation', 'status', 'user_password_repeat'], 'required'],
[['br_id', 'role_id', 'designation', 'created_by', 'updated_by', 'update_count', 'status', 'type'], 'integer'],
[['created_dt', 'updated_dt','user_password_repeat'], 'safe'],
[['user_name', 'user_password', 'eng_full_name', 'email'], 'string', 'max' => 50],
[['phone', 'mobile'], 'string', 'max' => 10],
[['remarks'], 'string', 'max' => 500],
[['user_name'], 'unique'],
[['user_password'], 'compare'],
['old_password', 'required' ,'on' => 'changePassword'],
['old_password', 'compareCurrentPassword', 'on' => 'changePassword'],
];
}
public function attributeLabels()
{
return [
'user_id' => 'User ID',
'user_name' => 'user name',
'user_password' => 'password',
'user_password_repeat' =>'Confirm Password',
'br_id' => 'Br ID',
'role_id' => 'role id',
'eng_full_name' => 'eng name',
'phone' => 'phone',
'mobile' => 'mobile',
'designation' => 'designation',
'email' => 'email',
'remarks' => 'remarks',
'created_by' => 'Created By',
'created_dt' => 'Created Dt',
'updated_by' => 'Updated By',
'updated_dt' => 'Updated Dt',
'update_count' => 'Update Count',
'status' => 'Status',
'type' => 'type',
'old_password'=>'old password'
];
}
}
You are sending the search params incorrectly in your controller:
$dataProvider = $searchModel->search([Yii::$app->request->queryParams]);
You need to send them without the square brackets:
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
Ok I found the answer for my question.Sometimes jquery files included with in the project may cause such problems.There may be conflict between jquery files.In my case ,i had included jquery-2.2.3.min.js.When i removed that files Search is working properly.
Related
I've been facing the problem since two days ago. But, can't fix it either. I have submitted all the necessary coding information below. Please, help me out.
Here is my controller...
<?php namespace App\Controllers;
use App\Models\UserModel;
use App\Controllers\BaseController;
class UserController extends BaseController
{
protected $userModel;
public function __construct()
{
$this->userModel = new UserModel();
}
public function registration() {
if($this->request->getMethod() == 'post'):
$rules = $this->userModel->getValidationRules(['only' => ['user', 'email', 'password',
'confirm_password', 'gender']]);
if(!$this->validate($rules)):
$this->session->setFlashdata('errors', $this->validator->getErrors());
return redirect()->back()->withInput();
else:
$data = $this->request->getPost();
unset($data['confirm_password'], $data['registration'], $data['ci4app_auto_fill']);
if($this->userModel->insert($data)):
$this->session->setFlashdata('success', 'Your registration has been done successfully. Thank you.');
return redirect()->to('login');
else:
echo "Sorry! Your registration has not been successful. Please, try again. Thank you.";
endif;
endif;
endif;
}
}
and here is my model
<?php namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $returnType = 'array';
protected $allowedFields = ['user', 'name', 'email', 'phone', 'gender', 'password', 'address',
'city', 'estate', 'country', 'image'];
protected $beforeInsert = ['hashPassword'];
protected $useSoftDeletes = true;
protected $useTimestamps = false;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
protected $validationRules = [
'user' => [
'label' => 'User ID',
'rules' => 'trim|required|is_unique[users.user,id,{id}]|alpha_numeric|min_length[3]'
],
'gender' => [
'label' => 'Gender',
'rules' => 'trim|required'
],
'email' => [
'label' => 'E-mail ID',
'rules' => 'trim|required|is_unique[users.email,id,{id}]|valid_email'
],
'password' => [
'label' => 'Password',
'rules' => 'trim|required|min_length[5]'
],
'confirm_password' => [
'label' => "Password Confirmation",
'rules' => 'trim|required|matches[password]'
],
'phone' => [
'label' => 'Phone Number',
'rules' => 'trim|numeric|max_length[13]|is_unique[users.phone,id,{id}]'
],
'address' => [
'label' => 'Address',
'rules' => 'trim|alpha_numeric_space'
],
'city' => [
'label' => 'City',
'rules' => 'trim|alpha_numeric_space'
],
'estate' => [
'label' => 'Estate',
'rules' => 'trim|alpha_space'
],
'country' => [
'label' => 'Country',
'rules' => 'trim|alpha_space'
]
];
protected $validationMessages = [];
protected $skipValidation = false;
public function hashPassword($data) {
if(! isset($data['data']['password'])) return $data;
$data['data']['password'] = password_hash($data['data']['password'], PASSWORD_DEFAULT);
return $data;
}
}
Neither data is being inserted nor any error has occurred!
What is the problem for I couldn't insert data into my database?
Now please tell me, how I can solve this problem. Thank you...
How get i sort my rows by field i get from model getter like this
* Returns the score for this team
*/
public function getScore() {
$score = 0;
if (!empty($this->bonus_points)) {
$score += $this->bonus_points;
}
foreach (Attempt::find()->where(['team_id' => $this->id, 'marked' => 1])->all() as $attempt) {
$score -= $attempt->cost;
$score += $attempt->reward;
}
return $score;
}
View Code
GridView::widget([
'id' => 'quickfire-grid',
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'filterPosition' => GridView::FILTER_POS_HEADER,
'tableOptions' => [
'class' => 'table'
],
'layout' => "{summary}\n{items}\n{pager}",
'columns' => [
['class' => 'yii\grid\CheckboxColumn'],
'name',
[
'attribute' => 'bonus_points',
'label' => 'Adjustment',
'filter' => false
],
[
'attribute' => 'score',
'label' => 'Score',
'filter' => false,
],
[
'label' => 'Adjust score',
'format' => 'raw',
'value' => function ($data) use ($game) {
return Html::input('text', 'score-' . $data->id, '0', ['id' => 'score-' . $data->id]) . ' ' . Html::a('Adjust score', '#', ['class' => 'btn btn-danger btn-adjust-score', 'data-team-id' => $data->id, 'data-href' => Url::toRoute(['adjust-scores', 'game_id' => $game->id, 'skipConfirmation' => true])]);
},
],
],
]);
Is it possible to sort grid by score field ? I think need to add some javascript code. I have read this article but there is no solution https://www.yiiframework.com/wiki/621/filter-sort-by-calculatedrelated-fields-in-gridview-yii-2-0.
Team::find()->select(['total_score' => 'ifnull(s.score, 0)+team.bonus_points'])
->leftJoin([
's' => Attempt::find()
->select('team_id, SUM(reward-cost) as score')
->where(['marked' => 1])
->groupBy('team_id')
], 's.team_id=team.id')
->orderBy('total_score')
Something like this) Modify select with your needs...
i use yii2 basic app and have gridview with filter and search.
i want pagination that for each 10 record. what can i do?
i know add pagination in dataprovider but how can add this to my function?
please help me.
this is important for me.
i do many search but can't find solution for this
controller:
public function actionIndex()
{
$searchModel = new ContactSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel'=>$searchModel,
'dataProvider' => $dataProvider,
]);
}
model\contactsearch.php
<?php
namespace app\models;
use app\models\Contact;
use yii\base\Model;
use yii\data\ActiveDataProvider;
class ContactSearch extends Contact {
public function rules() {
return [
[['f_name', 'l_name', 'phone_number', 'Mobile_number'], 'safe'],
];
}
public function scenarios() {
return Model::scenarios();
}
public function search($params) {
$query = Contact::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'l_name' => SORT_DESC,
],
],
]);
if (!(($this->load($params) && $this->validate()))) {
return $dataProvider;
}
$query->andFilterWhere(['like', 'f_name', $this->f_name])
->andFilterWhere(['like', 'l_name', $this->l_name])
->andFilterWhere(['like', 'phone_number', $this->phone_number])
->andFilterWhere(['like', 'Mobile_number', $this->Mobile_number]);
//->andorderBy('id asc');
return $dataProvider;
}
}
?>
view
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel'=>$searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'f_name',
'l_name',
'phone_number',
'Mobile_number',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
To customize record amount in gridview
$dataProvider = new ActiveDataProvider([
'query' => $query,
//show 10 items per page
'pagination' => [
'pagesize' => 10,
],
'sort' => [
'defaultOrder' => [
'l_name' => SORT_DESC,
],
Other option is:
stackoverflow link
In controller:
function actionIndex()
{
$query = Article::find()->where(['status' => 1]);
$countQuery = clone $query;
$pages = new Pagination(['totalCount' => $countQuery->count()]);
$models = $query->offset($pages->offset)
->limit($pages->limit)
->all();
return $this->render('index', [
'models' => $models,
'pages' => $pages,
]);
}
In view file:
foreach ($models as $model) {
// display $model here
}
// display pagination
echo LinkPager::widget([
'pagination' => $pages,
]);
Here is my ClientsController:
namespace App\Controller\Api;
use App\Controller\Api\AppController;
class ClientsController extends AppController{
public $paginate = [
'page' => 1,
'limit' => 5,
'maxLimit' => 15,
'fields' => [
'id', 'name', 'user_id', 'dob', 'phone', 'email'
],
'sortWhitelist' => [
'id', 'name', 'user_id', 'dob', 'phone', 'email'
]
];
public function index(){
$clients = $this->Clients->find('clients');
$this->set([
'clients'=>$clients,
'_serialize'=>['clients']
]);
}
}
Here is my custom Finder (ClientsTable):
public function findClients(Query $query, array $options){
$query
->select([
'clients.id',
'clients.name'
])
->where(['clients.user_id =' => 3]);
return $query;
}
How can I add pagination to this? This all works great it's just lacking pagination.
If I remove the index function I get pagination but then my finder doesn't seem to be called. This is how that code looks:
namespace App\Controller\Api;
use App\Controller\Api\AppController;
class ClientsController extends AppController{
public $paginate = [
'page' => 1,
'limit' => 5,
'finder' => 'clients',
'maxLimit' => 15,
'fields' => [
'id', 'name', 'user_id', 'dob', 'phone', 'email'
],
'sortWhitelist' => [
'id', 'name', 'user_id', 'dob', 'phone', 'email'
]
];
}
I don't have experience with using the "finder" option on the pagination array, but you should be able to just pass your query to the paginate function, along these lines:
$clients = $this->paginate($this->Clients->find('clients'));
You can try below code
$this->loadComponent('Paginator'); /*Load the Paginator component*/
$clients = $this->Paginator->paginate($this->Clients->findClients()); /*Pass your finder method to the Paginator*/
Here is the documentation for directly use of Paginator components Using the Paginator Directly
In Kartik Yii2 Export, While exporting as Excel am getting This Page Cant't Reached Error in Localhost.
if i export as Text or CSV, export get worked but if i open the exported file Text or CSV, Half the
report is printing like html code
Help will be really appreciated.
GridCode:
<?php $gridColumns = [
['class' => 'yii\grid\SerialColumn'],
'membercode',
'member_name',
[
'attribute' => 'payment_category',
'format' => 'raw',
'label' => 'Payment Category',
'value' => function($model, $key, $index, $grid) {
$temp = $model->payment_category;
$si = Category::find()->where(['category_id' => $temp])->one();
return $si['category_name'];
},
],
'member_gender',
'member_address:ntext',
'payment_date',
'amount',
'receipt_no',
'payment_mode',
'pledge_amount',
'young_amount',
'tv_amount',
'building_amount',
[
'attribute' => 'payment_subcategory',
'format' => 'raw',
'value' => function($model, $key, $index, $grid) {
$exp = explode(',', $model->payment_subcategory);
$relation_name = ArrayHelper::map(Subcategory::find()->where(['subcategory_id' => $exp])->all(), 'subcategory_id', 'subcategory_name');
$relation = implode(',', $relation_name);
return $relation;
},
'filter' => Html::activeDropDownList($searchModel, 'payment_subcategory', ArrayHelper::map(Subcategory::find()->asArray()->all(), 'id', 'subcategory_name'),['class'=>'form-control','multiple' => true]),
],
['class' => 'yii\grid\ActionColumn'],
]; ?>
<?= ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' => $gridColumns,
'columnSelectorOptions'=>[
'label' => 'Columns',
'class' => 'btn btn-danger'
],
'fontAwesome' => true,
'dropdownOptions' => [
'label' => 'Export All',
'class' => 'btn btn-primary'
]
]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumns,
'pager' => [
'firstPageLabel' => 'First',
'lastPageLabel' => 'Last',
],
]); ?>
Above is my Grid view Code.
Help will be really appreciated.
Updated:
Error geeting while exporting as CSV:
Error geeting while exporting as EXCEL
There is an issue in your gridview, one of the field in gridview carries "=" equal to sign. please check it out PhpOffice/PhpExcel
Try exportConfig settings this
<?= ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' => $gridColumns,
'columnSelectorOptions'=>[
'label' => 'Columns',
'class' => 'btn btn-danger'
],
'fontAwesome' => true,
'dropdownOptions' => [
'label' => 'Export All',
'class' => 'btn btn-primary'
]
'exportConfig' => [
ExportMenu::FORMAT_HTML => false,
ExportMenu::FORMAT_TEXT => false,
],
]); ?>
Try this code for your GridVew::Widget:
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumns,
'exportConfig'=> [
GridView::CSV=>[
'label' => 'CSV',
'icon' => '',
'iconOptions' => '',
'showHeader' => false,
'showPageSummary' => false,
'showFooter' => false,
'showCaption' => false,
'filename' => 'yii',
'alertMsg' => 'created',
'options' => ['title' => 'Semicolon - Separated Values'],
'mime' => 'application/csv',
'config' => [
'colDelimiter' => ";",
'rowDelimiter' => "\r\n",
],
],
],
]);