Yii2 - using 2 models in 1 view - php

I tried using 2 models in 1 view, but the fields I added are "(not set)" but they're deffinetly set in the database so what did i do wrong
Here you see the result of the added fields
here is the view code:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use app\models\Facturen;
/* #var $this yii\web\View */
/* #var $model app\models\Facturen */
/* #var $modelProducten app\models\Producten */
$this->title = $model->factuur_id;
$this->params['breadcrumbs'][] = ['label' => 'Factures', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="facturen-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->factuur_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->factuur_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'modelProducten' => $modelProducten,
'attributes' => [
'factuur_id',
'company.company_name',
'person.first_name',
'product.product_id',
'product.product_name',
'product.amount',
'product.price',
'date',
],
]) ?>
</div>
also the create code might be usefull
public function actionCreate()
{
$model = new Facturen();
$modelProducten = [new Producten];
if ($model->load(Yii::$app->request->post())) {
$transaction = Yii::$app->db->beginTransaction();
$success = true;
$modelProducten = Model::createMultiple(Producten::classname());
Model::loadMultiple($modelProducten, Yii::$app->request->post());
if ($model->save()) {
foreach($modelProducten as $modelProduct) {
$modelProduct->factuur_id = $model->factuur_id;
if (! $modelProduct->save()) {
$success = false;
break;
}
}
} else {
$success = false;
}
if ($success) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->factuur_id]);
} else {
Yii::$app->session->setFlash('danger', 'Kan niet opslaan, validate errors');
}
}
return $this->render('create', [
'model' => $model,
'modelProducten' => (empty($modelProducten)) ? [new Producten] : $modelProducten
]);
}
if you need any extra code just ask I'll provide it!
hopefully you guys understand the problem and are able to help me out
~ edit ~
#Gunnrryy
the relations are here
also the person works totaly fine only the "Producten" fields don't work
the Facturen model Code
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "facturen".
*
* #property integer $factuur_id
* #property string $date
* #property integer $company_id
* #property integer $person_id
*
* #property Companies $company
* #property Spokepersons $person
* #property Producten[] $productens
*/
class Facturen extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'facturen';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['date', 'company_id', 'person_id'], 'required'],
[['date'], 'string', 'max' => 64],
[['company_id', 'person_id'], 'integer'],
[['company_id'], 'exist', 'skipOnError' => true, 'targetClass' => Companies::className(), 'targetAttribute' => ['company_id' => 'company_id']],
[['person_id'], 'exist', 'skipOnError' => true, 'targetClass' => Spokepersons::className(), 'targetAttribute' => ['person_id' => 'person_id']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'factuur_id' => 'Factuurnummer',
'date' => 'Factuurdatum',
'company_id' => 'Bedrijfsnaam',
'person_id' => 'Contactpersoon',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCompany()
{
return $this->hasOne(Companies::className(), ['company_id' => 'company_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPerson()
{
return $this->hasOne(Spokepersons::className(), ['person_id' => 'person_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProduct()
{
return $this->hasMany(Producten::className(), ['factuur_id' => 'factuur_id']);
}
}

do the fact you already have function for relation you could add a getter for the related field you neeed
eg for company name you could add this function in you Facturen model
/* Getter for Company name name */
public function getCompanyName() {
return $this->company->company_name;
}
then in detail view you can simply companyName
<?= DetailView::widget([
'model' => $model,
'modelProducten' => $modelProducten,
'attributes' => [
'factuur_id',
'companyName',
'date',
],
]) ?>

Related

Query from database multiple rows, but get them in gridview on only one row

I have 4 tables
Equipments:
Laptop : ID - PK, laptop_model, laptop_series, laptop_date_acq, status;
Display : ID - PK, display_model, display_series, display_date_acq, status;
Phone : ID - PK, phone_model, phone_series, phone_date_acq, status;
UserEquipmentMapping: ID - PK, laptop_id ( FK TO id from table laptop), display_id(FK to id from table display), phone_id(FK to id from table Phone), start_date, end_date.
For each user, i am mapping an unique equipment with start_date and end_date, so for now in userequipmentmapping/index i am getting for one user 4 rows like this :
USER_X - Display_model - NULL - NULL - START_DATE - END_DATE;
USER_X - Display_model - NULL - NULL - START_DATE - NULL;
USER_X - NULL - Phone Model - NULL - START_DATE - NULL;
USER_X - NULL - NULL - Laptop Model - START_DATE - NULL;
i want in my grid_view to get on one single row an user with the equipments without end_date.
USER_X - DISPLAY_MODEL - PHONE_MODEL - LAPTOP_MODEL ( The ones without end_date, because the ones with end_date are not available anymore) and in view for each user to see all the equipments assigned, with or without end_date.
Any guidance is a lot of help, being a beginner in yii2. Thank you in advance !
Here is the code:
Controller:
<?php
namespace app\controllers;
use Yii;
use app\models\UserEquipmentMapping;
use app\models\UserequipmentmappingSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\models\User;
use app\models\Laptop;
use app\models\Phone;
use app\models\Display;
/**
* UserequipmentmappingController implements the CRUD actions for UserEquipmentMapping model.
*/
class UserequipmentmappingController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all UserEquipmentMapping models.
* #return mixed
*/
public function actionIndex()
{
$usermodel = new UserEquipmentMapping();
$userquery = $usermodel->getUsers();
$displaymodel = new UserEquipmentMapping();
$displayquery = $displaymodel->getDisplays();
$phonemodel = new UserEquipmentMapping();
$phonequery = $phonemodel->getPhones();
$laptopmodel = new UserEquipmentMapping();
$laptopquery = $laptopmodel->getLaptops();
#foreach($query as $q)
# print_r($q);
#
# die;
$searchModel = new UserequipmentmappingSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'userquery' => $userquery,
'displayquery' => $displayquery,
'laptopquery'=> $laptopquery,
'phonequery'=> $phonequery,
]);
}
/**
* Displays a single UserEquipmentMapping model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new UserEquipmentMapping model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new UserEquipmentMapping();
$usermodel = User::find()->all();
$laptopmodel = Laptop::find()->all();
$phonemodel = Phone::find()->all();
$displaymodel = Display::find()->all();
#die;
#print_r(Yii::$app->request->post()); die;
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
//code
#foreach($laptopmodel as $m){
#print_r($m->status );
#print_r($model->load(Yii::$app->request->post()));
#print_r($model);
#print_r($model->laptop_id);
#print_r($laptopmodel);
#die;
if($model->laptop_id)
{
$laptop = Laptop::findOne($model->laptop_id);
$laptop->status = Laptop::STATUS_ASSIGNED;
$laptop->save();
}
if($model->display_id)
{
$display = Display::findOne($model->display_id);
$display->status = Display::STATUS_ASSIGNED;
$display->save();
}
if($model->phone_id)
{
$phone = Phone::findOne($model->phone_id);
$phone->status = Phone::STATUS_ASSIGNED;
$phone->save();
}
$model->save();
return $this->redirect(['index', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
'usermodel' => $usermodel,
'laptopmodel' => $laptopmodel,
'phonemodel' => $phonemodel,
'displaymodel' => $displaymodel,
]);
}
/**
* Updates an existing UserEquipmentMapping model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$usermodel = User::find()->all();
$laptopmodel = Laptop::find()->all();
$phonemodel = Phone::find()->all();
$displaymodel = Display::find()->all();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
'usermodel' => $usermodel,
'laptopmodel' => $laptopmodel,
'phonemodel' => $phonemodel,
'displaymodel' => $displaymodel,
]);
}
/**
* Deletes an existing UserEquipmentMapping model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the UserEquipmentMapping model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return UserEquipmentMapping the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = UserEquipmentMapping::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
Model :
<?php
namespace app\models;
use Yii;
use app\models\User;
use app\models\UserQuery;
use yii\db\ActiveQuery;
/**
* This is the model class for table "user_equipment_mapping".
*
* #property int $id
* #property int $user_id
* #property int|null $laptop_id
* #property int|null $phone_id
* #property int|null $display_id
* #property string|null $start_date
* #property string|null $stop_date
*
* #property Display $display
* #property Laptop $laptop
* #property Phone $phone
* #property User $user
*/
class UserEquipmentMapping extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'user_equipment_mapping';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['user_id'], 'required'],
[['user_id', 'laptop_id', 'phone_id', 'display_id'], 'integer'],
[['start_date', 'stop_date'], 'safe'],
[['display_id'], 'exist', 'skipOnError' => true, 'targetClass' => Display::className(), 'targetAttribute' => ['display_id' => 'id']],
[['laptop_id'], 'exist', 'skipOnError' => true, 'targetClass' => Laptop::className(), 'targetAttribute' => ['laptop_id' => 'id']],
[['phone_id'], 'exist', 'skipOnError' => true, 'targetClass' => Phone::className(), 'targetAttribute' => ['phone_id' => 'id']],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'laptop_id' => 'Laptop ID',
'phone_id' => 'Phone ID',
'display_id' => 'Display ID',
'start_date' => 'Start Date',
'stop_date' => 'Stop Date',
];
}
/**
* Gets query for [[Display]].
*
* #return \yii\db\ActiveQuery|DisplayQuery
*/
public function getDisplay()
{
return $this->hasOne(Display::className(), ['id' => 'display_id']);
}
/**
* Gets query for [[Laptop]].
*
* #return \yii\db\ActiveQuery|LaptopQuery
*/
public function getLaptop()
{
return $this->hasOne(Laptop::className(), ['id' => 'laptop_id']);
}
/**
* Gets query for [[Phone]].
*
* #return \yii\db\ActiveQuery|PhoneQuery
*/
public function getPhone()
{
return $this->hasOne(Phone::className(), ['id' => 'phone_id']);
}
/**
* Gets query for [[User]].
*
* #return \yii\db\ActiveQuery|UserQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
public function getUsers()
{
return $this->hasMany(User::className(),['user_id', 'id']);
}
public function getLaptops()
{
return $this->hasMany(Laptop::className(),['laptop_id', 'id']);
}
public function getDisplays()
{
return $this->hasMany(Display::className(),['dislpay_id', 'id']);
}
public function getPhones()
{
return $this->hasMany(Phone::className(),['phone_id', 'id']);
}
/**
* {#inheritdoc}
* #return UserEquipmentMappingQuery the active query used by this AR class.
*/
public static function find()
{
return new UserEquipmentMappingQuery(get_called_class());
}
}
Index:
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel app\models\UserequipmentmappingSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'User Equipment Mappings';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-equipment-mapping-index">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Create User Equipment Mapping', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'formatter' => [
'class' => 'yii\i18n\Formatter',
'nullDisplay' => '-',],
'columns' => [
#['class' => 'yii\grid\SerialColumn'],
#'id',
#'user.username',
['attribute' => 'user',
'label' => 'Username',
'value' => 'user.username'
#},
],
#'laptop.laptop_model',
['attribute' => 'laptop',
'label' => 'Laptop Series',
'value' => 'laptop.laptop_series'
#},
],
#'laptop_id',
#'phone.phone_model',
['attribute' => 'phone',
'label' => 'Phone Series',
'value' => 'phone.phone_series'
#},
],
#'phone_id',
#'display.display_model',
['attribute' => 'display',
'label' => 'Display Series',
'value' => 'display.display_series'
#},
],
#'display_id',
'start_date',
'stop_date',
['class' => 'yii\grid\ActionColumn', 'header' => "Actions"],
],
]); ?>
</div>
Form:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\models\User;
use kartik\date\DatePicker;
use yii\web\View;
use yii\web\JqueryAsset;
use app\models\Laptop;
use app\models\Display;
use app\models\Phone;
$userData=ArrayHelper::map($usermodel, 'id','username');
$laptopData=ArrayHelper::map($laptopmodel,'id','laptop_series');
$phoneData=ArrayHelper::map($phonemodel,'id','phone_series');
$displayData=ArrayHelper::map($displaymodel,'id','display_series');
$availablelaptopData = ArrayHelper::map(Laptop::find()->where(['status' => 'Available'])->all(), 'id', 'laptop_series');
$availablephoneData = ArrayHelper::map(Phone::find()->where(['status' => 'Available'])->all(), 'id', 'phone_series');
$availabledisplayData = ArrayHelper::map(Display::find()->where(['status' => 'Available'])->all(), 'id', 'display_series');
?>
<div class="user-equipment-mapping-form">
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($model, 'user_id')->dropDownList($userData, ['prompt'=>'Select...']);?>
<?=$form->field($model, 'laptop_id')->dropDownList($availablelaptopData, ['prompt'=>'Select...']);?>
<?=$form->field($model, 'phone_id')->dropDownList($availablephoneData, ['prompt'=>'Select...']);?>
<?=$form->field($model, 'display_id')->dropDownList($availabledisplayData, ['prompt'=>'Select...']);?>
<?=$form->field($model, 'start_date')->widget(DatePicker::classname(), [
'language' => 'en',
'value' => date('yyyy/mm/dd', strtotime('+7 days')),
'readonly' => true,
#'disabled' => true,
#'size' => 'lg',
#'type' => DatePicker::TYPE_COMPONENT_APPEND,
'options' => ['placeholder' => 'Selectati data'],
'pluginOptions' => [
#'orientation' => 'top right',
'format' => 'yyyy/mm/dd',
'todayHighlight' => true,
'todayBtn' => true,
'autoclose'=>true,
]
]);?>
<?=$form->field($model, 'stop_date')->widget(DatePicker::classname(), [
'language' => 'en',
'value' => date('yyyy/mm/dd', strtotime('+7 days')),
'readonly' => true,
#'disabled' => true,
#'size' => 'lg',
#'type' => DatePicker::TYPE_COMPONENT_APPEND,
'options' => ['placeholder' => 'Selectati data'],
'pluginOptions' => [
#'orientation' => 'top right',
'format' => 'yyyy/mm/dd',
'todayHighlight' => true,
'todayBtn' => true,
'autoclose'=>true,
]
]);?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>

