cakePHP get users details of logged in user - cakephp-3.0

I am using the cakeManager plugin with cakePHP 3 to manage users. I have two user roles businesses and employees and I have tables for each with additional information.
When a user logs in I am trying to get the additional information with the users details but I cannot seem to get the associated tables with users.
Business Model:
/**
* Businesses Model
*/
class HotelsTable extends Table
{
/**
* Initialize method
*
* #param array $config The configuration for the Table.
* #return void
*/
public function initialize(array $config)
{
$this->table('businesses');
$this->displayField('name');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Users', [
'foreignKey' => 'user_id',
'joinType' => 'INNER'
]);
$this->hasMany('Employees', [
'foreignKey' => 'hotel_id'
]);
}
Extended Users Model from the plugin
namespace App\Model\Table;
use CakeManager\Model\Table\UsersTable as BaseUsersTable;
use Cake\Validation\Validator;
/**
* Users Model
*/
class UsersTable extends BaseUsersTable
{
/**
* Initialize method
*
* #param array $config The configuration for the Table.
* #return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->hasOne('Employees', [
'foreignKey' => 'user_id'
]);
$this->hasOne('Businesses', [
'foreignKey' => 'user_id'
]);
}
}
I have added the Businesses associations directly into plugin also to check is it an issue with the model extension.
Looking at the returned object I see the Roles model associations are also not returned so I suspect it is the plugins find is set to not retrieve assertions.
My problem is I don't know how to override this.

As of CakePHP 2.2 (http://bakery.cakephp.org/articles/lorenzo/2012/07/01/cakephp_2_2_and_2_1_4_released), the AuthComponent now accepts the 'contain' key for storing extra information in the session. I have checked with 3.0 and it still supports contain
'Auth' => [
'authorize' => 'Controller',
'userModel' => 'CakeManager.Users',
'authenticate' => [
'Form' => [
'contain' => [ 'Roles' ],
]
]
Look at this example to see how to change the default AuthComponent configurations.
Reference: https://gitter.im/cakemanager/cakephp-cakemanager?at=556389082e564d1f3abefc04

Related

How can I display in view multiple GridViews with one DataProvider group it by some field?

A have a table 'operations' with finance operations for all users, including 'id', 'user_id', 'sum', 'name', 'date_picked' etc.
I have created one ActiveDataProvider that gets all operations for concrete User. Now I would like to display in view data from this dataprovider - not in one GridView, but in several GridViews which data grouped by 'date_picked' value.
I know that I can make a new dataprovider for the each 'date_picked' but there will be a large amount of requests to database.
Is there a way to display grouped data in several GridViews based on one dataprovider's data?
Controller:
/** #var OperationComponent $comp */
$comp = Yii::$app->operation;
$userId = Yii::$app->user->id;
$filterModel = $comp->getOperationSearch();
$operations = $comp->getSearchProvider($userId, Yii::$app->request->get());
OperationComponent:
public function getOperationSearch()
{
return new OperationSearch();
}
public function getSearchProvider($user_id, $params)
{
$model = new OperationSearch();
return $model->search($user_id, $params);
}
OperationSearch:
public function search($user_id, $params)
{
$query = Operation::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 10,
],
// сортировка по умолчанию
'sort' => [
'defaultOrder' => [
'date_picked' => SORT_DESC
]
]
]);
return $dataProvider;
View:
....
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $filterModel,
.....
]); ?>
....
There is an Yii2 extension for complex GridViews: kartik-v/yii2-grid
It contains collapsible rows for showing details for a row.
You can view a demo here.
What you are looking for is the Expand Row Column Widget. It allows to expand a row by just loading the required data for this row details.
This extension has a good documentation is quite stable and tested and can be used straight forward.

CakePHP 3 is saying a table doesn't exist in another database when using an ORM query

I have an application in CakePHP 3.5.13 which uses four different databases.
In my config/app.php I have configured two of these as follows:
'Datasources' => [
'default' => [ 'database' => 'sdb5_hub_subdb', ... ],
'db_orgs' => [ 'database' => 'dev_hub_subdb_orgs', ... ]
];
So this means there are 2 databases with the names sdb5_hub_subdb and dev_hub_subdb_orgs.
I'm attempting to do a query which does a join on a table in each database.
I have my Table entities configured as follows:
// src/Model/Table/TblListsSubstancesCommentsTable.php
public function initialize(array $config)
{
$this->belongsTo('Substances', [
'foreignKey' => 'substance_id',
'joinType' => 'INNER'
]);
}
public static function defaultConnectionName()
{
return 'db_orgs';
}
// src/Model/Table/SubstancesTable.php
public function initialize(array $config)
{
$this->belongsTo('TblListsSubstancesComments', [
'foreignKey' => 'substance_id'
]);
}
When I attempt to do the following with the ORM:
$query = $Substances->find()->select(['id' => 'Substances.id'])->distinct();
if ($this->request->getData('org_information')) {
$org_information = $this->request->getData('org_information');
$query = $query->matching('TblListsSubstancesComments', function ($q) use ($org_information) {
return $q->where(['TblListsSubstancesComments.comment LIKE' => '%'.$org_information.'%' ]);
});
}
It's producing an SQL error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'sdb5_hub_subdb.tbl_lists_substances_comments' doesn't exist
I don't understand this because the table definitely exists. Furthermore my TblListsSubstancesCommentsTable.php has defaultConnectionName() in it to specify that it should use the db_orgs connection. So I assume it must know to go to the second database to load that table? It's like it's looking in the default database and not finding it, but I don't know why, because the Table entity is telling it where it needs to look.

