Yii2 insert date and time in sql - php

I am creating a yii application and I want to insert data into the database but the problem is how to insert date and time. It fails to insert every detail until I remove the date time column from the database .
This is the controller class:
<?php
namespace app\controllers;
use amnah\yii2\user\models\User;
use app\models\Influence;
use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use amnah\yii2\user\controllers\DefaultController as SuperDefault;
class DefaultController extends SuperDefault {
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['index', 'confirm', 'resend', 'logout'],
'allow' => true,
'roles' => ['?', '#'],
],
[
'actions' => ['account', 'profile','contact', 'resend-change', 'cancel','advertiser_dashboard','influencer_dashboard', 'influenza_info', 'advertiser'],
'allow' => true,
'roles' => ['#'],
],
[
'actions' => ['login', 'register','contact','influencer_dashboard', 'advertiser_dashboard','register_advert','forgot', 'reset', 'login-email', 'login-callback'],
'allow' => true,
'roles' => ['?'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post', 'get'],
],
],
];
}
public function actionInfluenza_info()
{
$u_id = Yii::$app->user->id;
$user = User::findOne($u_id);
$influence= new Influence();
if ($influence->load(Yii::$app->request->post())) {
$influence_data = Yii::$app->request->post('Influence', []);
$influence->firstname = $influence_data['firstname'];
$influence->lastname = $influence_data['lastname'];
$influence->email = $influence_data['email'];
$influence->city = $influence_data['city'];
$influence->type = $influence_data['type'];
$influence->pic = $influence_data['pic'];
$influence->address = $influence_data['address'];
$influence->country = $influence_data['country'];
$influence->gender = $influence_data['gender'];
$influence->id = $u_id;
$influence->save();
Yii::$app->session->setFlash("Profile-success", Yii::t("user", "Profile updated"));
return $this->refresh();
} else {
return $this->render('influenza_info', [
'user' => $user,
'influence' =>$influence
]);
}
}
}
this is the model class
<?php
namespace app\models;
use Yii;
use app\controllers\Expression;
/**
* This is the model class for table "influence".
*
* #property integer $id
* #property integer $user_id
* #property string $firstname
* #property string $lastname
* #property string $email
* #property string $city
* #property string $type
* #property string $pic
* #property string $address
* #property string $country
* #property string $gender
*/
class Influence extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'influence';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id', 'user_id', 'firstname', 'lastname', 'email', 'city', 'type', 'pic', 'address', 'country', 'gender'], 'required'],
[['id', 'user_id'], 'integer'],
[['firstname', 'lastname', 'email', 'city', 'type', 'pic', 'address', 'country', 'gender'], 'string', 'max' => 30]
];
}
public function beforeSave($insert)
{
if ($this->isNewRecord) { // new record only, otherwise time is inserted every time this record is updated
$this->created_at = new Expression('NOW()');
}
parent::afterSave($insert);
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'firstname' => 'Firstname',
'lastname' => 'Lastname',
'email' => 'Email',
'city' => 'City',
'type' => 'Type',
'pic' => 'Pic',
'address' => 'Address',
'country' => 'Country',
'gender' => 'Gender',
'created_at' => 'Created_at',
];
}
}
the table sql
CREATE TABLE `influence` (
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`firstname` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`lastname` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`city` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`type` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`pic` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`address` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`country` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`gender` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`created` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP
) ;
how do i make it insert automatically. if i try it from my admin it works and gets the dateand time . but with yii it does not.

To do this I remove the created attribute from the required rule.
I then create a beforeSave() method and on a new record insert it with Expression.
public function beforeSave($insert)
{
if ($this->isNewRecord) { // new record only, otherwise time is inserted every time this record is updated
$this->created = new Expression('NOW()');
}
parent::beforeSave($insert);
}
Make sure you import Expression into the model
Update
updated code thanks #crafter

you should use the Expression in the following way. Refer this link Class yii\db\Expression
When an Expression object is embedded within a SQL statement or fragment, it will be replaced with the $expression property value without any DB escaping or quoting. For example,
$expression = new Expression('NOW()');
$now = (new \yii\db\Query)->select($expression)->scalar(); // SELECT NOW();
echo $now; // prints the current date

