Search code examples
cakephpcakephp-1.2

Uploading multiple pictures from the same form in CakePHP 1.2


I have a one-to-many relationship where one House can have many Pictures. The models that I have are "House" and "Picture". I am using CakePHP 1.2 and I can upload one picture successfully by using this:

echo $form->input('Picture.filename', array('type' => 'file', 'label' => __l('Image')));

In my houses_controller.php file, I have this code to save the picture and corresponding association with its house:

$this->House->Picture->save($this->data['Picture']);

But I need to save several pictures now. I read the documentation at https://book.cakephp.org/1.2/en/The-Manual/Core-Helpers/Form.html and based on that information, I am trying to use this:

echo $form->input('Picture.0.filename', array('type' => 'file', 'label' => __l('Image 1'));
echo $form->input('Picture.1.filename', array('type' => 'file', 'label' => __l('Image 2'));

Then my houses_controller.php file has this:

$this->House->Picture->saveAll($this->data['Picture']);

I see that one new record is saved in my pictures table, but I was expecting to see two new entries in my table because I should have added two pictures, not only one. Any ideas about why this may not be saving two pictures for me? Thank you.


Solution

  • Solution:

    $this->Deal->Picture->save($this->data['Picture'][0]);
    $this->Deal->Picture->save($this->data['Picture'][1]);
    

    Using $this->data['Picture'] was not sufficient because the array was returning multiple elements, so I had to reference each with the corresponding index such as $this->data['Picture'][0] for the first element, $this->data['Picture'][1] for the second one, etc.

    NOTE: It was not saving two records for me, even thought I was using save() twice. But that was another issue. You can read the answers at Save multiple times in Cakephp for the corresponding solution. Basically you need to use create() before you use save().