Validation rule unique requires at least 1 parameters. laravel 5.4

I've got problem with my laravel 5.4 I can't save the data
public function rules()
{
return [
'permission_id' => 'required|unique',
'name' => 'required',
'label' => 'required',
];
}
Error
Validation rule unique requires at least 1 parameters.
the unique rule need at least the name of ur database table.
ur rules function should be like this:
public function rules()
{
return [
'permission_id' => 'required|unique:db_table_name',
'name' => 'required',
'label' => 'required',
];
}
for more informations check laravel doc unique rule

Yii2 dektrium add new field to user model and change it in account form

I have added a new field to user model 'paypal' and need to change it in overridden account form.
Override user model
<?php
namespace common\models;
class User extends \dektrium\user\models\User
{
public function scenarios()
{
$scenarios = parent::scenarios();
$scenarios['create'][] = 'paypal';
$scenarios['update'][] = 'paypal';
$scenarios['register'][] = 'paypal';
return $scenarios;
}
public function rules()
{
$rules = parent::rules();
$rules['paypalLength'] = ['paypal', 'string', 'max' => 255];
return $rules;
}
}
Override SettingsForm model
<?php
namespace common\models;
class SettingsForm extends \dektrium\user\models\SettingsForm
{
public $paypal;
public function rules()
{
$rules = parent::rules();
$rules['paypalLength'] = ['paypal', 'string', 'max' => 255];
return $rules;
}
}
Configure module
'user' => [
'class' => 'dektrium\user\Module',
'modelMap' => [
'User' => 'common\models\User',
'RegistrationForm' => 'common\models\RegistrationForm',
'SettingsForm' => 'common\models\SettingsForm',
],
'controllerMap' => [
...
And I have overridden account form view. When I'm trying to change paypal field in user/settings/account it doesn't change it. What should I do to make it work?
Thanks.
Also you must override view paths:
'view' => [
'theme' => [
'pathMap' => [
'#dektrium/user/views' => '#app/views/user',
],
],
],
And after that open #vendor/dektrium/yii2-user/views and make a folder on #app/views based on dektrium view folders. For example create a folder named admin (because you have on #vendor/dektrium/yii2-user/views a folder named admin) and create corresponded folder on app views, i.e. #app/views/admin.
After that create your view file that you want to change on #app/views/[dektrium-folder] and change it.

Yii2 Yii::$app->user->identity->id returns an error instead of redirecting to login page

in my behaviours I have specified that actionList can only be viewed by authenticated users.
$behaviors [ 'access' ] = [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => [ 'list' ],
'allow' => ['#'],
]
],
];
In actionList I'm getting the user_id:
public function actionList() {
$user_id = \Yii::$app->user->identity->id;
return $this->render( 'list' );
}
All good, but if you go to this action when not logged in, you get an error:
PHP Notice – yii\base\ErrorException
Trying to get property of non-object
Makes sense, I'm not logged in so I don't have a user id, but why does the code go that far? If I comment the $user_id = \Yii::$app->user->identity->id; out, I get redirected to the login page, which is the expected behaviour. I don't think I should have to do yet another check to see if someone is logged in in the action itself, shouldn't that be handled by the behaviours['access'] beforehand?
Try this changing the allow and roles attributes:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['list'],
'allow' => true,
'roles' => ['#'],
],
], // rules
], // access
];
}
More info here.
Here is my cent to the already good answers above
Add following code to the main controller file in your project (not the base controller) but some controller above this which is base for every other controller
/**
* Check if user is logged in and not logged out
*
* #param type $action
* #return type
*/
public function beforeAction($action) {
$this->enableCsrfValidation = false;
if(!empty($action) && $action->actionMethod == 'actionLogin') {
return true;
}
/* Check User's Login Status */
if (is_null(Yii::$app->user->identity)) {
$this->redirect(Url::to(['../site/login']));
Yii::$app->end();
}
return true;
}