Yii2 Setting read-only property - yii2

Good day everyone
When I try to create a client, I get an error: Setting read-only property: app\models\form\ClientForm::Clientclient
How can I fix this error?
This is my ClientClient(model)
class ClientClient extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'client_client';
}
public $clientclients;
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['age', 'client_id'], 'integer'],
[['first_name', 'patronymic', 'last_name', 'clientclients'], 'string', 'max' => 255],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'first_name' => 'First Name',
'patronymic' => 'Patronymic',
'last_name' => 'Last Name',
'age' => 'Age',
'client_id' => 'Client Id',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getClient_id()
{
return $this->hasOne(ClientPhone::class, ['client_id' => 'id']);
}
public function getPhone()
{
return $this->hasOne(ClientPhone::class, ['phone_digital' => 'id']);
}
}
This is my ClientForm(model):
class ClientForm extends model
{
private $_client;
private $_phone;
public function rules()
{
return [
[['ClientClient'], 'required'],
[['ClientPhone'], 'safe'],
];
}
public function afterValidate()
{
$error = false;
if (!$this->ClientClient->validate()) {
$error = true;
}
if (!$this->ClientPhone->validate()) {
$error = true;
}
if ($error) {
$this->addError(null); // add an empty error to prevent saving
}
parent::afterValidate();
}
public function save()
{
if (!$this->validate()) {
return false;
}
$transaction = Yii::$app->db->beginTransaction();
if (!$this->ClientClient->save()) {
$transaction->rollBack();
return false;
}
$this->ClientPhone->client_id = $this->ClientClient->id;
if (!$this->phone->save(false)) {
$transaction->rollBack();
return false;
}
$transaction->commit();
return true;
}
public function getClientclient()
{
return $this->_client;
}
public function setClient($client)
{
if ($client instanceof Client) {
$this->_client = $client;
} else if (is_array($client)) {
$this->_client->setAttributes($client);
}
}
public function getphone()
{
if ($this->_phone === null) {
if ($this->client->isNewRecord) {
$this->_phone = new Phone();
$this->_phone->loadDefaultValues();
} else {
$this->_phone = $this->client->phone;
}
}
return $this->_phone;
}
public function setPhone($phone)
{
if (is_array($phone)) {
$this->phone->setAttributes($phone);
} elseif ($phone instanceof Phone) {
$this->_phone = $phone;
}
}
public function errorSummary($form)
{
$errorLists = [];
foreach ($this->getAllModels() as $id => $model) {
$errorList = $form->errorSummary($model, [
'header' => '<p>Please fix the following errors for <b>' . $id . '</b></p>',
]);
$errorList = str_replace('<li></li>', '', $errorList); // remove the empty error
$errorLists[] = $errorList;
}
return implode('', $errorLists);
}
private function getAllModels()
{
return [
'Client' => $this->client,
'Phone' => $this->phone,
];
}
}
_form
<div class="clientclient-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($clientForm->Clientclient, 'first_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($clientForm->Clientclient, 'patronymic')->textInput(['maxlength' => true]) ?>
<?= $form->field($clientForm->clientphone, 'last_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($clientForm->clientphone, 'phone_digital')->widget( MaskedInput::class, ['mask' => '9999999999'])?>
<?= $form->field($clientForm->Clientclient, 'age')->textInput() ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
and Controller
public function actionCreate()
{
$clientForm = new ClientForm();
$clientForm->Clientclient = new ClientClient();
$clientForm->setAttributes(Yii::$app->request->post());
if (Yii::$app->request->post() && $clientForm->save()) {
Yii::$app->getSession()->setFlash('success', 'Clientclient has been created.');
return $this->redirect(['update', 'id' => $clientForm->Clientclient->id]);
} elseif (!Yii::$app->request->isPost) {
$clientForm->load(Yii::$app->request->get());
}
return $this->render('create', ['clientForm' => $clientForm]);
}
public function actionUpdate($id)
{
$clientForm = new ClientForm();
$clientForm->ClientClients = $this->findModel($id);
$clientForm->setAttributes(Yii::$app->request->post());
if (Yii::$app->request->post() && $clientForm->save()) {
Yii::$app->getSession()->setFlash('success', 'clientClient has been created.');
return $this->redirect(['update', 'id' => $clientForm->ClientClient->id]);
} elseif (!Yii::$app->request->isPost) {
$clientForm->load(Yii::$app->request->get());
}
return $this->render('create', ['clientForm' => $clientForm]);
}
Why is Clientclient::tags read-only? And whats the proper way to set a model relationship?

I get an error: Setting read-only property:
app\models\form\ClientForm::Clientclient
You are using Yii getter and setter class methods instead of public properties but only getter method is defined inside your ClientForm class. You need to also add the Setter method:
public function setClientclient($value)
{
$this->_client = $value;
}
See Concept Properties in official documentation for more details.

Easiest approach is to use setAttributes. Call it before or after $model->load(Yii::$app->request->post())
$model->setAttribute('_client', $value);

Related

how to addError function in yii2 model

i want make form for change password, with field old password and new password like this
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'old_password')->textInput()->label('Old Password ') ?>
<?= $form->field($model, 'password')->passwordInput()->label(' New Password ') ?>
<?= $form->field($model, 'confirm_password')->passwordInput()->label('Confirm new password') ?>
<div class="form-group">
<?= Html::submitButton('Change', ['class' => 'btn btn-primary btn-fill']) ?>
</div>
<?php ActiveForm::end(); ?>
I have controller like this
public function actionPass()
{
$id=Yii::$app->user->id;
$modelUser = $this->findModel($id);
try {
$model = new \frontend\models\ChangePasswordForm($id);
} catch (InvalidParamException $e) {
throw new \yii\web\BadRequestHttpException($e->getMessage());
}
if ($model->load(\Yii::$app->request->post())) {
if ( $model->validate() && $model->changePassword()) {
Yii::$app->session->setFlash('success', 'Password success to change ');
return $this->render('index', [
'model' => $model,
'modelUser' => $modelUser,
]);
} else {
Yii::$app->session->setFlash('error', 'Password failed to change!');
return $this->render('index', [
'model' => $model,
'modelUser' => $modelUser,
]);
}
}
i have model to manage change password process
class ChangePasswordForm extends Model
{
public $id;
public $password;
public $confirm_password;
public $old_password;
/**
* #var \common\models\User
*/
private $_user;
/**
* Creates a form model given a token.
*
* #param string $token
* #param array $config name-value pairs that will be used to initialize the object properties
* #throws \yii\base\InvalidParamException if token is empty or not valid
*/
public function __construct($id, $config = [])
{
$this->_user = User::findIdentity($id);
if (!$this->_user) {
throw new InvalidParamException('Unable to find user!');
}
$this->id = $this->_user->id;
parent::__construct($config);
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['password','confirm_password'], 'required'],
[['password','confirm_password'], 'string', 'min' => 8],
['confirm_password', 'compare', 'compareAttribute' => 'password'],
['old_password','findPasswords'],
];
}
/**
* Changes password.
*
* #return boolean if password was changed.
*/
public function changePassword()
{
$user = $this->_user;
$user->setPassword($this->password);
//$user->ps=$this->password;
return $user->save();
}
public function findPasswords($attribute, $params, $validator)
{
$user = User::findOne(Yii::$app->user->id);
if (!Yii::$app->getSecurity()->validatePassword($this->old_password, $user->password_hash))
$this->addError($attribute, 'The Old Password not match.');
}
}
the error validation for new password and confirm new password works, but not for old password field, the error not show in form when i fill password that not match with old password. Any help?
Shouldn't it be like this?
public function findPasswords($attribute, $params, $validator)
{
$user = User::findOne(Yii::$app->user->id);
if (!Yii::$app->getSecurity()->validatePassword($this->old_password, $user->password_hash))
$this->addError($attribute, 'The Old Password not match.');
return false;
}
return true;
}

