1
votes

How do you keep saveAssociated from saving records for associated data if the fields for the associated data are blank? My app is running CakePHP 2.4.

I'm including image uploads in one of my models with a hasMany Image relationship: it can successfully add attachments using the $this->Form->input('Image.0.image'... field in my form. These image uploads should be optional, but when the upload fields are blank, the save operation creates records for blank attachments.

I've tried checking the request data like this to see whether the image field is empty and then unsetting the ['Image'] array, but that doesn't seem to work.

public function add() {
    if ($this->request->is('post')) {
            $this->Post->create();
            if (empty($this->request->data['Image'][0]['image'])) {
                unset($this->request->data['Image']);           
            }

            if ($this->Post->saveAssociated($this->request->data)) {
                $this->Session->setFlash(__('The post has been saved'), 'flash/success');
                $this->redirect(array('action' => 'view', $this->Post->id));
        } else {
            $this->Session->setFlash(__('The post could not be saved. Please, try again.'), 'flash/error');
        }
    }
}
1
Debugger::dump($this->request->data['Image']) revealed that the arrays for image uploads are different from normal fields. This code worked: if (empty($this->request->data['Image']['0']['image']['name'])) {unset($this->request->data['Image']);}caitlin

1 Answers

1
votes

This may work for you-

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

            foreach($this->request->data['Image'] as $key => $value){
                if(empty($value['image'])){
                    unset($this->request->data['Image'][$key]);
                }
            }   
            $this->Post->create();

            if ($this->Post->saveAssociated($this->request->data)) {
                $this->Session->setFlash(__('The post has been saved'), 'flash/success');
                $this->redirect(array('action' => 'view', $this->Post->id));
        } else {
            $this->Session->setFlash(__('The post could not be saved. Please, try again.'), 'flash/error');
        }
    }
}