Yii2: Add 'user_id' when create a post - yii2

I have a 'post' table with attribute 'user_id' in it to know who have posted that post. I run into a problem, when create a post, the 'user_id' didn't add into database, which can't be null, so I can't continue from there. So how can I add 'user_id' of the user that is currently logging in, automatically.
I'm using Yii2 basic template.
Thanks

Or you could have a look at Blameable Behavior
BlameableBehavior automatically fills the specified attributes with the current user ID.
I use this in alot of my projects (often combined with sluggable and timeable) and its easy to use, just put the following in your Post model:
use yii\behaviors\BlameableBehavior;
public function behaviors()
{
return [
[
'class' => BlameableBehavior::className(),
'createdByAttribute' => 'user_id',
'updatedByAttribute' => false,
'attributes' => [
ActiveRecord::EVENT_BEFORE_VALIDATE => ['user_id'] // If usr_id is required
]
],
];
}
Referencing Behavior validation on validation behaviors.
If you want to do it manually like the other answers suggest, you need to change
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
to
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->user_id = \Yii::$app->user->identity->id
$model->save()
return $this->redirect(['view', 'id' => $model->id]);
}
Remember: when you validate before inputting the user id, the user_id can't be required in your model rules!

Apart from what Bloodhound suggest, you can also use the following code to get the currently logged in user ID:
$loggedInUserId = \Yii::$app->user->getId();

you can try this code
//To get whole logged user data
$user = \Yii::$app->user->identity;
//To get id of the logged user
$userId = \Yii::$app->user->identity->id
Look at the documentation for more details: doc .

Related

Laravel validation: unique rule to bring duplicated record back