The issue is that you are confusing the beforeSave and afterSave events.
In addition, your field name is created, not created at.
public function beforeSave($insert)
{
if ($this->isNewRecord) { // new record only, otherwise time is inserted every time this record is updated
$this->created = new Expression('NOW()'); // <== You were setting $this->created_at
}
parent::beforeSave($insert); // <== You were calling afterSave()
}

You have
`created` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP
in you db table but seems you have model field created as a string.
* #property string $created
check if there is mismatch problem related to ths field and eventually provide the right conversion before save or change the model (or the db) in order to have the same data type ..
Anyway you don't have rules for $created and the is not POSTED
add
public function rules()
{
return [
[['id', 'user_id', 'firstname', 'lastname', 'email', 'city', 'type', 'pic', 'address', 'country', 'gender'], 'required'],
[['id', 'user_id'], 'integer'],
[['firstname', 'lastname', 'email', 'city', 'type', 'pic', 'address', 'country', 'gender'], 'string', 'max' => 30]
[['created',], 'safe'],
];
}
Try also
$influence->save(false);
in this way you save the data withot validation check (use this only for debugging) if in this way the model is saved the try addding
[['created'], 'date'],
in rules

Related

Yii2 adding an extra field to the form to add to database

On an existing project there is a table with 3 fields (ID, name, label)
`id` int(11) NOT NULL,
`name` varchar(32) DEFAULT NULL,
`label` varchar(1) DEFAULT 'A'
Currently, on the products/create and products/update pages there is a form with only one field for 'name'. I need to add another field 'label'.
Before the update, models/Products.php has this code:
class Products extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'products';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['name'], 'string', 'max' => 32],
[['name'], 'unique'],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'name' => Yii::t('app', 'Name'),
];
}
}
I add the following to the above file, but no new input field is added to the form on the page:
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'name' => Yii::t('app', 'Name'),
'label' => Yii::t('app', 'Prefix'),
];
}
I also tried adding to the rules like this, but no joy
public function rules()
{
return [
[['name', 'label'], 'string', 'max' => 32],
[['name', 'label'], 'unique'],
];
}
You need to add the field to the HTML form.
If you open the file products/views/_form you will see the following line:
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
You need to add a new field for the label attribute, Yii will use the rules and label from the model to generate the field for the attribute, add this new line:
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'label')->textInput(['maxlength' => true]) ?>
Given your table fields:
`id` int(11) NOT NULL,
`name` varchar(32) DEFAULT NULL,
`label` varchar(1) DEFAULT 'A'
You probably want to update the rules to this, not to the ones you show:
public function rules()
{
return [
[['name',], 'string', 'max' => 32],
[['label',], 'string', 'max' => 1],
[['name',], 'unique'],
// Do not make label unique.
// [['name', 'label'], 'unique'],
];
}
label has a max length of 1 on the database, if you give it a max length of 32 on the ActiveRecord, it will let the user enter values longer than 1 byte, it will try to insert that value into the database, and an exception will be thrown.
If you make label unique, since it has a max length of 1, that will limit the maximum number of records that the table can hold to 256. You won't be able to reuse any of the labels, for example, there cannot be two records labeled "A", since that is the default value for the column, if you already have a record labeled "A" and you try to insert a new record leaving the label field empty, it will also result in an exception.
You may want to consider adding a required rule if you keep unique:
[['label',], 'required'],

Laravel 7 - Problem with unique constraint on update

