yii2 user dektrium user_id - mysql

Hello guys i'm using yii2 user of dektrium . I would save user_id an account in my table. the User table has 1..N relationship with my table. I am a princiapiante and do not know how to save user id in my table. I tried so but the record in the database is blank.
My model
public static function tableName()
{
return 'viaggio';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['citta_part','citta_arrivo','user_id'], 'required'],
[['data_part','ora_part','data_arrivo','ora_arrivo'],'safe'],
[['posti_disponibili', 'conferma_utenze', 'user_id','posti_max'], 'integer'],
[['prezzo'], 'number'],
[['citta_part', 'via_part', 'citta_arrivo', 'via_arrivo', 'veicolo'], 'string', 'max' => 45],
[['note'], 'string', 'max' => 255],
[['wifi', 'bagno', 'ac_dc','condizioni'],'integer'],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id_viaggio' => Yii::t('app', 'Id Viaggio'),
'citta_part' => Yii::t('app', 'Citta Part'),
'via_part' => Yii::t('app', 'Via Part'),
'ora_part' => Yii::t('app', 'Ora Part'),
'data_part' => Yii::t('app', 'Data Part'),
'posti_disponibili' => Yii::t('app', 'Posti Disponibili'),
'conferma_utenze' => Yii::t('app', 'Conferma Utenze'),
'prezzo' => Yii::t('app', 'Prezzo'),
'note' => Yii::t('app', 'Note'),
'citta_arrivo' => Yii::t('app', 'Citta Arrivo'),
'data_arrivo' => Yii::t('app', 'Data Arrivo'),
'ora_arrivo' => Yii::t('app', 'Ora Arrivo'),
'via_arrivo' => Yii::t('app', 'Via Arrivo'),
'veicolo' => Yii::t('app', 'Veicolo'),
'posti_max' => Yii::t('app', 'Posti Max'),
'wifi' => Yii::t('app', 'Wifi'),
'bagno' => Yii::t('app', 'Bagno'),
'ac_dc' => Yii::t('app', 'Ac Dc'),
'user_id' => Yii::t('app', 'User ID'),
];
}
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id'])->inverseOf('offris');
}
My Controller
public function actionOffri() {
$model = new Offri;
if($model->load(Yii::$app->request->post()) && $model->validate() && $model->save()) {
$model->$user_id = Yii::$app->user->identity->id;
Yii::$app->session->setFlash('success', 'Hai inserito i dati correttamente');
return $this->render('offri', ['model' => $model]);
} else {
Yii::$app->getSession()->setFlash('error', 'Completa correttamente tutti i campi.');
return $this->render('offri', ['model' => $model]);
}
}
suggestions?

First try move the assignment for user_id before validation otherwise the validation surely fail and the model is not saved
public function actionOffri()
{
$model = new Offri;
$model->$user_id = Yii::$app->user->id;
if($model->load(Yii::$app->request->post())&& $model->validate() && $model->save()) {
Yii::$app->session->setFlash('success', 'Hai inserito i dati correttamente');
return $this->render('offri', ['model' => $model]);
} else {
Yii::$app->getSession()->setFlash('error', 'Completa correttamente tutti i campi.');
return $this->render('offri', ['model' => $model]);
}
}
or if yuo need the username you can use Yii::$app->user->identity->username

I think your code has error:
$model->$user_id = Yii::$app->user->identity->id;
Try replace it by:
$model->user_id = Yii::$app->user->identity->id;

Related

Yii2 Sorting and filtering from a linked table through a table

