0

I have an issue where the images I'm trying to save in a backend form aren't being populated in the database properly..

My Form.php

<?php

class FactoryX_Blog_Block_Manage_Blog_Edit_Form extends 
Mage_Adminhtml_Block_Widget_Form
{
    protected function _prepareForm()
    {
        $form = new Varien_Data_Form(
            array(
                 'id'     => 'edit_form',
                 'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
                 'method' => 'post',
                 'enctype'  => 'multipart/form-data'
            )
        );

        $form->setUseContainer(true);
        $this->setForm($form);
        return parent::_prepareForm();
    }
}

The field in /Edit/Form.php

$fieldset->addField('main_image', 'image', array(
      'label'     => Mage::helper('blog')->__('Upload a Main Image'),
      'required'  => true,
      'name'      => 'main_image',
    ));

Controller in save action:

if(isset($_FILES['main_image']['name']) and 
(file_exists($_FILES['main_image']['tmp_name']))){
        try {
            $uploader = new Varien_File_Uploader('main_image');
            $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); 
            $uploader->setAllowRenameFiles(false);
            $uploader->setFilesDispersion(false);

            $path = Mage::getBaseDir('media') . DS . "/blog" ;

            $uploader->save($path, $_FILES['main_image']['name']);

            $data['main_image'] = $_FILES['main_image']['name'];
      }catch(Exception $e) {

      }
    }
    else {      
        if(isset($data['main_image']['delete']) && $data['main_image']['delete'] == 1)
            $data['image_main'] = '';
        else
            unset($data['main_image']);
    }

The images are saving into the media folder how I'd like them to, but the main_image field in my database is showing up as "Array". The main image field is type Varchar(255).

enter image description here

I would like the path of the image to be saved to the database instead.

1

Actually it's just PHP nature. The $_FILE['field_name']['name'] is an array, not string in most cases. You can modify Controller to the following:

foreach($_FILES['main_image']['name'] as $filename)   
    $uploader->save($path, $filename);

Ref:

  • I found out my problem was that the form was being saved again after I'd already saved it with the correct data, over writing my changes. But you couldn't have gotten that from the code I provided, so I'm marking you the correct answer. – Jack Perry Jan 10 '18 at 23:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.