Load data to a form from a different model in yii2 - yii2

I am creating a form to insert data into table salary. The associated Model is Salary. in the form I have fields s_wageperday,s_conveyanceperday. I have a separate table ratechart where these values are already stored. There's only one row in the table ratechart and it should be.the columns are - wage_per_day, conveyance_per_day. What I want is - when I load the Create form for salary - It should load the data from ratechart table in the respective textfield.
What I've done -
In RatechartController I've added the following code
public function actionGetForRatechart()
{
$rates = Employee::findOne(1)->asArray();
//$bottle -> select(['productnames.productnames_productname','productnames.bottletype','bottlename.unitprice'])->from('Productnames')->leftJoin('bottlename','productnames.bottletype = bottlename.bottlename')->where(['productnames_productname'=>$catid])->limit(1);
echo Json::encode($rates);
}
As far I know this data can be pulled to the form using Javascript in salary _form
Javascriptcode I've written so far (which is probably wrong) -
<?php
$script = <<< JS
$('#rateid').change(function(){
var = $(this).val();
$.get('index.php?r=salary/ratechart/get-for-ratechart',{ 1 : 1 }, function(data){
alert(data);
var data = $.parseJSON(data);
$('#salary-s_wageperday').attr('value',data.wage_per_day);
});
});
JS;
$this->registerJs($script);
?>
Please help.
Model Salary
<?php
namespace frontend\modules\salary\models;
use Yii;
/**
* This is the model class for table "salary".
*
* #property string $s_id
* #property string $s_date
* #property string $s_period
* #property string $s_empid
* #property string $s_empname
* #property integer $s_workingdays
* #property integer $s_leave
* #property integer $s_holiday
* #property integer $s_wageperday
* #property integer $s_totalwage
* #property integer $s_ovthour
* #property integer $s_ovtrateperhour
* #property integer $s_ovtamount
* #property integer $s_tiffinworkingday
* #property integer $s_tiffinrateperday
* #property integer $s_wdtiffinamount
* #property integer $s_sundayworked
* #property integer $s_sundayrate
* #property integer $s_sundaytiffinamount
* #property integer $s_nightcount
* #property integer $s_nightallrate
* #property integer $s_nightallowance
* #property integer $s_convday
* #property integer $s_convrate
* #property integer $s_conveyanceamount
* #property integer $s_tiffinovtcount
* #property integer $s_tiffinovtrate
* #property integer $s_tiffinovtamount
* #property integer $s_incentivecount
* #property integer $s_incentiverate
* #property integer $s_incentive
* #property integer $s_totalearning
* #property integer $s_epf
* #property integer $s_esi
* #property integer $s_ptax
* #property integer $s_takehome
*/
class Salary extends \yii\db\ActiveRecord
{
public $value;
public $totaldays;
public $ratechart;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'salary';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['s_date', 's_period', 's_empid', 's_empname','s_workingdays', 's_leave', 's_holiday','s_wageperday', 's_totalwage', 's_ovthour', 's_ovtrateperhour', 's_ovtamount', 's_tiffinworkingday', 's_tiffinrateperday', 's_wdtiffinamount', 's_sundayworked', 's_sundayrate', 's_sundaytiffinamount', 's_nightcount', 's_nightallrate', 's_nightallowance', 's_convday', 's_convrate', 's_conveyanceamount', 's_tiffinovtcount', 's_tiffinovtrate', 's_tiffinovtamount', 's_incentivecount', 's_incentiverate', 's_incentive', 's_totalearning', 's_epf', 's_esi', 's_ptax', 's_takehome'], 'required'],
[['s_date','value','totaldays'], 'safe'],
[['s_workingdays', 's_leave', 's_holiday', 's_wageperday', 's_totalwage', 's_ovthour', 's_ovtrateperhour', 's_ovtamount', 's_tiffinworkingday', 's_tiffinrateperday', 's_wdtiffinamount', 's_sundayworked', 's_sundayrate', 's_sundaytiffinamount', 's_nightcount', 's_nightallrate', 's_nightallowance', 's_convday', 's_convrate', 's_conveyanceamount', 's_tiffinovtcount', 's_tiffinovtrate', 's_tiffinovtamount', 's_incentivecount', 's_incentiverate', 's_incentive', 's_totalearning', 's_epf', 's_esi', 's_ptax', 's_takehome'], 'integer'],
[['s_period'], 'string', 'max' => 15],
[['s_empid'], 'string', 'max' => 20],
[['s_empname'], 'string', 'max' => 70],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
's_id' => 'ID',
's_date' => 'Date',
's_period' => 'Period',
's_empid' => 'Empid',
's_empname' => 'Empname',
's_workingdays' => 'Workingdays',
's_leave' => 'Leave',
's_holiday' => 'Holiday',
's_wageperday' => 'Wageperday',
's_totalwage' => 'Totalwage',
's_ovthour' => 'Ovthour',
's_ovtrateperhour' => 'Ovtrateperhour',
's_ovtamount' => 'Ovtamount',
's_tiffinworkingday' => 'Tiffinworkingday',
's_tiffinrateperday' => 'Tiffinrateperday',
's_wdtiffinamount' => 'Wdtiffinamount',
's_sundayworked' => 'Sundayworked',
's_sundayrate' => 'Sundayrate',
's_sundaytiffinamount' => 'Sundaytiffinamount',
's_nightcount' => 'Nightcount',
's_nightallrate' => 'Nightallrate',
's_nightallowance' => 'Nightallowance',
's_convday' => 'Convday',
's_convrate' => 'Convrate',
's_conveyanceamount' => 'Conveyanceamount',
's_tiffinovtcount' => 'Tiffinovtcount',
's_tiffinovtrate' => 'Tiffinovtrate',
's_tiffinovtamount' => 'Tiffinovtamount',
's_incentivecount' => 'Incentivecount',
's_incentiverate' => 'Incentiverate',
's_incentive' => 'Incentive',
's_totalearning' => 'Totalearning',
's_epf' => 'EPF',
's_esi' => 'ESI',
's_ptax' => 'PTax',
's_takehome' => 'Takehome',
];
}
}
Model Ratechart
<?php
namespace frontend\modules\salary\models;
use Yii;
/**
* This is the model class for table "ratechart".
*
* #property integer $rc_id
* #property integer $ovt_per_hour
* #property integer $tiffin_per_working_day
* #property integer $conveyance_per_working_day
* #property integer $tiffin_per_ovt_day
* #property integer $tiffin_per_sunday
* #property integer $night_allowance_per_night
* #property integer $incentive_per_count
*/
class Ratechart extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'ratechart';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['rc_id'], 'required'],
[['rc_id', 'ovt_per_hour', 'tiffin_per_working_day', 'conveyance_per_working_day', 'tiffin_per_ovt_day', 'tiffin_per_sunday', 'night_allowance_per_night', 'incentive_per_count'], 'integer'],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'rc_id' => 'Rc ID',
'ovt_per_hour' => 'Ovt Per Hour',
'tiffin_per_working_day' => 'Tiffin Per Working Day',
'conveyance_per_working_day' => 'Conveyance Per Working Day',
'tiffin_per_ovt_day' => 'Tiffin Per Ovt Day',
'tiffin_per_sunday' => 'Tiffin Per Sunday',
'night_allowance_per_night' => 'Night Allowance Per Night',
'incentive_per_count' => 'Incentive Per Count',
];
}
}
I've tried the following code in my _form
<?= $form->field('s_ovtrateperhour', Ratechart::findOne(1)->ovt_per_hour,['showLabels'=>false])->textInput(['placeholder'=>'Overtime rate per hour']) ?>
But getting error - Call to a member function formName() on string

