У меня 18n локализация, если это имеет значение. Я все перепробовал, но так и не понял, в чем проблема. КурсыКатегорииController.php
public function add()
{
$model = 'CoursesCategories';
if (isset($_GET['lang']) && $_GET['lang'] == 'kz'){
$this->$model->setLocale('kz');
}elseif (isset($_GET['lang']) && $_GET['lang'] == 'en'){
$this->$model->setLocale('en');
}else{
$this->$model->setLocale('ru');
}
if ( $this->request->is('post') ){
$data = $this->request->getData();
$entity = $this->$model->newEntity($data);
if ( $entity->getErrors() ){
$errors = $entity->getErrors();
foreach( $errors as $index => $err ){
$this->Flash->error( $err[array_key_first($err)] );
}
return $this->redirect( $this->referer() );
}
if ( $this->$model->save($entity) ){
$this->Flash->success(__('Данные успешно сохранены'));
return $this->redirect( $this->referer() );
} else{
$this->Flash->error(__('Ошибка сохранения данных'));
}
}
}
но если я перед "if" добавлю еще одно сохранение, то первое не работает, а второе уже работает:
$this->$model->save($entity)
if ( $this->$model->save($entity) ){
КурсыКатегорииTable.php
<?php
declare(strict_types=1);
namespace App\Model\Table;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* CoursesCategories Model
*
* @method \App\Model\Entity\CoursesCategory newEmptyEntity()
* @method \App\Model\Entity\CoursesCategory newEntity(array $data, array $options = [])
* @method \App\Model\Entity\CoursesCategory[] newEntities(array $data, array $options = [])
* @method \App\Model\Entity\CoursesCategory get($primaryKey, $options = [])
* @method \App\Model\Entity\CoursesCategory findOrCreate($search, ?callable $callback = null, $options = [])
* @method \App\Model\Entity\CoursesCategory patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
* @method \App\Model\Entity\CoursesCategory[] patchEntities(iterable $entities, array $data, array $options = [])
* @method \App\Model\Entity\CoursesCategory|false save(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\CoursesCategory saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
* @method \App\Model\Entity\CoursesCategory[]|\Cake\Datasource\ResultSetInterface|false saveMany(iterable $entities, $options = [])
* @method \App\Model\Entity\CoursesCategory[]|\Cake\Datasource\ResultSetInterface saveManyOrFail(iterable $entities, $options = [])
* @method \App\Model\Entity\CoursesCategory[]|\Cake\Datasource\ResultSetInterface|false deleteMany(iterable $entities, $options = [])
* @method \App\Model\Entity\CoursesCategory[]|\Cake\Datasource\ResultSetInterface deleteManyOrFail(iterable $entities, $options = [])
*/
class CoursesCategoriesTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('courses_categories');
$this->setDisplayField('title');
$this->setPrimaryKey('id');
$this->addBehavior('Translate', [
'fields' => [
'title',
],
'allowEmptyTranslations' => false
]);
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator): Validator
{
$validator
->integer('id')
->allowEmptyString('id', null, 'create');
$validator
->scalar('title')
->allowEmptyString('title');
return $validator;
}
}
Сущность — CourseCategory.php
<?php
declare(strict_types=1);
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* CoursesCategory Entity
*
* @property int $id
* @property string|null $title
*/
class CoursesCategory extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* @var array
*/
protected $_accessible = [
'title' => true,
];
}
Шаблон:
<section class = "content-header">
<div class = "container-fluid">
<div class = "row mb-2">
<div class = "col-sm-6">
<h1>Добавление</h1>
</div>
</div>
</div><!-- /.container-fluid -->
</section>
<?php echo $this->Form->create(null); ?>
<!-- Main content -->
<section class = "content">
<div class = "row">
<div class = "col-md-12">
<div class = "card card-primary">
<div class = "card-header">
<h3 class = "card-title">Данные</h3>
<div class = "card-tools">
<a href = "/admin/courses_categories" type = "button" class = "btn btn-tool">
<i class = "fas fa-arrow-left"></i>
</a>
</div>
</div>
<div class = "card-body form_cols">
<div class = "form-group">
<label for = "inputTitle">Название категории</label>
<?= $this->Form->text('title', array('id' => 'inputTitle', 'class' => 'form-control', 'required' => 'required')); ?>
</div>
<div class = "submit_row">
<?php echo $this->Form->button('Добавить', array('class' => 'btn btn-success')); ?>
</div>
</div>
</div>
</div>
</div>
</section>
<?php echo $this->Form->end(); ?>
Таблица: сюда введите описание изображения Отладка $данных:
APP/Controller\Admin\CoursesCategoriesController.php (line 79)
[
'title' => '11111111',
]
Что мне не хватает?
I just don’t understand what the reason is, I’ve probably already looked at all the files and tried everything I know
@GregSchmidt Может быть. Но у меня проблема в том, что сохранение работает только тогда, когда вы используете его снова. То есть если я напишу $this->$model->save($entity), то это не сработает, но если я повторю это дважды: $this->$model->save($entity); //не работает $this->$model ->save($entity); // теперь это работает, затем сохраняется в базе данных.
Да, я никогда не видел ничего подобного, поэтому у меня нет для вас решения. Я бы предложил посмотреть на вашу функцию beforeSave
, чтобы узнать, не делает ли она что-нибудь, что могло бы изменить состояние от одной попытки сохранения к другой, но из показанного вами кода кажется, что у вас ее нет. Есть ли у вас триггеры или хранимые процедуры на уровне базы данных, которые могут взаимодействовать с вещами здесь?
Мне удалось как-то это выяснить. В конечном итоге, чтобы все работало, нужно сделать следующее:
class CoursesCategory extends Entity
{
use TranslateTrait;
// use TranslateStrategyTrait;
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* @var array
*/
protected $_accessible = [
'title' => true,
'_translations' => true
];
}
и контроллер добавить:
public function add(){
$model = 'CoursesCategories';
if (isset($_GET['lang']) && $_GET['lang'] == 'kz'){
$this->CoursesCategories->setLocale('kz');
}elseif (isset($_GET['lang']) && $_GET['lang'] == 'en'){
$this->CoursesCategories->setLocale('en');
}else{
$this->CoursesCategories->setLocale('ru');
}
if ( $this->request->is('post') ){
$data = $this->request->getData();
$courseCategory = $this->CoursesCategories->newEmptyEntity();
$courseCategory->translation($this->CoursesCategories->getLocale())->set($data);
if ( $this->$model->save($courseCategory) ){
$this->Flash->success(__('Данные успешно сохранены'));
return $this->redirect( $this->referer() );
} else{
$this->Flash->error(__('Ошибка сохранения данных'));
}
}
}
Редактирование контроллера:
public function edit($item_id = null){
if (isset($_GET['lang']) && $_GET['lang'] == 'kz'){
$this->CoursesCategories->setLocale('kz');
}elseif (isset($_GET['lang']) && $_GET['lang'] == 'en'){
$this->CoursesCategories->setLocale('en');
}else{
$this->CoursesCategories->setLocale('ru');
}
$CoursesCategories = $this->CoursesCategories->get($item_id);
if ($this->request->is(['post', 'put'])) {
$new_data = $this->request->getData();
// $old_data = clone $data;
$CoursesCategories->translation($this->CoursesCategories->getLocale())->set($new_data);
if ( $CoursesCategories->getErrors() ){
$errors = $CoursesCategories->getErrors();
foreach( $errors as $index => $err ){
$this->Flash->error( $err[array_key_first($err)] );
}
return $this->redirect( $this->referer() );
}
$new_data = $CoursesCategories->toArray();
$this->CoursesCategories->patchEntity($CoursesCategories, $new_data);
if ($this->CoursesCategories->save($CoursesCategories)) {
$this->Flash->success(__('Изменения сохранены'));
return $this->redirect( $this->referer() );
}
$this->Flash->error(__('Ошибка сохранения'));
}
$this->set( compact('CoursesCategories') );
}
Бит, в котором вы выводите все ошибки, должен происходить внутри блока «не удалось сохранить». Данные могут пройти первоначальную проверку, поэтому сразу после исправления не возникнет ошибок, но затем произойдет сбой по какому-то другому правилу и по этой причине не будет сохранено. Возможно, здесь это не применимо, поскольку вы не показали никаких других правил, но все же это хорошая практика.