Many To Many relations Yii2

I need help with this code, I'm new to Yii2.
I'm building a sample project to start, and I don't know why my code gets the right result but doesn't save the ids I need into the many-to-many table for the relationship.
I started from this sample in the wiki: https://www.yiiframework.com/wiki/708/book-has-author-many-to-many-relations-using-kartikselect2
My Model
public function rules()
{
return [
[['anno', 'durata', 'flagdelete', 'categoriaid'], 'integer'],
[['titolo', 'riassunto', 'regista', 'descrizione'], 'string', 'max' => 50],
[['attoriIds'], 'safe'],
];
}
public function attributeLabels()
{
return [
'titolo' => 'Titolo',
'anno' => 'Anno',
'durata' => 'Durata',
'riassunto' => 'Riassunto',
'regista' => 'Regista',
'descrizione' => 'Descrizione',
'categoriaid' => 'Categoria',
'nome' => 'Attori',
];
}
/**
* #var array
*/
public $attoriIds = [];
public function getdropAttori()
{
$data = Attori::find()->asArray()->all();
return ArrayHelper::map($data, 'id', 'nome');
}
/**
* #return mixed
*/
public function getAttoriIds()
{
return $this->attoriIds;
}
/**
* #param $attoriIds
*/
public function setAttoriIds($attoriIds)
{
$this->attoriIds = \yii\helpers\ArrayHelper::getColumn(
$this->getAttdvd()->asArray()->all(),
'attori_id'
);
}
/**
* #param $insert
* #param $changedAttributes
*/
public function afterSave($insert, $changedAttributes)
{
$actualAttoris = [];
$attoriExists = 0;
if (($actualAttoris = Attdvd::find()->andWhere(
"dvd_id = $this->id"
)->asArray()->all()) !== null
) {
$actualAttoris = ArrayHelper::getColumn($actualAttoris, 'attori_id');
$attoriExists = 1;
}
if (!empty($this->despIds)) {
foreach ($this->despIds as $id) {
$actualAttoris = array_diff($actualAttoris, [$id]);
$r = new Attdvd();
$r->dvd_id = $this->id;
$r->attori_id = $id;
$r->save();
}
}
if ($attoriExists == 1) {
foreach ($actualAttoris as $remove) {
$r = Attdvd::findOne(
['attori_id' => $remove, 'dvd_id' => $this->id]
);
$r->delete();
}
}
parent::afterSave($insert, $changedAttributes);
}
/**
* #return mixed
*/
public function getAttdvd()
{
return $this->hasMany(Attori::className(), ['id' => 'attori_id'])->viaTable(
'attdvd', ['dvd_id' => 'id']
);
}
My Controller
public function actionCreate()
{
$model = new Dvd();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
]);
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
//i think the problem is the line below
$model->attoriIds = $model->AttoriIds;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
]);
}
My form (that work properly):
<?= $form->field($model, 'AttoriIds')->widget(Select2::classname(), ['data'=>$model->dropAttori, 'options' => ['multiple' => true, 'placeholder' => 'Seleziona attori']])->label('Attori') ?>
It's bad way because the making of that code in multiple models will make models dirtier. The better way is usage of a universal component that can manage relations in your models. For example yii2-many-to-many-behavior

