How to Save Survey Results

I have a survey form at my website and since the survey is quite long I put it on two pages. The first twelve questions are saved to the database and after that the next twelve questions are saved. But that means that two records are added to the database. I want to save it to the same record not two different records. How can this be done? Each template is saved with a method in the controller that looks like this.

    	public function survey()  {
    		
    		$survey = $this->Surveys->newEmptyEntity();
            if ($this->request->is('post')) {
                $survey = $this->Surveys->patchEntity($survey, $this->request->getData());
                if ($this->Surveys->save($survey)) {
                    $this->Flash->success(__('The survey has been saved.'));
    				
                    return $this->redirect(['action' => 'survey2']);
                }
                $this->Flash->error(__('The survey could not be saved. Please, try again.'));
            }
      
    		$this->set(compact('survey'));
    	}

Your survey function is correctly modelled on the standard add function, but survey2 should be modelled on the standard edit function, and change your redirect here to

return $this->redirect(['action' => 'survey2', $survey->id]);

By passing in the survey ID to the next function, and then loading that entity there instead of creating a new one, you’ll update your record instead of creating a new one.

Thanks, Zuluru.
I used the baked code for the edit function to apply to the survey2 method but now I get the error “Record not found in table “surveys” with primary key [NULL]” It complains about the following lines of code:

public function survey2($id = null){

		$survey = $this->Surveys->get($id, [
            'contain' => [],
        ]);

it just says, that no id was passed to survey2. you should check, if the save method worked and an id was generated

Did you change the redirect from survey so that the ID is passed?

I didn’t pass the $id into the function. I passed it now like this: public function survey2($id = null) and now it works.