Admin Form Field Value Not Saving to Database – Magento Solution

adminformadminhtmlimage-previewmodel

This is what I'm trying to achieve as the end result by the way:-

Magento Image Upload Preview

I think I may have just realised why $this->getImageHtml($model->getImgMain()) returns nothing. Is this meant to be getting the value from the database? If so, there is no value stored in the database. So the image uploader is uploading the image but not saving the name in the database. I think I'm getting somewhere?

Edit

I can confirm, that the value as per above is returned empty because the image filename is not being saved to the database:-

        $fldUpload = $form->addFieldset('upload', array('legend'=> $hlp->__('Image Upload')));
        $fldUpload->addField('img_main', 'file', array(
        'label'     => $hlp->__('Image'),
        'name'      => 'img_main',
        'required'  => false,
        'after_element_html' => $this->getImageHtml($model->getImgMain()),
        )); 
        $fldUpload->addField('remove_img_main', 'checkbox', array(
            'label'     => $hlp->__('Remove Image'),
            'name'      => 'remove_img_main',
            'value'     => 1,
        ));

And I created the table in the database img_main and whilst the image uploads, the filename is not saved to the database…

Really stumped on this one, I know the image filename is being generated correctly, I know that the field name is the same as the table name in the database. I can't figure out why the image filename is not being saved in the database table.

Best Answer

You are missing the necessary bit to actually write the data to the model/table.

On line $data[$field] = $newName; it alters the $data array that is used to store values pair and later you should call $model->setData($data) and then you need to actually save with $model->save();

You could pass a single value to the $models table column with $model->setImgMain("text here");. Note the camelcazing. After saving you could call $model->getImageMain() to get the stored value.