18

I create a new widget and one of the parameters is a picture chooser, I just use this code. Everything looks well. I can open media folder and choose the picture I want to use. When I choose the picture, the picture field on the form is filled with this value:

http://local.magento.com/admin/cms/wysiwyg/directive/___directive/e3ttZWRpYSB1cmw9Ind5c2l3eWcvcHVycGxlLmpwZyJ9fQ,,/key/4c150d984998702b74709bb8f05820aff2f85a968d47e50f9638b7d2a7b1ced3/

But when I save the form widget data, the picture field has this value: {{media url=

nothing more. How can I solve this?

2
  • 2
    The problem was on the configuration. On Configuration > General > Content Management, "Use Static URLs for Media Content in WYSIWYG for Catalog" It should be "yes"
    – mvistas
    Commented May 23, 2016 at 10:32
  • 2
    the problem with this approache is that you will run into problems moving from one env to another as the hardcoded image won't work Commented May 24, 2016 at 16:21

5 Answers 5

1

If you want to upload an image then why don't you use image selection button.?
If you like the editor then use it.But it is not a proper way to upload an image using an editor.You can use the button instead. If you don't know how to do it. Let me explain.

Here is my code. The below code is written in block file which creates a button.

$fieldset->addField(
        'image',
        'file',
        [
            'name' => 'image',
            'label' => __('Image'),
            'title' => __('Image'),
        ]
    );

Image is the database field name. In your case it's wysiwyg editor.I don't know the exact but once check in your database.

The below code is used to save the image in your table. Now put this code into your Controller.

<?php
namespace Vendor\Module\Controller\Adminhtml\Slider;

use Magento\Framework\App\Filesystem\DirectoryList;

class Save extends \Magento\Backend\App\Action

{

protected $_mediaDirectory;
protected $_fileUploaderFactory;

public function __construct(
    \Magento\Backend\App\Action\Context $context,        
    \Magento\Framework\Filesystem $filesystem,
    \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory
) 
{
    $this->_mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
    $this->_fileUploaderFactory = $fileUploaderFactory;
    parent::__construct($context);
}

public function execute()
{
    /*For Image Upload*/

    /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
    $resultRedirect = $this->resultRedirectFactory->create();

    try{
        $target = $this->_mediaDirectory->getAbsolutePath('imagefolder/');

        $targetOne = "imagefolder/";
        /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */
        $uploader = $this->_fileUploaderFactory->create(['fileId' => 'image']);
        /** Allowed extension types */
        $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png', 'zip', 'doc']);
        /** rename file name if already exists */
        $uploader->setAllowRenameFiles(true);
        /** upload file in folder "mycustomfolder" */
        $result = $uploader->save($target);
        /*If file found then display message*/
        if ($result['file']) 
        {
            $this->messageManager->addSuccess(__('File has been successfully uploaded')); 
        }
    }
    catch (Exception $e) 
    {
        $this->messageManager->addError($e->getMessage());
    }
    /*For Image Upload Finished*/ 

    $data = $this->getRequest()->getPostValue();

    $data['image'] = $targetOne.$result['file'];

    if (!$data) {
        $this->_redirect('*/*/filenaem');
        return;
    }
    try {

        $rowData = $this->_objectManager->create('Vendor\Module\Model\Slider');

        $rowData->setData($data);

        if (isset($data['id'])) 
        {
            $rowData->setEntityId($data['id']);
        }
        $rowData->save();
        $this->messageManager->addSuccess(__('Row data has been successfully saved.'));
    } 
    catch (Exception $e) 
    {
        $this->messageManager->addError(__($e->getMessage()));
    }
    $this->_redirect('*/*/index');

    return $this->resultRedirectFactory->create()->setPath(
        '*/*/upload', ['_secure'=>$this->getRequest()->isSecure()]
    );
}

/**
 * Check Category Map permission.
 *
 * @return bool
 */
protected function _isAllowed()
{
    return $this->_authorization->isAllowed('Vendor_Module::Module_list');
}

}

After that you want to called it in phtml for the result..so bellow code write in phtml file.
Here is code.

    $collection = $block->getCollectionFor();
    $_objectManager = \Magento\Framework\App\ObjectManager::getInstance(); //instance of\Magento\Framework\App\ObjectManager
    $storeManager = $_objectManager->get('Magento\Store\Model\StoreManagerInterface'); 
    $currentStore = $storeManager->getStore();
//Base URL for saving image into database.
    $mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

getCollectionFor() is write in my block.so according to that, you should apply as your block file.
I hope this is helpful to you. If you have any query let me know.

1
  • I called a result in phtml file using object manager.it will not a proper way but i don't want to write a more code here.so that's why i use it.if you want to use factory method then it will fine. Commented Aug 11, 2017 at 9:49
0

I have checked the code and found that the code to getting the image URL from the directory is not included. You have to work on it to solve this problem. The code to include the image URL is missing.

0

Looks like this is a known issue in Magento 2.1. Here is a link to their github for further info on the topic. https://github.com/magento/magento2/issues/6138 It appears there might be a few different fixes to try.

0

You can review last commit and create path for it on github and try to apply it https://github.com/magento/magento2/commit/ba6612462c260da7cc534b6365623993a6fe4311

0

By using jquery, we can save the image to a folder.

In script, write this code

<script>
    function file_up(id)
    {
        var up_id = 'uploadfiles'+id;
        var upremv_id = 'upload'+id;
        var files = document.getElementById(up_id).files;
        for (var i = 0; i < files.length; i++)
        {
            uploadFile(files[i],up_id,upremv_id);
        }
    }
    function uploadFile(file,up_id,upremv_id){
        var url = "<?php echo $baseurl ?>helloworld/index/upload";
        var xhr = new XMLHttpRequest();
        var fd = new FormData();
        xhr.open("POST", url, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                jQuery('#imgna'+up_id).val(xhr.responseText);
                console.log(xhr.responseText); // handle response.
                jQuery('#'+up_id).remove();
                jQuery('#'+upremv_id).remove();
                var img_va = '<img class="image" src="<?php echo $mediaUrl.'custom/'?>'+xhr.responseText+'">';
                jQuery('#pre'+up_id).html(img_va);
            }
        };
        fd.append('uploaded_file', file);

</script>

Then, in your custom controller:

Class Upload extends \Magento\Framework\App\Action\Action {

public function __construct(\Magento\Framework\App\Action\Context $context)
{
    parent::__construct($context);
}

public function execute()
{
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

    $fileSystem = $objectManager->create('\Magento\Framework\Filesystem');
    $mediaPath = $fileSystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath();
    $media = $mediaPath . 'custom/';

    //  exit;


    $file_name = rand() . $_FILES['uploaded_file']['name'];
    $file_size = $_FILES['uploaded_file']['size'];
    $file_tmp = $_FILES['uploaded_file']['tmp_name'];
    $file_type = $_FILES['uploaded_file']['type'];

    if (move_uploaded_file($file_tmp, $media . $file_name)) {
        echo $file_name;
    } else {
        echo "File was not uploaded";
    }
}

}

please refer How to save a image upload to a folder in magento2?

And by using observer, you can get the value of the image in post..In the input field tag use data-form-part="product_form".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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