Insert function at controller with model doesn't work in codeigniter4.. How can I solve this? - codeigniter-4

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...

Related

Sorting calculated fields in Yii2 (Grid View) getter param

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...

set pagination for gridview have filters in yii2 basic app

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,
]);

search not working with separate search model in yii2

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.

How to add pagination to custom query in CakePHP3

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

yii2: SqlDataProvider with pagination and searcModel getting error preg_match() expects parameter 2 to be string, object given

i want to show data using sqlDataProvider to gridview from different table and calculate it, here my code in siteController.php
public function actionSyahriyah()
{ $searchModel = new SyahriyahSearch();
$db = Yii::$app->db;
$bayar = $db ->createCommand('SELECT sy.no_syahriyah, sy.banyak, sa.nama, sy.tgl, sa.tarif
FROM santri sa, syahriyah sy
WHERE sa.no_induk = sy.no_induk
ORDER BY sy.tgl');
$dataProvider = new SqlDataProvider([
'sql' => $bayar,
'pagination' => [
'pageSize' => 5
],
]);
return $this->render('syahriyah',[
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
and this is the gridview:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
// ['class' => 'yii\grid\SerialColumn'],
'tgl',
'banyak',
],
'export' => false,
]);
?>
You can use dataProvider
<?php
$bayar = $db ->createCommand('SELECT sy.no_syahriyah, sy.banyak, sa.nama, sy.tgl, sa.tarif
FROM santri sa, syahriyah sy
WHERE sa.no_induk = sy.no_induk
ORDER BY sy.tgl');
$dataProvider = new SqlDataProvider([
'sql' => $bayar,
'pagination' => [
'pageSize' => 5
],
],
]);
?>

Resources