Update using hasMany in CakePHP does not work

Asked 2 years ago, Updated 2 years ago, 41 views

I am using cakePHP 2.4.9.
Combine the following two tables using the hasMany model for addition, editing, and updating.

events table

CREATE TABLE `events`(
  `id`int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name`varchar(256) DEFAULT NULL,
  `latitude`decimal(18,15) DEFAULT NULL,
  `longitude`decimal(18,15) DEFAULT NULL,
  `adult_price`int(11) DEFAULT NULL,
  `adult_age`int(11) DEFAULT NULL,
  `child_price`int(11) DEFAULT NULL,
  `child_age`int(11) DEFAULT NULL,
  `access`text,
  `description`text,
  `minimun_participants_number`int(11) DEFAULT NULL,
  `child_policy_flag`int(11) DEFAULT NULL,
  `meals_flug`int(11) DEFAULT NULL,
  `time_of_day`int(11) DEFAULT NULL,
  `pickup_flag`int(11) DEFAULT NULL,
  `duration_hour`int(11) DEFAULT NULL,
  `pv`int(11) DEFAULT NULL,
  `rating`int(11) DEFAULT NULL,
  `created`timestamp NULL DEFAULT NULL,
  `modified`timestamp NULL DEFAULT NULL,
ENGINE=MyISAM DEFAULT CHARSET=utf8;

events_schedules table

CREATE TABLE `events_schedules`(
  `id`int(11) unsigned NOT NULL AUTO_INCREMENT,
  `event_id`int(10) DEFAULT NULL,
  `title`varchar(50) DEFAULT NULL,
  `description`text,
  `start_hour`int(11) DEFAULT NULL,
  `start_min`int(11) DEFAULT NULL,
  `end_hour`int(11) DEFAULT NULL,
  `end_min`int(11) DEFAULT NULL,
  `created`datetime DEFAULT NULL,
  `modified`datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
ENGINE=MyISAM DEFAULT CHARSET=utf8;

Model/Event.php

<?php 
class EventController extensions AppModel
{
    public$hasMany=array(
        'Event' = > array(
            'className' = > 'Event',
            'foreignKey' = > 'event_id',
            'dependent' = > true,
            'conditions' = >',
            'fields' = >',
            'order' = >',
            'limit' = >',
            'offset' = >',
            'exclusive' = >',
            'finderQuery' = >',
            'counterQuery' = >',
        ),
    );
}

allows you to add multiple schedules per event ID.
This is the controller's processing.
Controller/EventController.php

<?php
App::uses('AppController', 'Controller');
App::uses('HttpSocket', 'Network/Http');

class EventsController extensions AppController
{

    public$uses=array('Event', 'EventSchedule');

    public function edit($id=null)
    {
        if($this->request->is('Event')||$this->request->is('post'))){
            if($id==null){
                $id = $this->Event->getLastInsertID();
            } else{
                $this->EventSchedule->deleteAll(array('EventSchedule.event_id'=>$id));
            }
            $this->Event->id=$id;

            if($this->Event->save($this->request->data)){
                if($this->request->data('EventsSchedule')){
                    $this->EventsSchedule->saveAll($this->request->data['EventsSchedule',array('deep'=>true)));
                }
                {
                    $this->Flash->success(__('Registration Completed'));
                }

                $this->redirect(array('action'=>'edit', $this->Event->id));
            } else{
                $this->Flash->error(__('Failed'));
            }
        }

        $options=array('conditions'=>array('Event.id'=>$id));
        $this->request->data=$this->Event->find('first',$options);
        $this->set('event', $this->request->data);
    }

View provides multiple inputs to be saved
View/Events/edit.ctp

<?phpecho$this->Form->create('Event', array('type'=>'button','action'=>'edit','div'=>false));?>
    (omitted)
    .
    .
    .
    <?php 
    $count = 0; 
    foreach($this->data['EventsSchedule'] as $EventsSchedule): ?> 
        <tr>
            <thrspan="8">Schedule</th>
            <td>
                <div class="form-inline">
                    <div class="ui two fields">
                        <div class="form-group">
                            <label>Japanese</label>
                            <?php echo$this->Form->input('EventsSchedule.'.$count.'.title', array('type'=>'text', 'placeholder'=>'s schedule title (Japanese)', 'div'=>false, 'label'=>quality;quality='qu';qualse;qualse;qualse;qualse>qualse ,'
                        </div>
                        <div class="form-group">
                            <label>Learn more</label>
                            <?php echo$this->Form->input('EventsSchedule.'.$count.'.description', array('type'=>'text', 'placeholder'=>'Schedule Detail (Japanese)', 'div'=>false, 'label'='>control='>policy>policy
                        </div>
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <td>
                <div class="form-inline">
                    <div class="ui fields">
                        <div class="form-group">
                            <label>Start Time</label>
                            <?php echo $this->Form-> input('EventsSchedule.'.$count.'.start_hour', array('type' =>'select', 'options' =>Configure::read('Hour.codes'), 'class' =>' select, fault='>dive
                            <?php echo $this->Form-> input('EventsSchedule.'.$count.'.start_min', array('type' =>'select', 'options' =>Configure::read('Minute.codes'), 'class' =>select, fault='>div 
                        </div>
                        <div class="form-group">
                            <label>End Time</label> 
                            <?php echo $this->Form-> input('EventsSchedule.'.$count.'.end_hour', array('type' =>'select', 'options' =>Configure::read('Hour.codes'), 'class' =>' select, fault='>dive
                            <?php echo $this->Form-> input('EventsSchedule.'.$count.'.end_min', array('type' =>'select', 'options' =>Configure::read('Minute.codes'), 'class' =>select, fault='>div
                        </div>
                    </div>
                </div>
            </td>
        </tr>
    <?php$count++;?>
    <?php endforeach;?>
<?phpecho$this->Form->end(array('label'=>'registration/editing', 'class'=>'btnbtn-primary'));?>

So far, we have managed to prepare the following:
·Event_id is not saved in the Events_schedule table when you press Update
·I want to be able to dynamically add the input field of the schedule

I would appreciate it if someone could let me know.
Thank you for your cooperation.

cakephp

2022-09-29 22:33

1 Answers

There are many strange things about the example code, but I will focus on the saved parts.

In EventsController::edit(), $this->Event->save() followed by $this->EventSchedule->saveAll(), but use saveAssociated altogether.

http://book.cakephp.org/2.0/ja/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array

if($this->Event->saveAssociated($this->request->data)){
    // Successful Storage Processing
} else{
    // What to do in the Event of a Failed Save
}

Also, since the id of the EventSchedule is not specified on the View side, a new EventSchedule record is created every time.

So, on the View side,

<?php
foreach($this->request->data['EventsSchedule'] as $count=>$EventsSchedule): ?> 
    <tr>
        <thrspan="8">Schedule</th>
        <td>
          <?phpecho$this->Form->hidden("EventsSchedule.$count.id");?>

Set EventsSchedule.id as hidden as shown in .

(Increments $count in the foreach loop, but if you get it as a key in foreach like this, you don't need to increase it.)


2022-09-29 22:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.