Save data to another model cakePHP 3.5

本小妞迷上赌 提交于 2019-12-04 05:51:31

问题


I'm still beginner in cakephp. I have table question and questionQuizzes. I have created the form named existingQuestion in question controller and want to save it in table questionQuizzes. However, the form cannot be saved. I have followed this example but it still cannot be saved.

This is QuestionController

public function existingQuestion()
{  

    //echo "here<br><br>";
    //$QuestionQuizzesTable = 
    $this->loadModel('QuestionQuizzes');
    $questions = $this->paginate($this->Questions);
    $questionQuiz = $this->QuestionQuizzes->newEntity();

    //print_r($this->request->getData());
    //die();

    if($this->request->is('post'))
    {

        $questionQuiz = $this->QuestionQuizzes->patchEntity($questionQuiz, $this->request->getData());
        print_r($this->request->getData());
        die();

        if ($this->QuestionQuizzes->save($questionQuiz)) {
            $this->Flash->success(__('The question has been saved.'));

            return $this->redirect(['action' => 'existingQuestion']);
        }
        $this->Flash->error(__('The question could not be saved. Please, try again.'));
    }

    //$this->Questions->saveAll($this->request->getData());
    $this->set(compact('questions'));
    $this->set('_serialize', ['questions']);
}

Can somebody help me??!

Edited 3: This is my existing_questions.ctp

<?php

 /**
 * @var \App\View\AppView $this
 * @var \App\Model\Entity\Question[]|\Cake\Collection\CollectionInterface 
  $questions
  */
  use Cake\ORM\TableRegistry;
  ?>
  <nav class="large-3 medium-4 columns" id="actions-sidebar">
   <ul class="side-nav">
    <li class="heading"><?= __('Actions') ?></li>
    <li><?= $this->Html->link(__('Courses'), ['controller' => 'Courses',  
    'action' => 'index']) ?></li>
    </ul>
    </nav>
   </nav>
    <div class="questions form large-9 medium-8 columns content">
    <fieldset>
    <legend><?= __('Add Question') ?></legend>
    <?php echo $this->Form->create($questionQuiz) ?>  
    <table cellpadding="0" cellspacing="0">
    <thead>
        <tr>
            <th scope="col"><?= $this->Paginator->sort('checked') ?></th>
            <th scope="col"><?= $this->Paginator->sort('id') ?></th>
            <th scope="col"><?= $this->Paginator->sort('question') ?></th>
            <th scope="col"><?= $this->Paginator->sort('marks') ?></th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($questions as $question): ?>
        <tr>
            <td><?= $this->Form->checkbox('questions[].', ['value' => 
            $question['id'], 'name' => 'question[id][]', 'checked'=>false, 
                'hiddenField' => false])?></td>
               <td><?= $this->Number->format($question->id) ?></td>
                <td><?= h($question->question) ?></td>
                <td><?= $this->Number->format($question->marks) ?></td>
        </tr>
        <?php endforeach; ?>                 
    </tbody>
    </table>
    <input type="submit" value="Save">        
    </form>
    <div class="paginator">
    <ul class="pagination">
        <?= $this->Paginator->first('<< ' . __('first')) ?>
        <?= $this->Paginator->prev('< ' . __('previous')) ?>
        <?= $this->Paginator->numbers() ?>
        <?= $this->Paginator->next(__('next') . ' >') ?>
        <?= $this->Paginator->last(__('last') . ' >>') ?>
    </ul>
    <p><?= $this->Paginator->counter(['format' => __('Page {{page}} of {{pages}}, showing {{current}} record(s) out of {{count}} total')]) ?></p>
     <?php //$this->Form->button(__('Submit'), ['action' => 'existingQuestion'])
         $this->Form->submit('Save'); 
        // $this->Form->end() ?>
</div>
</fieldset>
</div>

Edited 4: I have table quizzes which contains id and quiz id. And I have table questions contains id, question id, questions and marks. Then, I have table questionQuizzes which contains quiz id and question id.

Here is quizzesTable.php model:

class QuizzesTable extends Table
{

/**
 * Initialize method
 *
 * @param array $config The configuration for the Table.
 * @return void
 */
public function initialize(array $config)
{
    parent::initialize($config);

    $this->setTable('quizzes');
    $this->setDisplayField('title');
    $this->setPrimaryKey('id');

    $this->belongsTo('Courses', [
        'foreignKey' => 'course_id',
        'joinType' => 'INNER'
    ]);
    $this->hasMany('Attempts', [
        'foreignKey' => 'quiz_id'
    ]);
    $this->hasMany('Gradebooks', [
        'foreignKey' => 'quiz_id'
    ]);
}

/**
 * Default validation rules.
 *
 * @param \Cake\Validation\Validator $validator Validator instance.
 * @return \Cake\Validation\Validator
 */
public function validationDefault(Validator $validator)
{
    $validator
        ->integer('id')
        ->allowEmpty('id', 'create');

    $validator
        ->scalar('title')
        ->requirePresence('title', 'create')
        ->notEmpty('title');

    return $validator;
}

/**
 * Returns a rules checker object that will be used for validating
 * application integrity.
 *
 * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
 * @return \Cake\ORM\RulesChecker
 */
public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->existsIn(['course_id'], 'Courses'));

    return $rules;
}
}

Here is questionsTable.php

class QuestionsTable extends Table
{

/**
 * Initialize method
 *
 * @param array $config The configuration for the Table.
 * @return void
 */
public function initialize(array $config)
{
    parent::initialize($config);

    $this->setTable('questions');
    $this->setDisplayField('id');
    $this->setPrimaryKey('id');

    $this->hasMany('QuestionQuizzes', [
        'foreignKey' => 'question_id'
    ]);
}

/**
 * Default validation rules.
 *
 * @param \Cake\Validation\Validator $validator Validator instance.
 * @return \Cake\Validation\Validator
 */
public function validationDefault(Validator $validator)
{
    $validator
        ->integer('id')
        ->allowEmpty('id', 'create');

    $validator
        ->scalar('question')
        ->requirePresence('question', 'create')
        ->notEmpty('question');

    $validator
        ->numeric('marks')
        ->requirePresence('marks', 'create')
        ->notEmpty('marks');

    return $validator;
}
}

EDITED: existques function:

public function existQues()
{
    $questions = TableRegistry::get('questions');
    $query = $questions->find();

    foreach ($query as $row) 
    {
        $quizzes = $this->paginate($this->Quizzes);

        $this->set(compact('quizzes'));
        $this->set('_serialize', ['quizzes']);
    }
}

回答1:


Your data is in the wrong format. Where did you find this? It should look like this:

[
    'questions' => [
        '_ids' => [
            0 => 60,
            1 => 61,
        ]
    ]
]

Note that questions is now lower case and plural, and id is replaced with _ids. See here for more details.

You will also want to move this to the Quizzes controller (as I suggested last time) and do patchEntity on a quiz entity (through the Quizzes model), because right now the data you have is meaningless: how does it know what quiz it's supposed to be adding these questions to?



来源:https://stackoverflow.com/questions/47988273/save-data-to-another-model-cakephp-3-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!