Show Related Data in View Yii 2

I'm new in Yii 2, and I'm creating an inventory system for the library of my school, but I had a problem.
First, I have a relation like this:
I want to show all the adqs (a unique number for each book - that way we don't need to capture the book again for every copy) of a book in his view, but only the adqs related to the book id obviously at the bottom.
My View:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\helpers\Url;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $model app\models\Libros */
/* #var $searchModel app\models\LibrosSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = $model->lib_titulo;
$this->params['breadcrumbs'][] = ['label' => 'Libros', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="libros-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Modificar', ['update', 'id' => $model->lib_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Borrar', ['delete', 'id' => $model->lib_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<div class="row" align="center">
<?php
if ($model->lib_image_web_filename!='') {
echo '<br /><p><img width="500" src="'.Url::to('#web/', true). '/uploads/libros/'.$model->lib_image_web_filename.'"></p>';
}
?>
</div>
<div class="row" style="
text-align: center;
font: normal normal bold 15px/1 'lato';
color: rgba(7,7,7,1);
text-align: center;
">
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'lib_id',
'lib_titulo',
'lib_autor',
//'lib_edicion',
'editorialNombre',
'ubicacionNombre',
'lib_isbn',
'lib_clasificacion',
'lib_seccion',
//'lib_image_src_filename',
//'lib_image_web_filename',
],
]) ?>
</div>
</div>
My Controller (LibrosController):
<?php
namespace backend\controllers;
use Yii;
use app\models\Libros;
use app\models\LibrosSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
/**
* LibrosController implements the CRUD actions for Libros model.
*/
class LibrosController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Libros models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new LibrosSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Libros model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionCreate()
{
$model = new Libros();
if ($model->load(Yii::$app->request->post())) {
$image = UploadedFile::getInstance($model, 'image');
if (!is_null($image)) {
$model->lib_image_src_filename = $image->name;
$ext = end((explode(".", $image->name)));
// generate a unique file name to prevent duplicate filenames
$model->lib_image_web_filename = Yii::$app->security->generateRandomString().".{$ext}";
// the path to save file, you can set an uploadPath
// in Yii::$app->params (as used in example below)
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/libros/';
$path = Yii::$app->params['uploadPath'] . $model->lib_image_web_filename;
$image->saveAs($path);
}
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->lib_id]);
} else {
var_dump ($model->getErrors()); die();
}
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Libros model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
$image = UploadedFile::getInstance($model, 'image');
if (!is_null($image)) {
$model->lib_image_src_filename = $image->name;
$ext = explode(".", $image->name);
$ext_final = end($ext);
// generate a unique file name to prevent duplicate filenames
$model->lib_image_web_filename = Yii::$app->security->generateRandomString().".{$ext_final}";
// the path to save file, you can set an uploadPath
// in Yii::$app->params (as used in example below)
Yii::$app->params['uploadPath'] = Yii::$app->basePath . '/web/uploads/libros/';
$path = Yii::$app->params['uploadPath'] . $model->lib_image_web_filename;
$image->saveAs($path);
}
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->lib_id]);
} else {
var_dump ($model->getErrors()); die();
}
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Deletes an existing Libros model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Libros model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Libros the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Libros::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
My Model (Libros.php):
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "libros".
*
* #property int $lib_id
* #property string $lib_titulo
* #property string $lib_autor
* #property string $lib_edicion
* #property int $lib_ubi
* #property int $lib_editorial_id
* #property string $lib_isbn
* #property string $lib_clasificacion
* #property string $lib_seccion
* #property string $lib_image_src_filename
* #property string $lib_image_web_filename
*
* #property Adq[] $adqs
* #property Editorial $libEditorial
* #property Ubicacion $libUbi
* #property LibrosCarreras[] $librosCarreras
* #property Carreras[] $licCarreras
*/
class Libros extends \yii\db\ActiveRecord
{
const PERMISSIONS_PRIVATE = 10;
const PERMISSIONS_PUBLIC = 20;
public $image;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'libros';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['lib_titulo', 'lib_autor', 'lib_ubi', 'lib_isbn', 'lib_clasificacion', 'lib_seccion', 'lib_image_src_filename', 'lib_image_web_filename'], 'required'],
[['lib_ubi', 'lib_editorial_id'], 'integer'],
[['lib_titulo'], 'string', 'max' => 120],
[['lib_autor', 'lib_clasificacion'], 'string', 'max' => 64],
//[['lib_edicion'], 'string', 'max' => 3],
[['lib_isbn'], 'string', 'max' => 32],
[['lib_seccion'], 'string', 'max' => 2],
[['lib_editorial_id'], 'exist', 'skipOnError' => true, 'targetClass' => Editorial::className(), 'targetAttribute' => ['lib_editorial_id' => 'edi_id']],
[['lib_ubi'], 'exist', 'skipOnError' => true, 'targetClass' => Ubicacion::className(), 'targetAttribute' => ['lib_ubi' => 'ubil_id']],
[['lib_image_src_filename', 'lib_image_web_filename'], 'string', 'max' => 100],
[['image'], 'safe'],
[['image'], 'file', 'extensions'=>'jpg, gif, png'],
[['image'], 'file', 'maxSize'=>'1000000'],
[['lib_image_src_filename', 'lib_image_web_filename'], 'string', 'max' => 255], ];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'lib_id' => 'ID',
'lib_titulo' => 'Titulo',
'lib_autor' => 'Autor',
//'lib_edicion' => 'Edicion',
'lib_editorial_id' => 'Editorial',
'lib_isbn' => 'ISBN',
'lib_clasificacion' => 'Clasificacion',
'lib_ubi' => 'Ubicacion',
'lib_seccion' => 'Seccion',
'image' => 'Captura',
'lib_image_src_filename' => Yii::t('app', 'Nombre de Archivo'),
'lib_image_web_filename' => Yii::t('app', 'Nombre del Directorio'),
'editorialNombre' => 'Editorial',
'ubicacionNombre' => 'Ubicacion',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAdqs()
{
return $this->hasMany(Adq::className(), ['adq_libro_id' => 'lib_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
/**
* #return \yii\db\ActiveQuery
*/
public function getLibrosCarreras()
{
return $this->hasMany(LibrosCarreras::className(), ['lic_libros_id' => 'lib_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getEditorial0()
{
return $this->hasOne(Editorial::className(), ['edi_id' => 'lib_editorial_id']);
}
public function getEditorialNombre()
{
return $this->editorial0->edi_nombre;
}
public function getLibUbi()
{
return $this->hasOne(Ubicacion::className(), ['ubil_id' => 'lib_ubi']);
}
public function getUbicacionNombre()
{
return $this->libUbi->ubil_nombre; }
}
My Search Model (LibrosSearch.php):
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Libros;
/**
* LibrosSearch represents the model behind the search form of `app\models\Libros`.
*/
class LibrosSearch extends Libros
{
public $editorialNombre;
public $ubicacionNombre;
/**
* #inheritdoc
*/
public function rules()
{
return [
[['lib_id', 'lib_ubi', 'lib_editorial_id'], 'integer'],
[['lib_titulo', 'lib_autor', 'lib_isbn', 'lib_clasificacion', 'lib_seccion', 'lib_image_src_filename', 'lib_image_web_filename'], 'safe'],
[['editorialNombre'],'safe'],
[['ubicacionNombre'],'safe'],
];
}
/**
* #inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = Libros::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->setSort([
'attributes'=>[
'editorialNombre'=>[
'asc'=>['editorial.edi_nombre'=>SORT_ASC],
'desc'=>['editorial.edi_nombre'=>SORT_DESC],
'label'=>'Editorial Nombre'
]
]
]);
$dataProvider->setSort([
'attributes'=>[
'ubicacionNombre'=>[
'asc'=>['ubicacion.ubil_nombre'=>SORT_ASC],
'desc'=>['ubicacion.ubil_nombre'=>SORT_DESC],
'label'=>'Ubicacion Nombre'
]
]
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'lib_id' => $this->lib_id,
'lib_ubi' => $this->lib_ubi,
'lib_editorial_id' => $this->lib_editorial_id,
]);
$query->andFilterWhere(['like', 'lib_titulo', $this->lib_titulo])
->andFilterWhere(['like', 'lib_autor', $this->lib_autor])
//->andFilterWhere(['like', 'lib_edicion', $this->lib_edicion])
->andFilterWhere(['like', 'lib_isbn', $this->lib_isbn])
->andFilterWhere(['like', 'lib_clasificacion', $this->lib_clasificacion])
->andFilterWhere(['like', 'lib_seccion', $this->lib_seccion])
->andFilterWhere(['like', 'lib_image_src_filename', $this->lib_image_src_filename])
->andFilterWhere(['like', 'lib_image_web_filename', $this->lib_image_web_filename]);
$query->joinWith(['editorial0'=>function($q)//creamos un nuevo filtro
{
$q->where('editorial.edi_nombre LIKE "%' . $this->editorialNombre . '%"');
}]);
$query->joinWith(['libUbi'=>function($q)//creamos un nuevo filtro
{
$q->where('ubicacion.ubil_nombre LIKE "%' . $this->ubicacionNombre . '%"');
}]);
return $dataProvider;
}
}
How can I accomplish this task?
[
'attribute' => 'adq_libro_id',
'value' => implode(', ', \yii\helpers\ArrayHelper::map($model->Adqs, 'id',
function ( $model )
{
return $model['adq'];
}
)),
'format' => 'raw'
],
try like this. Check the right name of attributes
In your model Libros.php you have this function.
public function getAdqs()
{
return $this->hasMany(Adq::className(), ['adq_libro_id' => 'lib_id']);
}
This means you can access the relations of Libros like:
// where $model is an instance of Libros
$model->adqs->property_name
Or as a function
$model->getAdqs();

there is no any change to the rows displayed when doing "search" in yii2

I have problem when making modelsearch in yii2. Here's is relation diagram
I want to display Jurusan from table aitambah to table ais3 and I want to display NamaMahasiswa from table ai to ais3. I made table s3penghubung so that table aitambah can be related to ais3. I was able to display them. But, when I try to type "BIO" in Jurusan field, the searching not working properly. it is refreshing the page. there is no any change to the rows displayed. so, what should I do to fix that?
MODEL SEARCH CODE
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Ais3;
use app\models\AiTambah;
/**
* Ais3Search represents the model behind the search form about `app\models\Ais3`.
*/
class Ais3Search extends Ais3
{
/**
* #inheritdoc
*/
public function rules()
{
return [
[['id', 'kode'], 'integer'],
[['NRP', 'NRP1', 'NRP2', 'NRP3', 'NRP4', 'NRP5', 'NRP6', 'NRP7', 'namaMahasiswaText', 'ProgramStudi', 'TanggalMasuk', 'TanggalKeluar', 'jURUSANText','NAMKANTOR','ANGKATAN'], 'safe'],
];
}
public $NamaMahasiswa;
public $namaMahasiswaText;
public $NRP1;
public $NRP2;
public $NRP3;
public $NRP4;
public $NRP5;
public $NRP6;
public $NRP7;
public $JURUSAN;
public $jURUSANText;
public $NAMKANTOR;
public $ANGKATAN;
/**
* #inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* #param array $params
*
* #return ActiveDataProvider
*/
public function search($params)
{
$query = Ais3::find();
$query->joinWith('ai');
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'kode' => $this->kode,
]);
$query->andFilterWhere(['like', 'ais3.NRP', $this->NRP])
->andFilterWhere(['like', 'ai.NamaMahasiswa', $this->namaMahasiswaText])
->andFilterWhere(['like', 'ais3.ProgramStudi', $this->ProgramStudi])
->andFilterWhere(['like', 'ai.TanggalMasuk', $this->TanggalMasuk])
->andFilterWhere(['like', 'ais3.TanggalKeluar', $this->TanggalKeluar])
->andFilterWhere(['like', 'aitambah.JURUSAN', $this->JURUSAN]);
return $dataProvider;
}
}
MY GRIDVIEW CODE
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
'NRP',
'namaMahasiswaText',
'ProgramStudi',
//'TanggalMasuk',
[
'attribute' => 'TanggalMasuk',
'value' => function($data) {
return $data->ai->TanggalMasuk;
},],
'TanggalKeluar',
//YANG DITAMBAH
/*[
'attribute'=>'NRP1',
'value'=>'s3penghubung.aitambah.JURUSAN',
'label' => 'Jurusan',
],*/
'jURUSANText',
[
'attribute'=>'NRP2',
'value'=>'s3penghubung.aitambah.NAMKANTOR',
'label' => 'Nama Kantor',
],
[
'attribute'=>'NRP3',
'value'=>'s3penghubung.aitambah.ANGKATAN',
'label' => 'Angkatan',
],
[
'attribute'=>'NRP4',
'value'=>'s3penghubung.aitambah.TELP',
'label' => 'Nomor HP/Telp',
],
[
'attribute'=>'NRP5',
'value'=>'s3penghubung.aitambah.PEKERJAAN',
'label' => 'Pekejaan',
],
[
'attribute'=>'NRP6',
'value'=>'s3penghubung.aitambah.EMAIL',
'label' => 'Email',
],
[
'attribute'=>'NRP7',
'value'=>'s3penghubung.aitambah.KODEPROP',
'label' => 'KodeProp',
],
// 'kode',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
MY MODEL'S CODE
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "ais3".
*
* #property integer $id
* #property string $NRP
* #property string $ProgramStudi
* #property string $TanggalMasuk
* #property string $TanggalKeluar
* #property integer $kode
*
* #property Ai $nRP
* #property S3penghubung $kode0
*/
class Ais3 extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'ais3';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['kode'], 'required'],
[['kode'], 'integer'],
[['NRP'], 'string', 'max' => 15],
[['ProgramStudi'], 'string', 'max' => 5],
[['TanggalMasuk', 'TanggalKeluar'], 'string', 'max' => 20],
[['NRP'], 'exist', 'skipOnError' => true, 'targetClass' => Ai::className(), 'targetAttribute' => ['NRP' => 'NRP']],
[['kode'], 'exist', 'skipOnError' => true, 'targetClass' => S3penghubung::className(), 'targetAttribute' => ['kode' => 'kode']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'NRP' => Yii::t('app', 'Nrp'),
'ProgramStudi' => Yii::t('app', 'Program Studi'),
'TanggalMasuk' => Yii::t('app', 'Tanggal Masuk'),
'TanggalKeluar' => Yii::t('app', 'Tanggal Keluar'),
'kode' => Yii::t('app', 'Kode'),
'namaMahasiswaText' => Yii::t('app', 'Nama Mahasiswa'),
'jURUSANText' => Yii::t('app', 'Jurusan'),
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getai()
{
return $this->hasOne(Ai::className(), ['NRP' => 'NRP']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getS3penghubung()
{
return $this->hasOne(S3penghubung::className(), ['kode' => 'kode']);
}
//YANG DITAMBAH
public function getRelasiS3()
{
return array(
'aitambah'=>array(self::MANY_MANY, 'Aitambah', 'S3Penghubung(AiS3.id, Aitambah.NRP)'),
);
}
public function getNamaMahasiswaText()
{
$ai = ai::findOne(['NRP'=> $this->NRP]);
if (empty($ai))
return '';
return $ai->NamaMahasiswa;
}
public function getJURUSANText()
{
$aitambah = aitambah::findOne(['NRP'=> $this->NRP]);
if (empty($aitambah))
return '';
return $aitambah->JURUSAN;
}
}
I dont know how to fix those codes. Could you please help me to solve this? Thankyou
Your code is very difficult to debug. Try to keep a consistency for your naming conventions. The Yii way is all lower case letters separated with underscores.
Please read this and this about displaying and sorting relations.
As for the solution you can experiment a bit with the following:
Create a new relation in your model:
/**
* #return \yii\db\ActiveQuery
*/
public function getAitambah()
{
return $this->hasOne(Aitambah::className(), ['NRP' => 'NRP']);
}
Then in your SearchModel:
public function rules()
{
return [
[['id', 'kode'], 'integer'],
[['NRP', 'NRP1', 'NRP2', 'NRP3', 'NRP4', 'NRP5', 'NRP6', 'NRP7', 'namaMahasiswaText', 'ProgramStudi', 'TanggalMasuk', 'TanggalKeluar', 'jURUSANText','NAMKANTOR','ANGKATAN', 'JURUSAN'], 'safe'],
];
}
And in your search method:
...
$query = Ais3::find();
query->joinWith(['ai ai', 'aitambah aitambah']);
...
Finally in your view:
[
'attribute' => 'JURUSAN',
'value' => 'aitambah.JURUSAN',
'label' => 'JURUSAN',
],

Add a textinput which does not belong to the same model in yii2

I have a table production with 3 fields productname,batchno,qty. The data productname,batchno I get is from productbatch model. I can insert it clearly. Now I want to insert into table "bottle" with 3 fields bottlename, productname, qty. Productname has relation with bottlename. And the data comes from model productnames. I want to load bottlename whenever I select productname. I can populate the data and can see in firebug. What I want is to add a textinput in the production form and display the bottlename in the same form.
Production Controller
public function actionCreate()
{
$model = new Production();
$productname = new Productnames();
$bottle = new Bottle();
if ($model->load(Yii::$app->request->post()) && $productname->load(Yii::$app->request->post()))
{
$model->save();
//$bottle->attributes = $model->attributes;
$bottle->usedate = $model->productiondate;
$bottle->useqty = $model->prodqty;
$bottle->productname = $model->productname;
$bottle->bottlename = $productname->bottletype;
// $employee->emp_email = $model->emp_email;
// $employee->emp_mobile = $model->emp_mobile;
$bottle->save();
return $this->redirect(['create']);
} else {
return $this->render('create', [
'model' => $model,
'bottle' => $bottle,
]);
}
}
Production _form
<div class="production-form">
<?php $form = ActiveForm::begin(); ?>
<!--<?= Html::a('Select Product', ['/production/productbatch/index'], ['class'=>'btn btn-primary']) ?> -->
<?= $form->field($model, 'productiondate')->widget(
DatePicker::className(), [
// inline too, not bad
'inline' => false,
// modify template for custom rendering
//'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<!-- echo CHtml::button("(+)",array('title'=>"Select Product",'onclick'=>'js:selectproductforproduction();')); -->
<?= $form->field($model, 'productname')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Productnames::find()->all(),'productnames_productname','productnames_productname'),
'language' => 'en',
'options' => ['placeholder' => 'Select Product Name', 'id' => 'catid'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'batchno')->widget(DepDrop::classname(), [
'options'=>['id'=>'subcat-id'],
'pluginOptions'=>[
'depends'=>['catid'],
'placeholder'=>'Select BatchNo',
'url'=>Url::to(['/production/productbatch/subcat'])
]
]); ?>
<?= $form->field($model, 'prodqty')->textInput() ?>
<?= $form->field($productname, 'bottlename')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
The error I'm getting is -
Productnames Model -
<?php
namespace frontend\modules\production\models;
use Yii;
/**
* This is the model class for table "productnames".
*
* #property integer $productid
* #property string $company
* #property string $type
* #property string $productnames_productname
* #property integer $inventory
* #property string $unitrmcost
* #property string $unitlabelcost
* #property string $unitcartonecost
* #property string $productnames_labelname
* #property string $productnames_cartonename
* #property string $bottletype
* #property string $captype
*
* #property Productbatch[] $productbatches
* #property Production[] $productions
* #property Bottlename $bottletype0
* #property Capname $captype0
* #property Cartonename $productnamesCartonename
* #property Labelname $productnamesLabelname
* #property Productsales[] $productsales
*/
class Productnames extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public static function tableName()
{
return 'productnames';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['company', 'type', 'productnames_productname'], 'required'],
[['inventory'], 'integer'],
[['company'], 'string', 'max' => 40],
[['type', 'unitrmcost', 'unitlabelcost', 'unitcartonecost'], 'string', 'max' => 10],
[['productnames_productname', 'productnames_labelname', 'productnames_cartonename'], 'string', 'max' => 60],
[['bottletype', 'captype'], 'string', 'max' => 50],
[['productnames_productname'], 'unique']
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'productid' => 'Productid',
'company' => 'Company',
'type' => 'Type',
'productnames_productname' => 'Productnames Productname',
'inventory' => 'Inventory',
'unitrmcost' => 'Unitrmcost',
'unitlabelcost' => 'Unitlabelcost',
'unitcartonecost' => 'Unitcartonecost',
'productnames_labelname' => 'Productnames Labelname',
'productnames_cartonename' => 'Productnames Cartonename',
'bottletype' => 'Bottletype',
'captype' => 'Captype',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProductbatches()
{
return $this->hasMany(Productbatch::className(), ['productname' => 'productnames_productname']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProductions()
{
return $this->hasMany(Production::className(), ['productname' => 'productnames_productname']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getBottletype0()
{
return $this->hasOne(Bottlename::className(), ['bottlename' => 'bottletype']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getCaptype0()
{
return $this->hasOne(Capname::className(), ['capname' => 'captype']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProductnamesCartonename()
{
return $this->hasOne(Cartonename::className(), ['cartone_name' => 'productnames_cartonename']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProductnamesLabelname()
{
return $this->hasOne(Labelname::className(), ['label_name' => 'productnames_labelname']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getProductsales()
{
return $this->hasMany(Productsales::className(), ['productname' => 'productnames_productname']);
}
}
You forgot to render productname to create view, so pass it.
return $this->render('create', [
'model' => $model,
'bottle' => $bottle,
'productname' => $productname,
]);
Here's variants. Either you use two model instances(current and related) and pass them to view http://www.yiiframework.com/doc-2.0/guide-input-multiple-models.html or add virtual attribute to current model http://www.yiiframework.com/doc-2.0/guide-input-forms.html.
you have use $model = new Production(); in view ..so you have to define productname in production class .like--
public function attributeLabels()
{
return [
'productname' => 'Product Name',
];
}
then check it ...

How to process data in the class behavior public properties in model? (Yii2)

Model code:
<?php
namespace common\models;
use Yii;
use yii\db\ActiveRecord;
use common\components\behaviors\PageAncestorBehavior;
/**
* This is the model class for table "page".
*
* #property integer $id
* #property string $title
* #property string $title_eng
* #property string $text
* #property integer $update_ts
*
* #property PageTreepath[] $pageTreepaths
*/
class Page extends \yii\db\ActiveRecord
{
public $ancestor;
public $descendant;
/**
* #inheritdoc
*/
public static function tableName()
{
return '{{%page}}';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['title', 'text'], 'required'],
[['text'], 'string'],
[['update_ts'], 'integer'],
[['title', 'title_eng'], 'string', 'max' => 255]
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => Yii::t('app', 'Заголовок'),
'title_eng' => Yii::t('app', 'Транcлитерация заголовка'),
'text' => Yii::t('app', 'Текст страницы'),
'update_ts' => Yii::t('app', 'Дата и время последнего обновления'),
'ancestor' => Yii::t('app', 'Категория'),
];
}
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'timestamp' => [
'class' => 'yii\behaviors\TimestampBehavior',
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['update_ts'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['update_ts'],
],
],
'pageAncestor' => [
'class' => PageAncestorBehavior::className(),
'ancestor' => $this->ancestor
]
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPageTreepaths()
{
return $this->hasMany(PageTreepath::className(), ['ancestor' => 'id']);
}
/**
* Get all pages
* #return array
*/
public static function getAllPages() {
$query = new \yii\db\Query;
$query->select('id, title')
->from('{{%page}}')
->orderBy('title');
$command = $query->createCommand();
return $command->queryAll();
}
/**
* Get list all pages for dropdown list
* #return array
*/
public static function getListAllPages() {
$data = self::getAllPages();
$result = array(0 => '-');
if (!empty($data)) {
foreach ($data as $d) {
$result[$d['id']] = $d['title'];
}
}
return $result;
}
}
Behavior code:
<?php
namespace common\components\behaviors;
use yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use common\models\Page;
class PageAncestorBehavior extends Behavior
{
public $ancestor;
public function events()
{
return [
ActiveRecord::EVENT_BEFORE_INSERT => 'beforeInsert',
];
}
/**
* #param $event
*/
public function beforeInsert($event)
{
// --- How to get ancestor value?
//error_log("Ancestor:".$this->ancestor);
}
/**
* #return Page
*/
private function getOwner() {
return $this->owner;
}
}
View:
<?php $form = ActiveForm::begin([
'enableClientValidation'=> true,
'enableAjaxValidation'=> false,
'validateOnSubmit' => true,
'validateOnChange' => true,
'validateOnType' => true,
]); ?>
<?php echo $form->errorSummary($model); ?>
<?= $form->field($model, 'title')->textInput(['maxlength' => 255]) ?>
<?php
$redactor = yii\imperavi\Widget::widget(
[
'model' => $model,
'attribute' => 'text',
'options' => [
'minHeight' => 400,
],
]
);
$error = Html::error($model,'text', ['class' => 'help-block']); //error
?>
<?= $form->field($model, 'text', ['template' => "{$error}\n{label}\n{hint}\n{$redactor}"])->textarea();?>
<br />
<?php
// There is select for Page[ancestor]. Inf Behavior i don't recieved this.
echo $form->field($model, 'ancestor')->dropDownList($allPages);
?>
<div class="form-group">
<?= Html::submitButton(
$model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'),
['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']
) ?>
</div>
<?php ActiveForm::end(); ?>
Controller:
public function actionCreate()
{
$model = new Page;
$allPages = Page::getListAllPages();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'allPages' => $allPages
]);
}
}
I obtain all data from the form, but I don't receive value of $ancestor.
I want to receive these ancestor from the form that to use them in behavior.
Sorry for my English.
Just add ancestor to your rules and try!
[['title','ancestor', 'text'], 'required'],
The variable must be public in the behavior. And in the behavior you access it with this a way $this->ancestor
In your model set pageAncestor, but the name of behavior is PageAncestorBehavior.... why?

Categories