Good day everyone. I'm trying to add a filter for the associated phone_digital field but I get the following error
Structure -
1 table - ClientClient - first_name, patronymic, last_name, age.
2 table - ClientPhone - client_id, phone_digital.
ClientClient (model)
class ClientClient extends \yii\db\ActiveRecord
{
public static function tableName(){
return 'client_client';
}
public function rules(){
return [
[['age'], 'integer'],
[['first_name', 'patronymic', 'last_name'], 'string', 'max' => 255],
];
}
public function attributeLabels(){
return [
'id' => 'ID',
'first_name' => 'First Name',
'patronymic' => 'Patronymic',
'last_name' => 'Last Name',
'age' => 'Age',
'phone_digital' => 'Phone Digital',
];
}
public function getclientPhone(){
return $this->hasOne(clientPhone::class, ['client_id' => 'id']);
}
public function getPhone(){
return $this->hasOne(clientPhone::class, ['phone_digital' => 'id']);
}
public function getDigital(){
return $this->hasOne(ClientPhone::className(), ['id' => 'phone_digital']);
}
public function getPhoneDigital(){
return $this->phone->phone_digital;
}
}
ClientSearch (model)
class ClientSearch extends Clientclient
{
public $phonedigital;
public function rules(){
return [
[['id', 'age'], 'integer'],
[['first_name', 'phonedigital', 'patronymic', 'last_name'], 'safe'],
];
}
public function scenarios(){
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
public function search($params){
$query = Clientclient::find()->orderBy('phone_digital');
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->joinWith(['phonedigital' => function($query) { $query->from(['phonedigital' => 'ClientPhone']); }]);
$dataProvider->sort->attributes['phone'] = [
'asc' => ['phonedigital.phone_digital' => SORT_ASC],
'desc' => ['phonedigital.phone_digital' => SORT_DESC],
];
$query->andFilterWhere([
'id' => $this->id,
'age' => $this->age,
]);
$query->andFilterWhere(['like', 'first_name', $this->first_name])
->andFilterWhere(['like', 'patronymic', $this->patronymic])
->andFilterWhere(['like', 'last_name', $this->last_name])
->andFilterWhere(['like', 'phonedigital.phone_digital', $this->getAttribute('phonedigital')]);
return $dataProvider;
}
}
What do I need to do to make this work?
I guess you should put your orderBy after your join
check the commented lines:
public function search($params){
// do not put the join of a related table at the beginning because it's not related yet
$query = Clientclient::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->joinWith(['phonedigital' => function($query) { $query->from(['phonedigital' => 'ClientPhone']); }]);
// orderBy only after call the relacion
$query->orderBy('phonedigital.phone_digital');
$dataProvider->sort->attributes['phone'] = [
'asc' => ['phonedigital.phone_digital' => SORT_ASC],
'desc' => ['phonedigital.phone_digital' => SORT_DESC],
];
$query->andFilterWhere([
'id' => $this->id,
'age' => $this->age,
]);
$query->andFilterWhere(['like', 'first_name', $this->first_name])
->andFilterWhere(['like', 'patronymic', $this->patronymic])
->andFilterWhere(['like', 'last_name', $this->last_name])
->andFilterWhere(['like', 'phonedigital.phone_digital', $this->getAttribute('phonedigital')]);
return $dataProvider;
}
I hope it helps you, and sorry about my ingles

Yii2 - Update Complex Form

I created a Complex Form using two Model Classes:
Courses
CourseStructure
public function actionCreate()
{
$model = new Course();
$request = Yii::$app->request;
if ($model->load(Yii::$app->request->post()) && Yii::$app->request->isAjax) {
//The course was created successfully, so we can use its data to make course structure
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post())) {
$model->attributes = $_POST['Course'];
$model->course_start_date = date('Y-m-d', strtotime($_POST['Course']['course_start_date']));
$model->created_at = new \yii\db\Expression('NOW()');
}
$model->save(false);
if($model->save(false))
//The course was created successfully, so we can use its data to make course structure
{
// check if topic format
if($model->course_format == Course::TYPE_TOPIC)
{
for( $i = 1; $i <= $model->course_format_no; $i++ )
{
$structure = new CourseStructure();
$structure->course_id = $model->course_id;
$structure->structure_name = $model->course_format . $i;
$structure->structure_id = $i;
// fill in other course structure data here
$structure->save();
}
}
}
else
return $this->render('create', ['model' => $model,]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
From CourseControllers, if course_format = TYPE_TOPIC, then based on the course_format_no selected,
some rows are added in course_structure table (CourseStructure). For instance, if course_format_no = 3, it creates three additional rows in course_structure table.
if($model->course_format == Course::TYPE_TOPIC)
{
for( $i = 1; $i <= $model->course_format_no; $i++ )
{
$structure = new CourseStructure();
$structure->course_id = $model->course_id;
$structure->structure_name = $model->course_format . $i;
$structure->structure_id = $i;
// fill in other course structure data here
$structure->save();
}
}
It works fine in CourseCreate Action in CourseController.
Now how do I do it for the CourseUpdate Action, so that if that either reduce the number of rows or increase it in course_structure table based on the course_format_no added in the update.
course_structure
This is what I have:
public function actionUpdate($id)
{
$model = $this->findModel($id);
$old_model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && Yii::$app->request->isAjax) {
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post())) {
$model->attributes = $_POST['Course'];
$model->course_start_date = Yii::$app->dateformatter->getDateFormat($_POST['Course']['course_start_date']);
$model->updated_by = Yii::$app->getid->getId();
$model->updated_at = new \yii\db\Expression('NOW()');
if($model->save(false))
return $this->redirect(['view', 'id' => $model->course_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
CourseStructure model
class CourseStructure extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'course_structure';
}
public function rules()
{
return [
[['course_id', 'structure_id', 'summary_format', 'created_by', 'updated_by'], 'integer'],
[['structure_summary'], 'string'],
[['created_at', 'updated_at'], 'safe'],
[['structure_name'], 'string', 'max' => 200],
];
}
public function attributeLabels()
{
return [
'course_structure_id' => 'Course Structure ID',
'course_id' => 'Course ID',
'structure_id' => 'Structure ID',
'structure_name' => 'Structure Name',
'structure_summary' => 'Structure Summary',
'summary_format' => 'Summary Format',
'created_at' => 'Created At',
'created_by' => 'Created By',
'updated_at' => 'Updated At',
'updated_by' => 'Updated By',
];
}
public function getCourses()
{
return $this->hasOne(Course::className(), ['course_id' => 'course_id']);
}
public static function getAllCourseStructure()
{
$dataTmp = self::find()->orderBy('structure_name')->all();
$result = yii\helpers\ArrayHelper::map($dataTmp, 'course_structure_id', 'structure_name');
return $result;
}
}
Courses model
class Course extends \yii\db\ActiveRecord
{
const TYPE_WEEKLY= 'Weekly';
const TYPE_TOPIC='Topic';
public $coursefile;
public static function tableName()
{
return 'course';
}
public function rules()
{
return [
[['course_category_id', 'course_format_no', 'show_grade', 'created_by', 'updated_by'], 'integer'],
[['course_code', 'course_name', 'course_format', 'course_format_no'], 'required', 'message' => ''],
[['course_summary'], 'string'],
[['course_start_date', 'created_at', 'updated_at', 'course_file_path'], 'safe'],
[['course_code'], 'string', 'max' => 100],
[['course_name'], 'string', 'max' => 255],
[['course_num', 'course_format'], 'string', 'max' => 20],
[['course_code'], 'unique'],
[['coursefile'], 'safe'],
[['course_name', 'course_category_id'], 'unique', 'targetAttribute' => ['course_name', 'course_category_id'], 'message' => Yii::t('app', 'The combination of Course Name and Course Category has already been taken.')],
[['coursefile'], 'file', 'extensions' => 'jpg, jpeg, gif, png, pdf, txt, jpeg, xls, xlsx, doc, docx', 'maxFiles' => 4],
[['coursefile'], 'file', 'maxSize'=>'10000000'],
[['course_file_path', 'course_file_name'], 'string', 'max' => 255],
];
}
public function attributeLabels()
{
return [
'course_id' => 'Course ID',
'course_category_id' => 'Course Category',
'course_code' => 'Course Short Name',
'course_name' => 'Course Full Name',
'course_num' => 'Course ID Number',
'course_summary' => 'Course Summary',
'course_start_date' => 'Course Start Date',
'course_format' => 'Course Format',
'course_format_no' => 'No.of Sections',
'course_file_path' => Yii::t('app', 'Pathname'), //'Course File',
'course_file_name' => Yii::t('app', 'Filename'),
'show_grade' => 'Show Grade',
'created_at' => 'Created At',
'created_by' => 'Created By',
'updated_at' => 'Updated At',
'updated_by' => 'Updated By',
];
}
public function getCourseCategory()
{
return $this->hasOne(CourseCategories::className(), ['course_category_id' => 'course_category_id']);
}
public static function getAllCourse()
{
$dataTmp = self::find()->orderBy('course_name')->all();
$result = yii\helpers\ArrayHelper::map($dataTmp, 'course_id', 'course_name');
return $result;
}
public static function getCourseFormat()
{
return[
Yii::t('app', self::TYPE_TOPIC) => Yii::t('app', 'Topic'),
Yii::t('app', self::TYPE_WEEKLY) => Yii::t('app', 'Weekly'),
];
}
}
How do I write the code to update CourseStructure in the ActionUpdate.

cakephp 3 using for login another model than users auth

I'm trying to make a login from another model and I have an error.
This is my code for Student Model
var $name= 'Student';
public $components = array(
'Session',
'Auth' => array(
'loginAction' => array(
'controller' => 'students',
'action' => 'login',
'plugin' => 'students'
),
'authError' => 'Did you really think you are allowed to see that?',
'authenticate' => array(
'Form' => array(
'fields' => array(
'username' => 'username', //Default is 'username' in the userModel
'password' => 'password' //Default is 'password' in the userModel
)
)
)
)
);
StudentsController looks like
public function beforeFilter(Event $event) {
parent::beforeFilter($event);
$this->Auth->allow('login');
}
public function login() {
if($this->Session->check('Auth.Student')){
$this->redirect(array('action' => 'login'));
}
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->Session->setFlash(__('Welcome, '. $this->Auth->student('username')));
$this->redirect($this->Auth->redirectUrl());
} else {
$this->Session->setFlash(__('Invalid username or password'));
}
}
}
And the AppController is
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
}
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'students', 'action' => 'login'),
'loginAction' => array('controller' => 'students', 'action' => 'login'),
));
public function beforeFilter(Event $event) {
$this->Auth->authenticate=array (
'loginAction' => [
'controller' => 'Students',
'action' => 'login',
'plugin' => false,
],
'Basic' => ['userModel' => 'Students'],
'Form' => ['userModel' => 'Students']
);
}
And I have the following error
Component class SessionComponent could not be found.
How can I fix it?
Session was deprecated in cakePHP 3, How you are doing is for cake2. In cake 3 you can use RequestHandeler like,
$this->loadComponent('RequestHandler');
OR
public $components = array(
'RequestHandler'
);
then use,
$this->request->Session()->read/write/delete/destroy();
Hope this will work for you :).

