Anonymous
Yii2 Установка свойства только для чтения
Сообщение
Anonymous » 19 окт 2024, 07:03
Всем доброго дня
Когда я пытаюсь создать клиент,
получаю ошибку: Установка свойства только для чтения: app\models\form\ClientForm:: Клиентклиент
Как исправить эту ошибку?
Это мой ClientClient(модель)
Код: Выделить всё
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']);
}
}
Это моя клиентская форма (модель):
Код: Выделить всё
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' => '
Please fix the following errors for ' . $id . '[/b]
',
]);
$errorList = str_replace('[*]', '', $errorList); // remove the empty error
$errorLists[] = $errorList;
}
return implode('', $errorLists);
}
private function getAllModels()
{
return [
'Client' => $this->client,
'Phone' => $this->phone,
];
}
}
_form
и контроллер
Код: Выделить всё
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]);
}
Почему Clientclient::tags доступен только для чтения? И как правильно установить отношения модели?
Подробнее здесь:
https://stackoverflow.com/questions/511 ... y-property
1729310586
Anonymous
Всем доброго дня[b] Когда я пытаюсь создать клиент, получаю ошибку: Установка свойства только для чтения: app\models\form\ClientForm:: Клиентклиент Как исправить эту ошибку? Это мой ClientClient(модель) [code]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']); } } [/code] Это моя клиентская форма (модель): [code]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' => ' Please fix the following errors for ' . $id . '[/b] ', ]); $errorList = str_replace('[*]', '', $errorList); // remove the empty error $errorLists[] = $errorList; } return implode('', $errorLists); } private function getAllModels() { return [ 'Client' => $this->client, 'Phone' => $this->phone, ]; } } [/code] _form [code] [/code] и контроллер [code]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]); } [/code] Почему Clientclient::tags доступен только для чтения? И как правильно установить отношения модели? Подробнее здесь: [url]https://stackoverflow.com/questions/51134901/yii2-setting-read-only-property[/url]