I have not found anywhere a clean way of what I am exactly looking for so thought to give on here a try:
$validator = Validator::make($request->all(), [
'an_id' => 'unique:users,an_id',
'another_id' => 'unique:users,another_id',
'test_id' => 'unique:users,test_id',
]);
if ($validator->fails()) {
//
}
So, what I'd like to do is when a duplicate test_id is provided, is to not only fail but show me which user uses the same test_id.
Is this actually possible through Laravel's Validation?
If I understand correctly, is this what you want to achieve?
Update: maybe you want to get the duplicated user in the view.
Update2: a quick way to get and return the duplicated users, if any.
(Note: I haven't tested the code so maybe slight adjustments are needed)
$validator = Validator::make($request->all(), [
'an_id' => 'unique:users,an_id',
'another_id' => 'unique:users,another_id',
'test_id' => 'unique:users,test_id',
]);
if ($validator->fails()) {
//find the duplicated user
$duplicatedUserX = User::where(
'another_id', $request->input('another_id')
)->get();
$duplicatedUserY = User::where(
'test_id', $request->input('test_id')
)->get();
// add their test_id to error messagebag.
if(!empty($duplicatedUserX){
$validator->errors()
->add('duplicatedUserXId', $duplicatedUserX->id);
}
if(!empty($duplicatedUserY){
$validator->errors()
->add('duplicatedUserYId', $duplicatedUserY->id);
}
// Send duplicated users and messagebag back to View
return redirect()->back()
->with('dupUsers', [
'x' => $duplicatedUserX,
'y' => $duplicatedUserY,
])->withErrors($validator);
}

How to make that GridView buttons update and delete just only visible for admins?

I am new to Yii2 and I have 3 kind of user rights:
Admin, moderator and user. I have my GridView and I don't want to show for the user the Update and Delete buttons, just only the GridView. How should I do that?
Here is my actionCreate, there is an input form:
public function actionCreate()
{
$model = new Project();
$model->scenario = Project::SCENARIO_CREATE;
if ($model->load(Yii::$app->request->post())) {
if ($model->save()) {
Yii::$app->getSession()->setFlash('success', Yii::t('app', 'Skelbimas sėkmingai pridėtas!'));
return $this->redirect(['index']);
}
}
return $this->render('create', [
'model' => $model,
]);
}
I've tried to search the information according to this, but couldn't find useful ones. Thanks for any help or information.
To accomplish this, you have to use the property $visibleButtons of you ActionColum class.
So:
'visibleButtons' = [
'update' => Yii::$app->user->can('update'), // or whatever condition
'delete' => Yii::$app->user->can('update')
]
and so on. Each Key on the visibleButtons array is the name of the button.
Yii Framework's guide
    .........
        [
            'class'=>'yii\grid\ActionColumn',
            'template'=> '{view} {update} {delete} ',
            'buttons'=> [
                'update'=> function($url,$model) {
if (Yii::$app->user->can('admin')) {
                    returnHtml::a( '<span class="glyphicon glyphicon-pencil"></span>', $url);
}
                },
                'delete'=>function($url,$model,$key) {
if (Yii::$app->user->can('admin')) {
                        returnHtml::a('delete', $url);
}
                },
            ],
        ],
One possibility would be using the 'template' attribute of youe 'ActionColumn' like:
[
...
'template'=> (user has only user rights ? '{view}' ? '{view} {update} {delete}')
...
]
Please, bare in mind that even though this solution will hide the buttons for users with only user right, it won't prevent them of accessing update and delete action urls, so you have to check permissions also in the controller level.

How to set Authorization wise view in the Form in CakePHP-3.0

I want to set an authorization in the registration of a form using CakePHP 3.0.
Before asking here, i tried below things but no luck in my favor.
Suppose i have role field in the usersTable like 'superuser', 'admin', 'user'.
I want to provide permission superuser to make all the things like create admin and user. and then admin can create admin and user, and user can make user only.
The code i tried in the add function of UsersController.
if($this->Auth->user['role'] === 'superuser'){
$roles = $this->Users->find('list');
} elseif ($this->Auth->user['role'] === 'admin') {
$roles = $this->Users->find('list')->where(['Users.role !==' => 'superuser']);
} else {
$roles = $this->Users->find('list')->where(['Users.role' => 'user']);
}
after failing i tried below things in the add.ctp
if(!empty($this->request->session()->check('Auth.User.role') === 'superadmin')){
echo $this->Form->input('role',['options' => ['admin' => 'Admin', 'user' => 'User']]);
} elseif(!empty($this->request->session()->check('Auth.User.role') === 'admin')){
echo $this->Form->input('role',['options' => ['user' => 'User', 'icr' => 'ICR', 'routing' => 'Routing']]);
} else {
echo $this->Form->input('role', ['options' => ['user' => 'User']]);
}
Could you please suggest on this regard or is there any easiest way to do so?
Thanks
As outlined in your double post # google groups ( https://groups.google.com/forum/#!topic/cake-php/nTURwYME-6o ) you shoudn't blindy combine three things that have nothing in common, that is guaranteed to blow up.
if(!empty($this->request->session()->check('Auth.User.role') === 'superadmin')){}
should rather be
if ($this->request->session()->read('Auth.User.role') === 'superadmin') {}

Yii 2 Gridview - Search Query generates ambiguous fields

I am generating related records search query for Gridview use
I get this error :
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'dbowner' in where clause is ambiguous
The SQL being executed was: SELECT COUNT(*) FROM tbl_iolcalculation LEFT JOIN tbl_iolcalculation patient ON tbl_iolcalculation.patient_id = patient.id WHERE (dbowner=1) AND (dbowner=1)
I have two related models 1) iolcalculation and patient - each iolcalculation has one patient (iolcalculation.patient_id -> patient.id)
The relevant code in my model IolCalculationSearch is :
public function search($params)
{
$query = IolCalculation::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->sort->attributes['patient.lastname'] = [
'asc' => ['patient.lastname' => SORT_ASC],
'desc' => ['patient.lastname' => SORT_DESC],
];
$query->joinWith(['patient'=> function($query) { $query->from(['patient'=>'tbl_iolcalculation']); } ]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'patient_id' => $this->patient_id,
'preop_id' => $this->preop_id,
'calculation_date' => $this->calculation_date,
'iol_calculated' => $this->iol_calculated,
The reason this error is generated is that each model has an override to the default Where clause as follows, the reason being that multiple users data needs to be segregated from other users, by the field dbowner:
public static function defaultWhere($query) {
parent::init();
$session = new Session();
$session->open();
$query->andWhere(['t.dbowner' => $session['dbowner']]);
}
this is defined in a base model extending ActiveRecord, and then all working models extend this base model
How Can I resolve this ambiguous reference in the MySQL code?
Thanks in advance
$query->andFilterWhere([
// previous filters
self::tableName() . '.structure_id' => $this->structure_id,
// next filters
]);
I think, that you are searching for table aliases.
(https://github.com/yiisoft/yii2/issues/2377)
Like this, of course you have to change the rest of your code:
$query->joinWith(['patient'=> function($query) { $query->from(['patient p2'=>'tbl_iolcalculation']); } ]);
The only way I can get this to work is to override the default scope find I had set up for most models, so that it includes the actual table name as follows - in my model definition:
public static function find() {
$session = new Session();
$session->open();
return parent::find()->where(['tbl_iolcalculation.dbowner'=> $session['dbowner']]);
}
There may be a more elegant way using aliases, so any advice would be appreciated - would be nice to add aliases to where clauses, and I saw that they are working on this....

Retrieving and posting static dropdown data into mysql database in Zend 2

I have several fields in my form that i wish to post to the database. All the other fields bar the dropdown field are all working fine
The official documentation for zend 2 is not really clear on how to deal with posting data from a dropdown menu into the database
Here's what i have:
my addAction in the controller
public function addAction()
{
$form = new UsersForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$users = new Users();
$form->setInputFilter($users->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid())
{
$users->exchangeArray($form->getData());
$this->getUsersTable()->saveUser($users);
// Redirect to list of albums
return $this->redirect()->toRoute('index');
}
}
return array('form' => $form);
}
my form
public function __construct($name = null)
{
// we want to ignore the name passed
parent::__construct('users');
//other form elements...
//the dropdown menu
$this->add(array(
'type' => 'Select',
'name' => 'groupid',
'options' => array(
'label' => 'Group',
'value_options' => array(
'0' => 'Not Selected',
'1' => 'Super Admin',
'2' => 'Company Admin',
),
),
));
//...
}
}
the view
<?php
$form->setAttribute('action', $this->url('user', array('action' => 'add')));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formRow($form->get('groupid'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
When i run my application for the addAction, i get an error message:
Statement could not be executed (23000 - 1048 - Column 'GroupID' cannot be null)
where 'GroupID' is the column in my table that takes the value from the dropdown which means the field is not being posted
I need help on this
If the column in your database is GroupID, the form element should also be named that. Yours is groupid (i.e. lowercase). If that doesn't fix the issue, please edit your question to include the DB structure and the code for the saveUser() function.