Related

Yii2 Trying to get property 'chnmem_stid' of non-object

I'm using Yii2 Advanced and I'm getting this error
Trying to get property 'chnmem_stid' of non-object
The error is in this function in $isMember->chnmem_stid;
public function actionChannel($id)
{
$model = $this->findModelUID($id);
$isMember = AxChnPermission::ChnMember($model->channel_id);
$memberStt = array(1,2,3);
if (in_array($isMember->chnmem_stid, $memberStt))
{
$dataProviderPost = AxChannelProvider::ContentProviderMember ($model->channel_id);
}
else
{
$dataProviderPost = AxChannelProvider::ContentProviderGuest ($model->channel_id);
}
return $this->render('/channel/_viewPost', [
'model' => $this->findModelUID($id),
'isMember' => $isMember,
'dataProviderPost' => $dataProviderPost,
]);
}
the function AxChnPermission::ChnMember($model->channel_id); is
public static function ChnMember($chn_id)
{
$member = ChnMember::findOne(['user_id' => Yii::$app->user->id, 'channel_id' => $chn_id]);
return $member;
}
so the function I want to return only one result, The "chnmem_stid" is set to hasOne in model
/**
* This is the model class for table "chnmember".
*
* #property string $member_note
* #property int $user_id
* #property int $channel_id
* #property int $channel_admin
* #property int $chnmem_stid
* #property string $chnmem_date
* #property int $dsh_statut
*
* #property Channel $channel
* #property User $user
* #property ChnmemberStatut $chnmemSt
* #property Channel $channelAdmin
*/
/**
* #return \yii\db\ActiveQuery
*/
public function getChnmemSt()
{
return $this->hasOne(ChnmemberStatut::className(), ['chnmem_stid' => 'chnmem_stid']);
}
The error appears if return of this function is NULL
public static function ChnMember($chn_id)
{
$member = ChnMember::findOne(['user_id' => Yii::$app->user->id, 'channel_id' => $chn_id]);
return $member;
}
Your function AxChnPermission::ChnMember() may return null (if requested record does not exist). And this is probably the case, since error message says that $isMember is not object. You need to make additional check for this case:
$isMember = AxChnPermission::ChnMember($model->channel_id);
if ($isMember === null) {
// throw exception?
}