YII2 Call to a member function isAttributeRequired() on a non-object

I am new with Yii2, im trying to make sales transaction, but i have problem for dropdownlist in detail section.
for this module, i have 3 tables :
1. for header, table salesheader
2. for detail, table salesdetail
3. for item, table item
this is my code :
on controller :
public function actionUpdate($id)
{
$model = $this->findModel($id); //find appropriate record in salesheader
//$modeldetail = salesdetail::findModel($id);
$modeldetail = new salesdetail();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
} else {
$item = item::find()->select(["concat('[',code,'] - ', name) as item", "id"])->indexBy('id')->column();
$detail = salesdetail::find()->select(["*"])->all(); //find appropriate record in salesdetail
return $this->render('update', [
'model' => $model,
'modeldetail' => $modeldetail,
'item' => $item,
'detail' => $detail
]);
}
}
on salesheader model
namespace app\models;
use Yii;
class salesheader extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'salesheader';
}
public function rules()
{
return [
[['partnerId', 'date', 'term', 'name'], 'required'],
[['name', 'invNumber'], 'string'],
[['partnerId', 'term'], 'integer']
];
}
public function attributeLabels()
{
return [
'partnerId' => 'Customer',
'date' => 'Date',
'invNumber' => 'Inv. Number',
'term' => 'Term',
'name' => 'Name'
];
}
on salesdetail model
namespace app\models;
use Yii;
class salesdetail extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'salesdetail';
}
public function rules()
{
return [
[['itemId', 'qty', 'price'], 'required'],
[['unit'], 'string']
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'itemId' => 'Item',
];
}
}
on my view
<?= $form->field($detail, 'itemId')->dropDownList($item)->label(false) ?>
and when open the page in browser, i got this error "Call to a member function isAttributeRequired() on a non-object"
and if i change this line on controller
//$modeldetail = salesdetail::findModel($id);
$modeldetail = new salesdetail();
to this one
$modeldetail = salesdetail::findModel($id);
//$modeldetail = new salesdetail();
then the error would be "Call to undefined method app\models\salesdetail::findModel()"
can somebody tell me what am i doing wrong ?
and how to get appropriate data from salesdetail based on salesheader and put it on dropdownlist ?
Thank you for ur help

Yii2 hiddenInput does not react on options value