I'm trying to add unique validation to my model, but there is an error when I tried to update the data.
The table:
acq_m_budgets
==================================
budget_id serial NOT NULL,
budget_code character varying(15) NOT NULL,
budget_name character varying(100) NOT NULL,
ma_code character varying(10),
start_period timestamp without time zone NOT NULL,
end_period timestamp without time zone NOT NULL,
budget numeric(16) DEFAULT 0,
credit numeric(16) DEFAULT 0,
debet numeric(16) DEFAULT 0,
balance numeric(16) DEFAULT 0,
reserve numeric(16) DEFAULT 0,
created_by character varying(100) NOT NULL,
created_on timestamp without time zone DEFAULT now(),
updated_by character varying(100) NOT NULL,
updated_on timestamp without time zone DEFAULT now(),
CONSTRAINT PK_AcqMBudgets PRIMARY KEY (budget_id),
CONSTRAINT UN_AcqMBudgets UNIQUE (budget_code)
My model: AcqMBudgets.php
class AcqMBudgets extends Model
{
public $timestamps = false;
protected $primaryKey = 'budget_id';
public $sortable = ['budget_code', 'budget_name', 'ma_code', 'balance', 'updated_on'];
protected $fillable = ['budget_code', 'budget_name', 'ma_code', 'start_period', 'end_period', 'budget', 'credit', 'debet', 'balance', 'reserve', 'created_by', 'created_on', 'updated_by', 'updated_on'];
protected $attributes = [
'budget' => 0,
'credit' => 0,
'debet' => 0,
'balance' => 0,
'reserve' => 0,
];
public static function createRules()
{
return [
'budget_code' => 'required|unique:acq_m_budgets,budget_code|max:15',
'budget_name' => 'required|max:100',
'ma_code' => 'max:10',
'start_period' => 'required',
'end_period' => 'required',
];
}
public static function updateRules($id)
{
return [
'budget_code' => 'required|unique:acq_m_budgets,budget_code,' . $id . '|max:15',
'budget_name' => 'required|max:100',
'ma_code' => 'max:10',
'start_period' => 'required',
'end_period' => 'required',
];
}
}
My Controller: BudgetController.php
...
public function create(Request $request)
{
$validateData = $request->validate(AcqMBudgets::createRules());
$model = new AcqMBudgets;
$post = $request->only($model->getFillable());
$post['start_period'] = (!empty($post['start_period'])) ? date('Y-m-d', strtotime(str_replace('/', '-', $post['start_period']))) : null;
$post['end_period'] = (!empty($post['end_period'])) ? date('Y-m-d', strtotime(str_replace('/', '-', $post['end_period']))) : null;
$model->fill($post);
$model->save();
return redirect()->route('acq.view.master.budget', ['id' => $model->budget_id, 'rf' => 'a']);
}
...
public function update($id, Request $request)
{
$validateData = $request->validate(AcqMBudgets::updateRules($request->input('budget_id')));
$model = AcqMBudgets::find($id);
$post = $request->only($model->getFillable());
$post['start_period'] = (!empty($post['start_period'])) ? date('Y-m-d', strtotime(str_replace('/', '-', $post['start_period']))) : null;
$post['end_period'] = (!empty($post['end_period'])) ? date('Y-m-d', strtotime(str_replace('/', '-', $post['end_period']))) : null;
$model->fill($post);
$model->save();
return redirect()->route('acq.view.master.budget', ['id' => $model->budget_id, 'rf' => 'e']);
}
...
On the model, I already separated the rules for create and update method. The difference is in the updateRules(), there is a primary key parameter which is needed in the array of rules.
On the controller, on update function, there is an error which stated: SQLSTATE[42703]: Undefined column: 7 ERROR: column "id" does not exist LINE 1: ...from "acq_m_budgets" where "budget_code" = $1 and "id" <> $2 ^ (SQL: select count(*) as aggregate from "acq_m_budgets" where "budget_code" = N01 and "id" <> ).
The primary key I used is integer and incremental, but due to some circumstances, the name of the primary key cannot be just id, so I changed it into budget_id and already declared it at the beginning of the model. Going by the error message, it seems Laravel keeps trying to compare with this id field instead the one I declared. What needs to be done to fix this?
UPDATE IN CODE:
I used Rule namespace on createRules and updateRules on model:
public static function createRules()
{
return [
'budget_code' => ['required', Rule::unique('acq_m_budgets', 'budget_code'), 'max:15'],
'budget_name' => ['required', 'max:100'],
'ma_code' => ['max:10'],
'start_period' => ['required'],
'end_period' => ['required'],
];
}
public static function updateRules($id)
{
return [
'budget_code' => ['required', Rule::unique('acq_m_budgets', 'budget_code')->ignore($id, 'budget_code'), 'max:15'],
'budget_name' => ['required', 'max:100'],
'ma_code' => ['max:10'],
'start_period' => ['required'],
'end_period' => ['required'],
];
}
When I tried to update the data, I made changes to some fields except the budget_code. The changes won't be saved if I didn't change the budget_code field as well, since it always give an error: "budget_code" has already been taken. I use dd($post), and the fields I changed is passed on perfectly.
I would use the Rule namespace, where you can call unique through that. For this to work you have to use arrays, for validation rules instead of strings, this is the better approach for readability anyways.
Rule::unique has the method ignore() where the second parameter is the id column, this can be seen here.
'budget_code' => [
'required',
Rule::unique('acq_m_budgets', 'budget_code')->ignore($id, 'budget_id'),
'max:15'
]