Subquery in SELECT using Yii2 ActiveRecord

Is it possible to convert this kind of SQL into ActiveRecord query in Yii2:
SELECT
*,
(select count(*) from pendaftar where pendaftar.prodi_pilihan_1 = a.id_prodi_penerima)as jum1,
(select count(*) from pendaftar where pendaftar.prodi_pilihan_2 = a.id_prodi_penerima)as jum2
FROM prodi_penerima as a
I have two relational models that are Pendaftar and ProdiPenerima.
This is Pendaftar model:
...
* #property ProdiPenerima $prodiPilihan1
* #property ProdiPenerima $prodiPilihan2
...
/**
* #return \yii\db\ActiveQuery
*/
public function getPekerjaanIdPekerjaan()
{
return $this->hasOne(Pekerjaan::className(), ['id_pekerjaan' => 'pekerjaan_id_pekerjaan']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getUserPendaftar()
{
return $this->hasOne(User::className(), ['id' => 'id_user_pendaftar']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProdiPilihan1()
{
return $this->hasOne(ProdiPenerima::className(), ['id_prodi_penerima' => 'prodi_pilihan_1']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProdiPilihan2()
{
return $this->hasOne(ProdiPenerima::className(), ['id_prodi_penerima' => 'prodi_pilihan_2']);
}
And this is ProdiPenerima model:
...
* #property Pendaftar[] $pendaftars
* #property Pendaftar[] $pendaftars0
...
/**
* #return \yii\db\ActiveQuery
*/
public function getPendaftars()
{
return $this->hasMany(Pendaftar::className(), ['prodi_pilihan_1' => 'id_prodi_penerima']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPendaftars0()
{
return $this->hasMany(Pendaftar::className(), ['prodi_pilihan_2' => 'id_prodi_penerima']);
}
prodi_pilihan_1 and prody_pilihan_2 are foreign keys in pendaftar table, that key was referenced from ProdiPenerima table.
$result = ProdiPenerima::find()
->select([
'*',
'jum1' => Pendaftar::find()
->select(['COUNT(*)'])
->where('pendaftar.prodi_pilihan_1 = a.id_prodi_penerima'),
'jum2' => Pendaftar::find()
->select(['COUNT(*)'])
->where('pendaftar.prodi_pilihan_2 = a.id_prodi_penerima')
])
->alias('a')
->asArray()
->all();
Results can be accessed by:
foreach ($result as $row) {
echo $row['jum1'];
}
That because asArray() was used, so query return array of arrays instead of array of models.
If you need models, you should add properties into your models to store result of subqueries:
class ProdiPenerima extends ActiveRecord {
public $jum1;
public $jum2;
// ...
}
Then remove isArray() from query:
$result = ProdiPenerima::find()
->select([
'*',
'jum1' => Pendaftar::find()
->select(['COUNT(*)'])
->where('pendaftar.prodi_pilihan_1 = a.id_prodi_penerima'),
'jum2' => Pendaftar::find()
->select(['COUNT(*)'])
->where('pendaftar.prodi_pilihan_2 = a.id_prodi_penerima')
])
->alias('a')
// ->asArray()
->all();
Results can be accessed by:
foreach ($result as $model) {
echo $model->jum1;
}
But note that using asArray() will be faster, so unless you need access some model methods (or rely on typecasting of values from DB) I would prefer arrays.

yii2- saving datas to multiple rows from one form

I am so new to the yii2 framework, I have a form that I want to save each party score to correspond to each party abbreviation. I don't know how to go about it. here is my code.
the model -
namespace app\models;
use Yii;
/**
* This is the model class for table "announced_pu_results".
*
* #property int $result_id
* #property string $polling_unit_uniqueid
* #property string $party_abbreviation
* #property int $party_score
* #property string $entered_by_user
* #property string $date_entered
* #property string $user_ip_address
*/
class AnnouncedPuResults extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'announced_pu_results';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['polling_unit_uniqueid', 'party_abbreviation', 'party_score', 'entered_by_user', 'date_entered', 'user_ip_address'], 'required'],
[['party_score'], 'integer'],
[['date_entered'], 'safe'],
[['polling_unit_uniqueid', 'entered_by_user', 'user_ip_address'], 'string', 'max' => 50],
// [['party_abbreviation'], 'string', 'max' => 4],
];
}
public function getPollingUnit()
{
return $this->hasOne(PollingUnit::className(), ['id' => 'polling_unit_uniqueid']);
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'result_id' => 'Result ID',
'polling_unit_uniqueid' => 'Polling Unit Uniqueid',
'party_abbreviation' => 'Party Abbreviation',
'party_score' => 'Party Score',
'entered_by_user' => 'Entered By User',
'date_entered' => 'Date Entered',
'user_ip_address' => 'User Ip Address',
];
}
}
the controller action is create ---
public function actionCreate()
{
$model = new AnnouncedPuResults();
if ($model->load(Yii::$app->request->post()) ){
//&& $model->save()) {
$post = yii::$app->request->post('AnnouncedPuResults');
$party_score = $post['party_score'];
$count = count($party_score);
for($i =0 ; $i < $count; $i++) {
$model->party_abbreviation = $post['party_abbreviation'];
$model->polling_unit_uniqueid = $post['polling_unit_uniqueid'];
$model->entered_by_user = $post['entered_by_user'];
$model->date_entered = $post['date_entered'];
$model->party_score = $post['party_score'];
$model->save();
}
return $this->redirect(['view', 'id' => $model->result_id]);
}else{
return $this->render('create', [
'model' => $model,
]);
}
}
this is the partial view form for the action create----
the screenshot of my form is attached
I want to save the results from my select boxes and the inputs the number of times they are selected to multiple rows in the database at a time
this is how the database looks like
please help me out, I hope my question is understandable.

Why can't I create CRUD with GII in Yii2

I have made the view table with function "join" in sql. but when I try to generate the view table with gii, it was said that "Table associated with Rangkuman must have primary key", and I have made primary key with table that associated with Rangkuman. But still be like this picture
Here is Rangkuman model
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "rangkuman".
*
* #property string $Fakultas
* #property string $Departemen
* #property string $KodeMayor
* #property string $NIM
* #property integer $TahunMasuk
* #property integer $JenisKelamin
* #property integer $StatusAkademik
* #property string $Usia
*/
class Rangkuman extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'rangkuman';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['Fakultas', 'Departemen', 'NIM', 'JenisKelamin'], 'required'],
[['TahunMasuk', 'JenisKelamin', 'StatusAkademik', 'Usia'], 'integer'],
[['Fakultas', 'Departemen'], 'string', 'max' => 5],
[['KodeMayor'], 'string', 'max' => 10],
[['NIM'], 'string', 'max' => 11],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'Fakultas' => Yii::t('app', 'Fakultas'),
'Departemen' => Yii::t('app', 'Departemen'),
'KodeMayor' => Yii::t('app', 'Kode Mayor'),
'NIM' => Yii::t('app', 'Nim'),
'TahunMasuk' => Yii::t('app', 'Tahun Masuk'),
'JenisKelamin' => Yii::t('app', 'Jenis Kelamin'),
'StatusAkademik' => Yii::t('app', 'Status Akademik'),
'Usia' => Yii::t('app', 'Usia'),
];
}
}
and here is the sql code
CREATE ALGORITHM=UNDEFINED DEFINER=`root`#`localhost` SQL SECURITY DEFINER VIEW `rangkuman` AS select `dbintegrasi`.`ipbmst_fakultas`.`Kode` AS `Fakultas`,
`dbintegrasi`.`ipbmst_departemen`.`Kode` AS `Departemen`,
`dbintegrasi`.`akdmst_mayor`.`Kode` AS `KodeMayor`,
`dbintegrasi`.`akdmst_mahasiswadoktor`.`NIM` AS `NIM`,
`dbintegrasi`.`akdmst_mahasiswadoktor`.`TahunMasuk` AS `TahunMasuk`,
`dbintegrasi`.`ipbmst_orang`.`JenisKelaminID` AS `JenisKelamin`,
`dbintegrasi`.`akdmst_mahasiswadoktor`.`StatusAkademikID` AS `StatusAkademik`,
timestampdiff(YEAR,`dbintegrasi`.`ipbmst_orang`.`TanggalLahir`,now()) AS `Usia`
from (((((`dbintegrasi`.`akdmst_mahasiswadoktor` join `dbintegrasi`.`akdmst_mayor`
on((`dbintegrasi`.`akdmst_mahasiswadoktor`.`MayorID` = `dbintegrasi`.`akdmst_mayor`.`ID`)))
join `dbintegrasi`.`ipbmst_departemen` on((`dbintegrasi`.`akdmst_mayor`.`DepartemenID` = `dbintegrasi`.`ipbmst_departemen`.`ID`)))
join `dbintegrasi`.`ipbmst_fakultas` on((`dbintegrasi`.`ipbmst_departemen`.`FakultasID` = `dbintegrasi`.`ipbmst_fakultas`.`ID`)))
join `dbintegrasi`.`ipbmst_orang` on((`dbintegrasi`.`akdmst_mahasiswadoktor`.`NIM` = `dbintegrasi`.`ipbmst_orang`.`NIMS3Key`)))
join `dbintegrasi`.`akdref_statusakademik` on((`dbintegrasi`.`akdmst_mahasiswadoktor`.`StatusAkademikID` = `dbintegrasi`.`akdref_statusakademik`.`ID`)))
join `dbintegrasi`.`ipbref_jeniskelamin` on((`dbintegrasi`.`ipbmst_orang`.`JenisKelaminID` = `dbintegrasi`.`ipbref_jeniskelamin`.`ID`));
What should I do? Thank you