Going to change image field in model by changing value in hidden field:
View:
<?= HTML::activeHiddenInput($model, 'image_clean', [
'id' => 'cleaner',
'name' => 'cleaner',
'value' => false
])
?>
<?=
Html::button('Remove logo', [
'id' => 'btn_clean',
])
?>
at the end of view:
<?php
$this->registerJs(<<<JS
$('#btn_clean').on('click', function() {
alert('Going to remove logo'); // Reachable!
$('#cleaner').val(true);
});
JS
);
?>
Model:
public $image_clean; // Remove logo
public function rules() {
return [
//...
[['image_clean'], 'boolean'],
//...
];
}
public function attributeLabels() {
return [
//...
'image_clean' => 'Remove logo',
//...
];
}
public function beforeValidate() {
if($this->image_clean) { } // Never!
return parent::beforeValidate();
}
public function beforeSave($insert) {
if($this->image_clean) { } // Never!
return parent::beforeSave($insert);
}
Unfortunately, $this->image_clean in model's beforeValidate / beforeSave always false. Why?
Javascript btn_clean handler works as it should be.
Hiddeninput's name overrides default one.
So, I just remove 'name' => 'cleaner'. It's not required

Undefined variable: yii2

Getting error when I am trying to create dynamic form in using yii2-dynamicform. at the time of create method it is working fine but at the time of update showing the error. I have two tables one is
1.vendors &
2.vendors_more_categories
Relation is 1-* between vendors & vendors_more_categories I just refereed https://github.com/wbraganca/yii2-dynamicform this link.
<?php
namespace app\controllers;
namespace backend\controllers;
use Yii;
use app\models\Vendors;
use app\models\VendorsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\filters\AccessControl;
use app\models\VendorsMoreCategories;
use backend\models\Model;
use yii\web\Response;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
/**
* VendorsController implements the CRUD actions for Vendors model.
*/
class VendorsController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['index','create', 'update', 'delete'],
'rules' => [
[
'actions' => ['index','create', 'update', 'delete'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all Vendors models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new VendorsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Vendors model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Vendors model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Vendors();
$modelsVendorsMoreCategories = [new VendorsMoreCategories];
if($model->load(Yii::$app->request->post())){
$modelsVendorsMoreCategories = Model::createMultiple(VendorsMoreCategories::classname());
Model::loadMultiple($modelsVendorsMoreCategories, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsVendorsMoreCategories) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsVendorsMoreCategories as $modelVendorsMoreCategories) {
$modelVendorsMoreCategories->vmc_ven_id = $model->ven_id;
if (! ($flag = $modelVendorsMoreCategories->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
$model->file = UploadedFile::getInstance($model, 'file');
$save_file = '';
if($model->file){
$imagename = Vendors::find()->orderBy('ven_id DESC')->one();
$imagename=$imagename->ven_id+1;
$imagepath = 'images/imgvendors/'; // Create folder under web/uploads/logo
$model->ven_business_logo = $imagepath.$imagename.'.'.$model->file->extension;
$save_file = 1;
}
if ($model->save(false)) {
if($save_file){
$model->file->saveAs($model->ven_business_logo);
}
return $this->redirect(['view', 'id' => $model->ven_id]);
}
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}else {
return $this->render('create', [
'model' => $model,
'modelsVendorsMoreCategories' => (empty($modelsVendorsMoreCategories)) ? [new VendorsMoreCategories] : $modelsVendorsMoreCategories
]);
}
}
/**
* Updates an existing Vendors model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
//print_r($model->attributes);
$modelsVendorsMoreCategories = $model->ven_id;
if($model->load(Yii::$app->request->post())){
$oldIDs = ArrayHelper::map($modelsVendorsMoreCategories, 'id', 'id');
$modelsVendorsMoreCategories = Model::createMultiple(VendorsMoreCategories::classname(), $modelsVendorsMoreCategories);
Model::loadMultiple($modelsVendorsMoreCategories, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsVendorsMoreCategories, 'id', 'id')));
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsVendorsMoreCategories) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (! empty($deletedIDs)) {
Address::deleteAll(['id' => $deletedIDs]);
}
foreach ($modelsVendorsMoreCategories as $modelVendorsMoreCategories) {
$modelVendorsMoreCategories->vmc_ven_id = $model->ven_id;
if (! ($flag = $modelVendorsMoreCategories->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
$model->file = UploadedFile::getInstance($model, 'file');
$save_file = '';
if($model->file){
$imagepath = 'images/imgvendors/'; // Create folder under web/uploads/logo
$model->ven_business_logo = $imagepath.$model->ven_id.'.'.$model->file->extension;
$save_file = 1;
}
if ($model->save(false)) {
if($save_file){
$model->file->saveAs($model->ven_business_logo);
}
return $this->redirect(['view', 'id' => $model->ven_id]);
}
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}else {
return $this->render('update', [
'model' => $model,
'modelsVendorsMoreCategories' => (empty($modelsVendorsMoreCategories)) ? [new VendorsMoreCategories] : $modelsVendorsMoreCategories
]);
}
}
/**
* Deletes an existing Vendors model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Vendors model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Vendors the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Vendors::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
//Function used for deleting the images
public function actionDeleteimg($id, $field)
{
$img = $this->findModel($id)->$field;
if($img){
if (!unlink($img)) {
return false;
}
}
$img = $this->findModel($id);
$img->$field = NULL;
$img->update();
return $this->redirect(['update', 'id' => $id]);
}
//Function used for getting more sub categories for vendor
public function actionGetSubCategories()
{
$mbcid=$_GET['ven_main_category_id'];
$sbcid=$_GET['ven_sub_category_id'];
echo $mbcid;
}
public function actionLists($id)
{
$countVendors = Vendors::find()->where(['ven_contact_person_id' => $id])->count();
$vendors = Vendors::find()->where(['ven_contact_person_id' => $id])->all();
if ($countVendors > 0) {
foreach ($vendors as $vendor) {
echo "<option value='" . $vendor->ven_id . "'>" . $vendor->ven_company_name . "</option>";
}
} else {
echo "<option></option>";
}
}
}
You accessing modelsVendorsMoreCategories[0] (as an element of an array )
'model'=> $modelsVendorsMoreCategories[0],
in your DinamicForm widget but when you update the model you pass as $modelsVendorsMoreCategories this value
$modelsVendorsMoreCategories = $model->ven_id;
(don't seems an array, you must be sure this object contain an array with a proper element in 0 index))
'modelsVendorsMoreCategories' => (empty($modelsVendorsMoreCategories)) ?
[new VendorsMoreCategories] : $modelsVendorsMoreCategories
]);
$modelsVendorsMoreCategories should contain the VendorsMoreCategories model in actionUpdate method. In this code ($modelsVendorsMoreCategories = $model->ven_id) $modelsVendorsMoreCategories contains $model->ven_id. It is an integer value, not the VendorsMoreCategories object.
The Vendors model should contain a relation on the VendorsMoreCategories model:
class Vendors extends \yii\db\ActiveRecord
{
....
public function getVendorsMoreCategories()
{
return $this->hasMany(VendorsMoreCategories::className(), 'vendor_id'=>'id']);
}
}
And then, you should use that relation in your actionUpdate method:
$model = $this->findModel($id);
$modelsVendorsMoreCategories = $model->vendorsMoreCategories;
if(!$modelsVendorsMoreCategories) {
$modelsVendorsMoreCategories = [new VendorsMoreCategories];
}
In your actionUpdate you have:
$modelsVendorsMoreCategories = $model->ven_id;
But you should have:
$modelsVendorsMoreCategories = $model->nameOfMyRelation;
To get what's the real name, go in your $model, and look for something like:
/**
* #return \yii\db\ActiveQuery
*/
public function getNameOfMyRelation()
{
return $this->hasMany(VendorsMoreCategories::className(), ['ven_id' => 'id']);
}
If you don't have any function making the relation of this two tables, write one. If you having trouble doing that, you can always use the gii's model generator and check the Vendors model (you dont need to replace it, just preview the code).
Check your create.php file in view folder, pass required variable on
_form.php file from here as:-
<?= $this->render('_form', [
'model' => $model,
'modelsAddress' => $modelsAddress,
]) ?>
Check Your create file in view folder:
Controller:
Controller pass the parameter into create.php
return $this->render('create', [
'model' => $model,
'modelsVendorsMoreCategories' => (empty($modelsVendorsMoreCategories)) ? [new VendorsMoreCategories] : $modelsVendorsMoreCategories
]);
View:create.php
If You miss the parameter: 'modelsVendorsMoreCategories' =>$modelsVendorsMoreCategories.
It shows the Undefined variable error in _form.php page.
<?= $this->render('_form', [
'model' => $model,
'modelsVendorsMoreCategories' =>$modelsVendorsMoreCategories
])?>
View:_form.php
$modelsVendorsMoreCategories[0];
the paramater not passing before now it passing.