some data cannot be inserted into database

When new user fills out the registration form and hit submit, i can get all of the data that i need using dd($var). But, while inserting to database laravel says Cannot insert the value NULL into column 'password' . Why laravel didn't get my password while inserting to database ?
i have no idea what i did wrong here.
help me ..
this is my RegisterController.php
protected function create(array $data)
{
$pw_hash = Hash::make($data['Password']);
$uuid4 = Uuid::uuid4();
$a = DB::table('Person.Person')->insert(array(
'PersonId' => $uuid4->toString(),
'PersonName' => $data['PersonName'],
'Email' => $data['Email'],
'IsActive' => false,
'IsLoginActive' => false,
'PasswordSalt' => substr($pw_hash, 7, 22),
'PasswordHash' => sha1($pw_inpt.''.$pw_salt),
'IsMale' => $data['IsMale'],
'Email' => $data['Email'],
'Phone' => $data['Phone'],
'LoginName' => $data['Email'],
'PersonName' => $data["NamaDepan"]." ".$data['NamaBelakang'],
'EmailVerifiedAt' => date('Y-m-d'),
'EmailVerified' => false,
'EmailVerificationCode'=> Hash::make(rand(0,100)),
'password'=> 'aaaapass',
));
dd($a);
}
and this is my User.php Model
class User extends Authenticatable{
use Notifiable;
protected $table = 'Person.Person';
// protected $username = 'Email';
public $incrementing = false;
protected $primaryKey = 'PersonId';
const CREATED_AT = 'CreatedDate';
const UPDATED_AT = 'ModifiedDate';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'PersonId',
'Email',
'Phone',
'IsMale',
'password',
'IsActive',
'Position',
'LoginName',
'kencur',
'ClusterId',
'BirthDate',
'BirthPlace',
'PersonName',
'PersonImage',
'PasswordSalt',
'PasswordHash',
'ModifiedDate',
'IsLoginActive',
'EmailVerified',
'WhatsappNumber',
'EmailVerifiedAt',
'EmailVerificationCode',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'PasswordHash',
'PasswordSalt',
'remember_token',
];
public function getEmailForPasswordReset() {
return $this->Email;
}
}
and this is what laravel says:
Cannot insert the value NULL into column 'password', table 'Assess2.Person.Person'; column does not allow nulls. INSERT fails. (SQL: insert into [Person].[Person] ([PersonId], [PersonName], [Email], [IsActive], [IsLoginActive], [PasswordSalt], [PasswordHash], [IsMale], [Phone], [LoginName], [EmailVerifiedAt], [EmailVerified], [EmailVerificationCode], [password]) values (f6377aeb-df36-4f38-aef5-40c7a2240cc5, has sutenan, namadcvbepan#gmail.com, 0, 0, CTDdYYCXHULY4ad8jQJ9WO, $2y$10$CTDdYYCXHULY4ad8jQJ9WOmVqCILEuJPHSgffLlVW5SK7b7Q4qMpy, true, 55, namadcvbepan#gmail.com, 2019-03-04, 0, $2y$10$vcHlXQgukHomPI.FJZe2XOyl0lJd3Lo5rDqVN5SU8gY3UloPLsr.C, aaaapass))
im using laravel 5.7. thank you
PASSWORD is reserved keyword of database. Try to rename that column.

How to save images with Cakephp-File-Storage?

UPDATE
So I added some logs to the action upload in ProductsController and the method upload in MediasTable to find out what is happening. The entity from ProductsController this->Products->Medias->newEntity() was pass to MediasTable but it wasn't save.
It is necessary to upload the file to save the data in the db? Like if all the data is ok but the file is no present the event will be reject the data and do nothing in the db?
I'm using cakephp 3.1 with the file-storage plugin. I'm following the quickstart guide from the docs: Quick-Start but I don't understand some parts and doesn't upload, insert in database neither make thumbnails.
This is my database:
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
product_name VARCHAR(255) NOT NULL,
quantity INT NOT NULL,
sold INT NOT NULL,
description VARCHAR(1000),
price DECIMAL(7,2) NOT NULL,
old_price DECIMAL(7,2) NOT NULL,
visited INT NOT NULL,
status INT NOT NULL,
created DATETIME,
modified DATETIME
);
CREATE TABLE media_types (
id INT AUTO_INCREMENT PRIMARY KEY,
name_media_type VARCHAR(255) NOT NULL,
created DATETIME,
modified DATETIME
);
CREATE TABLE medias (
id INT AUTO_INCREMENT PRIMARY KEY,
media_type_id INT NOT NULL,
product_id INT NOT NULL,
path VARCHAR(255) NOT NULL,
created DATETIME,
modified DATETIME,
FOREIGN KEY media_type_key (media_type_id) REFERENCES media_types(id),
FOREIGN KEY product_key (product_id) REFERENCES products(id)
);
MediasTable:
...
use Burzum\FileStorage\Model\Table\ImageStorageTable;
class MediasTable extends ImageStorageTable {
public function initialize(array $config) {
parent::initialize($config);
$this->table('medias');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('MediaTypes', [
'foreignKey' => 'media_type_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Products', [
'foreignKey' => 'product_id',
'joinType' => 'INNER'
]);
}
...
public function upload($productId, $entity) {
$media = $this->patchEntity($entity, [
'adapter' => 'Local',
'model' => 'Media',
'foreign_key' => $productId
]);
Log::write('debug', $media);
return $this->save($media);
}
}
ProductsTable:
class ProductsTable extends Table {
public function initialize(array $config) {
parent::initialize($config);
$this->table('products');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('Medias', [
'className' => 'Medias',
'foreignKey' => 'foreign_key',
'conditions' => [
'Medias.model' => 'Media'
]
]);
}
...
}
ProductsController:
class ProductsController extends AppController {
public function upload($productId = null) {
$productId = 2;
$entity = $this->Products->Medias->newEntity();
if ($this->request->is(['post', 'put'])) {
$entity = $this->Products->Medias->patchEntity(
$entity,
$this->request->data
);
if ($this->Products->Medias->upload($productId, $entity)) {
$this->Flash->set(__('Upload successful!'));
}
}
$this->set('productImage', $entity);
}
...
}
In config/local_store.php is the same as the example (I include this file in boostrap.php)
...
$listener = new LocalFileStorageListener();
EventManager::instance()->on($listener);
$listener = new ImageProcessingListener();
EventManager::instance()->on($listener);
Configure::write('FileStorage', [
'imageSizes' => [
'Medias' => [
'large' => [
...
]);
FileStorageUtils::generateHashes();
StorageManager::config('Local', [
'adapterClass' => '\Gaufrette\Adapter\Local',
'adapterOptions' => [TMP, true],
'class' => '\Gaufrette\Filesystem'
]);
upload.ctp
echo $this->Form->create($productImage, array('type' => 'file'));
echo $this->Form->file('file');
echo $this->Form->error('file');
echo $this->Form->submit(__('Upload'));
echo $this->Form->end();
In the quick start there is two upload methods: uploadImage and uploadDocument
but in the controller they use "upload".
There is another association in Products in the example, I need this?:
$this->hasMany('Documents', [
'className' => 'FileStorage.FileStorage',
'foreignKey' => 'foreign_key',
'conditions' => [
'Documents.model' => 'ProductDocument'
]
]);
I found this question (from there is the db I'm using) Getting Started with cakephp-file-storage quickstart guide and upload and insert but doesn't make the thumbnails and if I change the table to ImageStoreTable shows an error "Class not found"
So if anybody can help me I will be very grateful!

How to add role to user?

We used Yii2 framework last alpha. Role for user already created but problem is how it assign to user. Documentation is absent.
For database version of RBAC use DbManager (quote frm: Alexufo):
use yii\rbac\DbManager;
$r=new DbManager;
$r->init();
$r->createRole("admin","Administrator");
$r->save();
$r->assign('1','admin'); //1 is user id
Example Access rules:
<?php
namespace backend\controllers;
use yii;
use yii\web\AccessControl;
use yii\web\Controller;
class SiteController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
//'actions' => ['login', 'error'], // Define specific actions
'allow' => true, // Has access
'roles' => ['#'], // '#' All logged in users / or your access role e.g. 'admin', 'user'
],
[
'allow' => false, // Do not have access
'roles'=>['?'], // Guests '?'
],
],
],
];
}
public function actionIndex()
{
return $this->render( 'index' );
}
}
?>
Don't forget to add this to your configuration file (config/main.php):
'components' => [
'authManager'=>array(
'class' => 'yii\rbac\DbManager',
'defaultRoles' => ['end-user'],
),
...
]
Tables:
drop table if exists `tbl_auth_assignment`;
drop table if exists `tbl_auth_item_child`;
drop table if exists `tbl_auth_item`;
create table `tbl_auth_item`
(
`name` varchar(64) not null,
`type` integer not null,
`description` text,
`biz_rule` text,
`data` text,
primary key (`name`),
key `type` (`type`)
) engine InnoDB;
create table `tbl_auth_item_child`
(
`parent` varchar(64) not null,
`child` varchar(64) not null,
primary key (`parent`,`child`),
foreign key (`parent`) references `tbl_auth_item` (`name`) on delete cascade on update cascade,
foreign key (`child`) references `tbl_auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;
create table `tbl_auth_assignment`
(
`item_name` varchar(64) not null,
`user_id` varchar(64) not null,
`biz_rule` text,
`data` text,
primary key (`item_name`,`user_id`),
foreign key (`item_name`) references `tbl_auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;
You can also find this information in the "yii/rbac" directory (including other SQL files).
For functionality and more details:
https://github.com/yiisoft/yii2/blob/master/docs/guide/security-authorization.md
$user_id = 1;
$auth = new DbManager;
$auth->init();
$role = $auth->createRole('editor');
$auth->add($role);
$auth->assign($role, $user_id);
=========================================================================
if you want to select role instead creating then
$auth = new DbManager;
$auth->init();
$role = $auth->getRole('admin');
$auth->assign($role, $user_id);
100% worked!
Solved!
================ create role ============
use yii\rbac\PhpManager;
$r=new PhpManager;
$r->init();
$r->createRole("admin","Администратор");
$r->save();
=============== assign ==================
$r->assign('1','admin'); //1 is user id
A really simple way to achieve an admin role is to add this to your controller:
use yii;
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'actions' => ['index'],
'roles' => ['#'],
],
[
'allow' => !Yii::$app->user->isGuest && Yii::$app->user->identity->isAdmin(),
'actions' => ['view', 'create', 'update', 'delete'],
],
],
],
];
}
Then add to your User model an isAdmin() which returns true for your admin user(s) and false for everyone else. Personally, I use:
public function isAdmin() {
return Self::ROLE_ADMIN === $this->role;
}
Admittedly, this is not "by the book". But it is simple, quick and effective.
$user_id = \Yii::$app->user->id;
$auth = new DbManager;
$auth->init();
$role = $auth->createRole('editor');
$auth->add($role);
$auth->assign($role, $user_id);

Categories