Double insert record in Yii2

Hey! do you need that double insert every time user create

public function actionCreate()
{
$model = new Records();

if($model->load(Yii::$app->request->post()))
{
$model->name = $model->name.’.trustpositifkominfo’;
$model->save();
// second insert here
$clone = new Records;
$clone->attributes = $model->attributes;
$clone->name = ‘*.’.$clone->name;
$clone->save();
return $this->redirect([‘view’, ‘id’ => $model->id]);
}
else {
return $this->render(‘create’, [
‘model’ => $model,
]);
}

}

Iklan

Create customized field value Yii2

hello! After a long hiatus. I got a project for my office. It is a dashboard application for powerdns. All the records  have only 1 master domain. So, I have to do a trick to put trustpositifkominfo as a domain for every record inserted. here is the magic:

public function beforeSave($insert) {

if ($insert) {
$this->domain_id = 1;
$this->name = $this->name.’.trustpositifkominfo’;
}
return parent::beforeSave($insert);

}

[yii1] Create Search for related model in GridView

Today I challenge myself to make a documentation of my code. And the topic of today’s post is how to create search (filter) for related model in your GridView (using yiiframework).

First, we’re working in model:

public $CourseIDFK; // put your target field’s name as a public variable

then, make a function, let’s name it search2().

public function search2() {

$criteria = new CDbCriteria;

$criteria->together = true;
$criteria->with[] = ‘courseIDFK’;

if ($this->CourseIDFK) {

$criteria->compare(‘courseIDFK.Name’, $this->CourseIDFK, true);

}

return new CActiveDataProvider($this, array(
‘criteria’ => $criteria,

));
}

then in controller put ‘search2’ as a parameter of the model’s object :
$model=new Classregistration(‘search2’);

in view admin, set dataprovider as below:
‘dataProvider’=>$model->search2(),

and don’t forget to put your target’s field value

‘value’ => ‘($data->courseIDFK->Name)’, // this is your target field’s value

voila! now you can search any value of your related model in your GridView 😉

Still can’t figure out? ask me in comment section. Sure I will help u ^^