cakePHP 4 实体保存仅在第二次有效

问题描述 投票:0回答:1

我有 18n 本地化,如果这很重要的话。我已经尝试了一切,但我只是不明白问题是什么。 课程类别控制器.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) ){

课程类别表.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(); ?>

表:enter image description here 调试$data:

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

php cakephp
1个回答
0
投票

我能够以某种方式弄清楚。最后,为了让一切正常工作,你需要这样做:

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();
        // $this->CoursesCategories->setLocale('ru');
        // $courseCategory = $this->CoursesCategories->newEntity($data);
        $courseCategory = $this->CoursesCategories->newEmptyEntity();
        // debug($this->CoursesCategories->getLocale()); die;
        $courseCategory->translation($this->CoursesCategories->getLocale())->set($data);
        // $entity->_translations['ru'] = $data;
        // $entity->locale='ru';
        // debug($entity); die;
        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') );
}
© www.soinside.com 2019 - 2024. All rights reserved.