Entity saving only works the second time cakePHP4

I have 18n localization, if that matters. I’ve tried everything, but I just don’t understand what the problem is. CoursesCategoriesController.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(__('Success'));
                return $this->redirect( $this->referer() );
            } else{
                $this->Flash->error(__('Not succes'));
            }
        }
    }

but if I add another save before “if”, then the first one doesn’t work, but the second one already works:

$this->$model->save($entity)
if( $this->$model->save($entity) ){

CoursesCategoriesTable.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;
    }
}

Entity - 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,
    ];
}

Template:

<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(); ?>

Debug $data:

APP/Controller\Admin\CoursesCategoriesController.php (line 79)
[
  'title' => '11111111',
]

What am I missing? Why is a record only added to the database after a duplicate save?

If I remove

$this->addBehavior('Translate', [
             'fields' => [
                 'title',
             ],
             'allowEmptyTranslations' => false
         ]);

and therefore it’s

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');
        }

for saving to work, then everything works. But at the same time, other models remain fine with this “addBehavior”

I was able to figure it out somehow. In the end, for everything to work, you need to do this:

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
    ];
}

and controller add:

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(__('Ошибка сохранения данных'));
        }
    }
}

controller edit:

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') );
}