Yii mysql datetime empty

I have a problem with a Yii model, I create a MySQL table with two datetime column.
And create the model with gii. The problem is that when I get the data from the model I get the datetime fields empty.
<?php
/**
* This is the model class for table "Template".
*
* The followings are the available columns in table 'Template':
* #property string $tmpId
* #property integer $fanPageId
* #property string $name
* #property string $title
* #property string $description
* #property string $headerFile
* #property string $msgNotTlt
* #property string $msgNotMsg
* #property string $msgNotImg
* #property string $msgNotLnk
* #property string $terms
* #property string $strProm
* #property string $endProm
*/
class Template extends CActiveRecord
{
/**
* Returns the static model of the specified AR class.
* #param string $className active record class name.
* #return Template the static model class
*/
public static function model($className=__CLASS__)
{
return parent::model($className);
}
/**
* #return string the associated database table name
*/
public function tableName()
{
return 'Template';
}
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('fanPageId', 'numerical', 'integerOnly'=>true),
array('name, title, description, headerFile, msgNotTlt, msgNotMsg, msgNotImg, msgNotLnk, terms', 'length', 'max'=>11),
array('strProm, endProm', 'safe'),
//array('endProm, strProm', 'type', 'type'=>'datetime', 'datetimeFormat'=>'yyyy/M/d H:m:s'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('tmpId, fanPageId, name, title, description, headerFile, msgNotTlt, msgNotMsg, msgNotImg, msgNotLnk, terms, strProm, endProm', 'safe', 'on'=>'search'),
);
}
/**
* #return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
);
}
/**
* #return array customized attribute labels (name=>label)
*/
public function attributeLabels()
{
return array(
'tmpId' => 'Tmp',
'fanPageId' => 'Fan Page',
'name' => 'Name',
'title' => 'Title',
'description' => 'Description',
'headerFile' => 'Header File',
'msgNotTlt' => 'Msg Not Tlt',
'msgNotMsg' => 'Msg Not Msg',
'msgNotImg' => 'Msg Not Img',
'msgNotLnk' => 'Msg Not Lnk',
'terms' => 'Terms',
'strProm' => 'Str Prom',
'endProm' => 'End Prom',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
* #return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('tmpId',$this->tmpId,true);
$criteria->compare('fanPageId',$this->fanPageId);
$criteria->compare('name',$this->name,true);
$criteria->compare('title',$this->title,true);
$criteria->compare('description',$this->description,true);
$criteria->compare('headerFile',$this->headerFile,true);
$criteria->compare('msgNotTlt',$this->msgNotTlt,true);
$criteria->compare('msgNotMsg',$this->msgNotMsg,true);
$criteria->compare('msgNotImg',$this->msgNotImg,true);
$criteria->compare('msgNotLnk',$this->msgNotLnk,true);
$criteria->compare('terms',$this->terms,true);
$criteria->compare('strProm',$this->strProm,true);
$criteria->compare('endProm',$this->endProm,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
}
In rules of you model add the two columns:
array('datetime_1, datetime_2', 'safe'),
array('id, <attributes>, datetime_1, datetime_2', 'safe', 'on'=>'search'),
If possible, post you code/model...