yii2 data to the db saves them all null

hello guys I have a problem when I send the form data in the database , all NULL fields are saved . Any suggestions?
my Controller
public function actionOffri()
{
$model = new Offri;
if($model->load(Yii::$app->request->post())&& $model->validate() && $model->save())
{
Yii::$app->session->setFlash('success', 'Hai inserito i dati correttamente');
return $this->render('offri', ['model' => $model]);
}
}
my Model I just added the rules and variables of the fields feature
ex.
public $name;
public function rules()
{
return [['name'],'string'.....
....
];
}
My Full Model
class Offri extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'viaggio';
}
public $data_par;
public $ora_part;
public $data_arrivo;
public $ora_arrivo;
public $citta_part;
public $citta_arrivo;
public $wifi;
public $bagno;
public $ac_dc;
public $condizioni;
/**
* #inheritdoc
*/
public function rules()
{
return [
[['citta_part','citta_arrivo'], 'required'],
[['citta_part','citta_arrivo'], 'string', 'max' => 255],
[['posti_disponibili', 'conferma_utenze', 'accounts_id_account', 'posti_max', 'wifi', 'bagno', 'ac_dc'], 'integer'],
[['prezzo'], 'number'],
[['accounts_id_account'], 'required'],
[['citta_part', 'via_part', 'citta_arrivo', 'via_arrivo', 'veicolo'], 'string', 'max' => 45],
[['note'], 'string', 'max' => 255],
[['accounts_id_account'], 'exist', 'skipOnError' => true, 'targetClass' => Accounts::className(), 'targetAttribute' => ['accounts_id_account' => 'id_account']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id_viaggio' => Yii::t('app', 'Id Viaggio'),
'citta_part' => Yii::t('app', 'Citta Part'),
'via_part' => Yii::t('app', 'Via Part'),
'ora_part' => Yii::t('app', 'Ora Part'),
'data_part' => Yii::t('app', 'Data Part'),
'posti_disponibili' => Yii::t('app', 'Posti Disponibili'),
'conferma_utenze' => Yii::t('app', 'Conferma Utenze'),
'prezzo' => Yii::t('app', 'Prezzo'),
'note' => Yii::t('app', 'Note'),
'accounts_id_account' => Yii::t('app', 'Accounts Id Account'),
'citta_arrivo' => Yii::t('app', 'Citta Arrivo'),
'data_arrivo' => Yii::t('app', 'Data Arrivo'),
'ora_arrivo' => Yii::t('app', 'Ora Arrivo'),
'via_arrivo' => Yii::t('app', 'Via Arrivo'),
'veicolo' => Yii::t('app', 'Veicolo'),
'posti_max' => Yii::t('app', 'Posti Max'),
'wifi' => Yii::t('app', 'Wifi'),
'bagno' => Yii::t('app', 'Bagno'),
'ac_dc' => Yii::t('app', 'Ac Dc'),
];
}
From what I can see from your rules, labels and members, it is probably because you're using virtual members where you shouldn't. Note that using virtual members will overwrite any value from user's input. Since you're not assigning any manual value, Yii just clears all and leaves them empty. You also most likely have set null as default value in your columns (if data is empty), that's why you're seeing null in every row.
To solve this issue, remove these lines from your Model:
public $data_par;
public $ora_part;
public $data_arrivo;
public $ora_arrivo;
public $citta_part;
public $citta_arrivo;
public $wifi;
public $bagno;
public $ac_dc;
public $condizioni;
These virtual attributes are being used differently from DB attributes and I think in your case you don't need them here.

Updating Image in Yii2

While updating image using Yii2 I'm facing a problem with the validation.Its always asking me to upload an image. But I don't want this. Always updating an image is not necessary.
I tried skipOnEmpty but its not working properly it cause effect while uploading a photo, which is also incorrect.
Please help!!
Model
public function rules()
{
return [
[['carid', 'name'], 'required'],
[['carid', 'coverphoto', 'status'], 'integer'],
[['name'], 'string', 'max' => 200],
[['imageFiles'], 'image','extensions' => 'png, jpg, jpeg, gif', 'maxFiles' => 4, 'minWidth' => 100, 'maxWidth' => 800, 'minHeight' => 100, 'maxHeight'=>600,'skipOnEmpty' => true],
];
}
Controller
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->photoid]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
You should to use scenario for update.
Like as,
Add on condition in model's rule for applying scenario .
[['imageFiles'], 'image','extensions' => 'png, jpg, jpeg, gif', 'maxFiles' => 4, 'minWidth' => 100, 'maxWidth' => 800, 'minHeight' => 100, 'maxHeight'=>600,'skipOnEmpty' => true, 'on' => 'update-photo-upload'],
And use that scenario in controller's action.
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->scenario = 'update-photo-upload';
........
.....
}
try rule as
[
['imageFiles'], 'file',
'extensions' => 'png, jpg, jpeg, gif',
'mimeTypes' => 'image/jpeg, image/png',
'maxFiles' => 4,
'minWidth' => 100,
'maxWidth' => 800,
'minHeight' => 100,
'maxHeight'=>600,
'skipOnEmpty' => true
],
This is working in my case, hope it works for you too.
**Your View Like This**
<?php use yii\widgets\ActiveForm;?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'imageFiles')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end() ?>
*** Your Controller Like This******
use Yii;
use yii\web\Controller;
use app\models\UploadForm;
use yii\web\UploadedFile;
class SiteController extends Controller
{
public function actionUpdate()
{
$model = new UploadForm ();
$model->scenario = 'update';
if (Yii::$app->request->isPost) {
$model->imageFiles= UploadedFile::getInstance($model, 'imageFiles');
if ($model->upload()) {
// file is uploaded successfully
return;
}
}
return $this->render('update', ['model' => $model]);
}
}
***** Your ModelLike This ******
use yii\base\Model;
use yii\web\UploadedFile;
class UploadForm extends Model
{
/**
* #var UploadedFile[]
*/
public $imageFiles;
public function rules()
{
return [
[['carid', 'name'], 'required'],
[['carid', 'coverphoto', 'status'], 'integer'],
[['name'], 'string', 'max' => 200],
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg', 'maxFiles' => 4,'on'=>'update'],
];
}
public function upload()
{
if ($this->validate()) {
foreach ($this->imageFiles as $file) {
$file->saveAs('uploads/' . $file->baseName . '.' . $file->extension);
}
return true;
} else {
return false;
}
}
function scenario()
{
return [
'create' => ['imageFiles ', 'carid','name','coverphoto','status'],
'update' => ['imageFiles ', 'carid','name','coverphoto','status'],
];
}
}