3

I followed this tutorial to add a custom field to CMS pages: https://www.atwix.com/magento/adding-custom-attribute-to-a-cms-page/

And it works very well. But I want an image uploader instead of a text field. How do I do this?


This is my Observer:

class test_CmsBanner_Model_Observer
{
    public function cmsField($observer)
    {
        //get CMS model with data
        $model = Mage::registry('cms_page');
        //get form instance
        $form = $observer->getForm();
        //create new custom fieldset 'test_content_fieldset'
        $fieldset = $form->addFieldset('test_content_fieldset', array('legend'=>Mage::helper('cms')->__('Custom'),'class'=>'fieldset-wide'));
        //add new field
        $fieldset->addField('content_custom', 'text', array(
            'name'      => 'content_custom',
            'label'     => Mage::helper('cms')->__('Banner Image'),
            'title'     => Mage::helper('cms')->__('Banner Image'),
            'disabled'  => false,
            //set field value
            'value'     => $model->getContentCustom()
        ));

    }
}

And I saw this line:

$fieldset->addField('content_custom', 'text', array(

It says text at the moment. What do I change it to, to create an image upload field?

1

Try this:

$fieldset->addField('content_custom', 'image', array(

You can see all availabe form elements types inside the directory lib/Varien/Data/Form/Element/Image.php. See all availabe form element types in below screen-shot.

enter image description here

But I believe this is not enough. Since your form holds a file input, it is required to hold your form following attribute enctype="mutltipart/form-data". Without this attribute in your form, it wont save your file inputs.

So For this, I believe you need to do this in your observer.

$form = $observer->getForm();
$form->setEnctype("mutltipart/form-data");
  • Well, simply changing the 'text' to 'image' worked perfectly, thanks alot! – Maarten Wolfsen Nov 1 '16 at 13:59
1

OK, so in order to make it work in my case, here what I needed to do :

First, we need to add enctype="multipart/form-data" to the related form, but for me, the instruction below...

$form->setEnctype("multipart/form-data"); // care, there was a typo in the previous post

... didn't do the job in the events below :

adminhtml_cms_page_edit_tab_main_prepare_form adminhtml_cms_page_edit_tab_content_prepare_form adminhtml_cms_page_edit_tab_design_prepare_form adminhtml_cms_page_edit_tab_meta_prepare_form

So I had to add another event observer on "adminhtml_block_html_before" :

<adminhtml_block_html_before>
    <observers>
        <Domain_Module_Model_Observer>
            <type>singleton</type>
            <class>Domain_Module_Model_Observer</class>
            <method>addFormEnctype</method>
        </Domain_Module_Model_Observer>
    </observers>
</adminhtml_block_html_before>

Here is the related method "addFormEnctype" :

// Observer plugged on "adminhtml_block_html_before"
public function addFormEnctype($observer) {
    try {
        $block = $observer->getEvent()->getBlock();
        if ($block instanceof Mage_Adminhtml_Block_Cms_Page_Edit_Form){
            $form = $block->getForm();
            $form->setData('enctype', 'multipart/form-data');
            $form->setUseContainer(true);
        }
    }
    catch(Exception $e) {
        Mage::logException($e);
    }
}

Well, that's not very sexy, but as there is no dedicated event to do this, that was a simple way to do what i need. Another way would be to override the "Mage_Cms_Block_Adminhtml_Cms_Page_Edit_Form" to rewrite the form options.

So at this point, your form should have the enctype="multipart/form-data". Then, I had to handle images files. To do so, I needed a new observer listener / method. Here is the event :

<cms_page_prepare_save>
    <observers>
        <Domain_Module_Model_Observer>
            <type>singleton</type>
            <class>Domain_Module_Model_Observer</class>
            <method>savePage</method>
        </Domain_Module_Model_Observer>
    </observers>
</cms_page_prepare_save>

And here is the related method :

// Observer plugged on "cms_page_prepare_save"
public function savePage($observer) {
    try {
        // Initialisations
        $model = $observer->getEvent()->getPage();
        $request = $observer->getEvent()->getRequest();
        $data = $request->getPost();
        $media_dir = 'cms_page'.DS;
        $media_path = Mage::getBaseDir('media').DS.$media_dir;

        // Looping on images attributes
        $imagesAttributesNames = array('additional_img_a', 'additional_img_b', 'additional_img_c', 'additional_img_d', 'additional_img_e');
        foreach($imagesAttributesNames as $imageAttributeName) {
            $uploadedImage = $_FILES[$imageAttributeName];
            if (isset($uploadedImage['name']) && $uploadedImage['name'] != '') {
                // Upload the image
                $uploader = new Varien_File_Uploader($imageAttributeName);
                $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png', 'bmp'));
                $uploader->setAllowRenameFiles(false);
                $uploader->setFilesDispersion(false);
                $uploader->save($media_path, $uploadedImage['name']);
                // Adjusting model
                $model->setData($imageAttributeName, $media_dir.$uploadedImage['name']);
            } else {
                if($data[$imageAttributeName]['delete'] == 1) {
                    $data[$imageAttributeName] = '';
                    $model->setData($imageAttributeName, $data[$imageAttributeName]);
                } else {
                    unset($data[$imageAttributeName]);
                    $model->setData($imageAttributeName, implode($request->getPost($imageAttributeName)));
                }
            }
        }
    }
    catch(Exception $e) {
        Mage::logException($e);
    }
}

The last part could be simplified. In my case I had 5 image fields :

  • additional_img_a
  • additional_img_b
  • additional_img_c
  • additional_img_d
  • additional_img_e

So I made a loop. The method overall is quite pretty simple / obvious. You just control $_FILES, check what you have to, move files, and adjust data before it will be stored in database (path).

Hope that it could help someone :)

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.