Images in Magento widgets - magento

I am developing a site for a fashion client in Magento Community version 1.4.2 and as part of this project I need to have some customized home page promotion blocks to feature specific products or categories of products. For this I thought I would write my own widget and have made pretty good progress in this with the exception of how to deal with images. I need to include an image as part of the promotion. In my widget definition file I included the following parameter
<image>
<label>Image</label>
<description>Promotion image</description>
<visible>1</visible>
<type>image</type>
</image>
This seemed at first to work fine and when creating/editing a widget in the admin back end a file upload field is included in the widget options however on saving the form the image does not appear to be uploaded, or its details retained in the database. Does anyone else have experience of using images in widgets and what I may be doing wrong?

There are a couple reason why it doesn't save/upload the image:
The form enctype needs to be "multipart/form-data" for a file upload to work
Even if you change the form enctype to "multipart/form-data" you will notice if you monitor the requests that it gets POST'ed as "application/x-www-form-urlencoded" this is because it is done through ajax and ajax by itself can't process a file upload, you need to process them separately.
I have successfully implemented a "Insert Image" button which initialises the Media Library dialogue where you can browse your server for images and/or upload images.
Once the user clicks "Insert File" it inserts the full image url into a textbox in the widget so it's passed along like a normal field to your template.
This is how I achieved it:
In your widget.xml specify a new node:
<image translate="label">
<label>Image</label>
<visible>1</visible>
<required>1</required>
<type>label</type>
<helper_block>
<type>widgets/cms_wysiwyg_images_chooser</type>
<data>
<button translate="open">
<open>Insert Image...</open>
</button>
</data>
</helper_block>
</image>
The helper block type <type>widgets/cms_wysiwyg_images_chooser</type> is a custom class, so you can change it to anything you want as long as you create the class/files correctly.
<?php
class Stackoverflow_Widgets_Block_Cms_Wysiwyg_Images_Chooser extends Mage_Adminhtml_Block_Template
{
public function prepareElementHtml(Varien_Data_Form_Element_Abstract $element)
{
$config = $this->getConfig();
$chooseButton = $this->getLayout()->createBlock('adminhtml/widget_button')
->setType('button')
->setClass('scalable btn-chooser')
->setLabel($config['button']['open'])
->setOnclick('MediabrowserUtility.openDialog(\''.$this->getUrl('*/cms_wysiwyg_images/index', array('target_element_id' => $element->getName())).'\')')
->setDisabled($element->getReadonly());
$text = new Varien_Data_Form_Element_Text();
$text->setForm($element->getForm())
->setId($element->getName())
->setName($element->getName())
->setClass('widget-option input-text');
if ($element->getRequired()) {
$text->addClass('required-entry');
}
if ($element->getValue()) {
$text->setValue($element->getValue());
}
$element->setData('after_element_html', $text->getElementHtml().$chooseButton->toHtml());
return $element;
}
}
?>
And that is it! You should now have a new field in your widget options called "Image" with a textbox and a button in which you can insert the url to an image on your server and display it from your template.
A quick explanation of how it works:
A button is created that has an onclick function that calls the Media Library dialogue by calling MediabrowserUtility.openDialog() which along is passed the parameter target_element_id which tells media library what element to set the value in once they user clicks "Insert File" so we simply pass along the id of our textbox in the widget for it to receive the url of the image that the user selected.
Hope this helps someone as I couldn't find any resources out there that explained how to do it so I spent quite a while digging through Magento to work it all out :)
What I would like to do in the future is have it so it displays the image after you select it in the widget, and it stores the url in a hidden field, but having an onchange bind is not fired when the value is set to the element from js/mage/adminhtml/browser.js in the insert function, so without changing the core files it is a lot harder to do. I thought about playing around with when the form gets focus again after the Media Library closes or a timer (pretty dodgey but would work), but I have other things to move on to and may come back to it later!
UPDATE:
The URL's that the Media Library generates are like so:
http://www.yourwebsite.com/index.php/admin/cms_wysiwyg/directive/___directive/e3ttZWRpYSB1cmw9Ind5c2l3eWcvd2lkZ2V0cy9iYW5uZXIvaG9tZXBhZ2UvZm9yZWdyb3VuZC9maXNoLXRhbmsucG5nIn19/key/e8167e3884e40b97d8985e7b84e7cbc7875f134e5f7e5946c9c2a482d0279762/
Which are a cached image, and only work if the user is an admin. Stupid? Yes. If you insert the same image in to a CMS page when the html is generated for output it converts it to the original url on the server accessible via /media/wysiwyg/path/to/file/photo.jpg. We need the original url to show to the user, so what we can do is hook into the function that generates the widget html (when you click "Insert Widget") and look for /admin/cms_wysiwyg/directive/___directive/ and replace it with the original URL to the image as the CMS page does.
In your config.xml for your custom widgets:
<global>
<models>
<widget>
<rewrite>
<widget>Stackoverflow_Widgets_Model_Widget</widget>
</rewrite>
</widget>
</models>
</global>
Then create the model Widget code\local\Stackoverflow\Widgets\Model\Widget.php:
<?php
class Stackoverflow_Widgets_Model_Widget extends Mage_Widget_Model_Widget
{
public function getWidgetDeclaration($type, $params = array(), $asIs = true)
{
foreach($params as $k => $v){
if(strpos($v,'/admin/cms_wysiwyg/directive/___directive/') !== false){
$parts = explode('/',parse_url($v, PHP_URL_PATH));
$key = array_search('___directive', $parts);
if($key !== false){
$directive = $parts[$key+1];
$src = Mage::getModel('core/email_template_filter')->filter(Mage::helper('core')->urlDecode($directive));
if(!empty($src)){
$params[$k] = parse_url($src, PHP_URL_PATH);
}
}
}
}
return parent::getWidgetDeclaration($type, $params, $asIs);
}
}
Which overrides the getWidgetDeclaration function which is called every time a the widget output is produced for a textarea/wysiwyg and looks through all the parameters and if it finds an image that is linked to the admin cache it will find out the original image and overwrite the variable in the array and call the original function with the parameters.
If the cached image is not found the function will work as normal.
UPDATE: 13/09/2012
As Jonathan Day pointed out you have to overwrite Mage_Widget_Model_Widget_Instance also if you want it to work in a Widget Instance.
I haven't had the need to add an image to a widget through a Widget Instance until now and was confused why my function didn't work, until I investigated and realised the "popup" widget instances use Mage_Widget_Model_Widget and the widget instances that are used on a Widget options tab (no popup) are Mage_Widget_Model_Widget_Instance and do not extend Mage_Widget_Model_Widget so do not inherit the functionality.
To add the functionality to Mage_Widget_Model_Widget_Instance simply add the line <widget_instance>Petbarn_Widgets_Model_Widget_Instance</widget_instance> to your config.xml so it will look like:
<global>
<models>
<widget>
<rewrite>
<widget>Stackoverflow_Widgets_Model_Widget</widget>
<widget_instance>Stackoverflow_Widgets_Model_Widget_Instance</widget_instance>
</rewrite>
</widget>
</models>
</global>
Then create the model Instance code\local\Stackoverflow\Widgets\Model\Widget\Instance.php:
<?php
class Petbarn_Widgets_Model_Widget_Instance extends Mage_Widget_Model_Widget_Instance
{
protected function _beforeSave()
{
if (is_array($this->getData('widget_parameters'))) {
$params = $this->getData('widget_parameters');
foreach($params as $k => $v){
if(strpos($v,'/cms_wysiwyg/directive/___directive/') !== false){
$parts = explode('/',parse_url($v, PHP_URL_PATH));
$key = array_search('___directive', $parts);
if($key !== false){
$directive = $parts[$key+1];
$src = Mage::getModel('core/email_template_filter')->filter(Mage::helper('core')->urlDecode($directive));
if(!empty($src)){
$params[$k] = parse_url($src, PHP_URL_PATH);
}
}
}
}
$this->setData('widget_parameters', $params);
}
return parent::_beforeSave();
}
}
This time we are modifying the widget_parameters data at the start of the _beforeSave() function so it fixes up the url before it saves it.
You also have to ensure the /js/mage/adminhtml/browser.js javascript file is included (in my case it wasn't) to get the MediabrowserUtility functionality.
To ensure it is included, the easiest way is to include it for all of admin (didn't spend much time targeting it better).
Create a local.xml for adminhtml layouts (if you don't already have one): app\design\adminhtml\default\default\layout\local.xml
<?xml version="1.0"?>
<layout version="0.1.0">
<default>
<reference name="head">
<action method="addJs"><script>mage/adminhtml/browser.js</script></action>
</reference>
</default>
</layout>
This will make Magento include js/mage/adminhtml/browser.js on every page of admin so MediabrowserUtility will always be available.
NOTE: I'm using Magento Enterprise 1.11.2.0 so I'm not sure how it behaves on other versions.

I solved this use case by creating a custom field type for widgets:
<image>
<label>Image</label>
<description>Promotion image</description>
<visible>1</visible>
<type>widgetimagechooser/chooser</type>
</image>
I implemented a block Aijko_WidgetImageChooser_Block_Chooser that triggers the standard Magento image chooser element.
To solve the problem with the non clear url to the image file I implemented a custom controller Aijko_WidgetImageChooser_Adminhtml_Cms_Wysiwyg_Images_ChooserController that handles the return value from the Magento standard image chooser.
The value is added to a textbox in the widget. This relative url to the image then can be used to show the image in the frontend.
Feel free to try the extension available on Github or install directly using Magento Connect.

Thx krus for you answer! I've found a nicer way to solve the problem with the cached image URLs. I even had to do this, because your solution overwriting the Widget Model didn't work with Magento 1.7.0.2.
So what I have done is adding a new GET parameter use_file_url to the URL used for the Chooser Block:
$url = $this->getUrl(
'*/cms_wysiwyg_images/index',
array(
'target_element_id' => $element->getName(),
'use_file_url' => 1
)
);
This passes the GET parameter to the media browser. The next step is to pass this parameter to the onInsertAction of the Mage_Adminhtml_Cms_Wysiwyg_ImagesController. Do do this, you have to override the getOnInsertUrl() function of the Mage_Adminhtml_Block_Cms_Wysiwyg_Images_Content Block:
public function getOnInsertUrl()
{
$useFileUrl = (int)$this->getRequest()->getParam('use_file_url', 0);
return $this->getUrl('*/*/onInsert', array('use_file_url' => $useFileUrl));
}
Then you need to handle the new parameter in the Mage_Adminhtml_Cms_Wysiwyg_ImagesController controller:
public function onInsertAction()
{
$useFileUrl = (int)$this->getRequest()->getParam('use_file_url', 0) == 1 ? true : false;
$helper = Mage::helper('cms/wysiwyg_images');
$storeId = $this->getRequest()->getParam('store');
$filename = $this->getRequest()->getParam('filename');
$filename = $helper->idDecode($filename);
$asIs = $this->getRequest()->getParam('as_is');
Mage::helper('catalog')->setStoreId($storeId);
$helper->setStoreId($storeId);
if ($useFileUrl == false) {
$image = $helper->getImageHtmlDeclaration($filename, $asIs);
} else {
$image = $helper->getImageMediaUrl($filename);
}
$this->getResponse()->setBody($image);
}
The last step is to override the Mage_Cms_Helper_Wysiwyg_Images helper and add the getImageMediaUrl() function:
public function getImageMediaUrl($filename)
{
return $this->getCurrentUrl() . $filename;
}
I think this is a quite pretty approach, even though you have to ovverride 4 classes. But passing a GET parameter seems to be more future safe than parsing the cached URL.

There is no file uploads for widgets. To solve that problem you may use magento media browser and select image like for wysiwyg editor, but there is other issue, media browser do not return clear url of image.

As of Magento version 1.9.2.0 you will also need to add the following to your adminhtml layout file:
lib/flex.js
lib/FABridge.js
mage/adminhtml/flexuploader.js

Magento's Image custom attributes normally does not come to extension tab and you will have to go to Catalog>Product> Images to assign this attribute. But with some custom coding you can achieve this.

Related

Joomla MVC Module delete model

I'm a newbie on Joomla developing and I'm trying to fix an old administration module made by 'someone before me'. Module's been developed using MVC Components, it has several CRUDs and I'm stucked at deleting an item. The template view adds the toolbar icon like this:
JToolbarHelper::deleteList('', 'paises.delete', JTOOLBAR_DELETE);
It also has at the list controller (DistribuidoresControllerPaises), the getModel function:
public function getModel($name = 'Pais', $prefix = 'DistribuidoresModel', $config = array('ignore_request' => true))
{
$model = parent::getModel($name, $prefix, $config);
return $model;
}
The model class:
class DistribuidoresModelPais extends JModelAdmin
When selecting an item on the list, and clicking the trash button an empty page opens with this ending:
administrator/index.php?option=com_distribuidores&view=pais
If I come back to grid, the item still remains.
Any suggestion?
Thanks in advance
You can debug this by enabling debugging from Joomla configuration or you can try to to check with exit with in "delete" function of "paises" controller and can check you get item ids in post request or not.
Also you are using view "pais" also using model "pais" then why you are using "paises" controller for delete function, you should use "pais" controller to delete.
Also provide delete function which you are using to delete items, it may contain some issue.

Magento, checkout/cart block not loading in ajax extension

I'm programming an ajax extension to Magento and I'm having trouble when I try to make checkout/cart work with it.
I want to reload the entire block, including the item and also the cart totals after a change in any product in the cart.
I've modified the layout as many sites said and I can't get the checkout/cart block render well.
My two solutions were:
1° Tryed to update the layout via an xml file, and I get a false in $block_cart.
I've a class
Mati_Ajax_CartController extends Mage_Checkout_CartController
{
...
public function updateShoppingCartAction()
{
...
$block_cart = $this->getLayout()->getBlock('checkout/cart');
...
}
}
and a xml file (which I'm sure i'ts being loaded beacause the js pointed there is loading)
<checkout_cart_updateshoppingcart>
<update handle="checkout_cart_index" />
</checkout_cart_updateshoppingcart>
2° Tryed to create the block
public function updateShoppingCartAction()
{
...
$block_cart = $this->getLayout()->getBlockSingleton('checkout/cart')->setTemplate("checkout/cart.phtml")->toHtml();
...
}
And here I get the block, but when the template executes $this->getChildHtml('totals');
It gets a false anwer, so the webpage has some differences with the previousone
Does anybody knows how to make this work ?
In your first attempt just append ->toHtml();
Alternatively you could have included that as a command in the xml output="toHtml"
Check how the checkout/onepage/review functions if you are looking for advice.
There they access the response object and then set the body of the response to the html variable, in your case $block_cart
The key was in the xml file
<ajax_cart_updateshoppingcart>
<update handle="checkout_cart_index" />
</ajax_cart_updateshoppingcart>

Magento custom admin menu dropdown

I need a little help: I’m developing an admin module, where I create two menus. I want to set the links in the config.xml, but I do not get it. My config.xml is as follows.
<children>
<menuitem1 module="PrecosMargens">
<title>Actualizar Preços Custos</title>
<action>PrecosMargens/example</action>
</menuitem1>
<menuitem2 module="PrecosMargens">
<title>Actualizar Preços vendas</title>
<action>PrecosMargens/example2</action>
</menuitem2>
</children>
But with the MenuItem2 get error 404. Can you help me how to solve this? In the controller file I have just as follows:
class lbonus_PrecosMargens_ExampleController extends Mage_Adminhtml_Controller_Action
{
public function indexAction()
{
// "Fetch" display
$this->loadLayout();
// "Inject" into display
// THe below example will not actualy show anything since the core/template is empty
$this->_addContent($this->getLayout()->createBlock('core/template')
//defino o template
->setTemplate('PrecosMargens/list.phtml'));
// "Output" display
$this->renderLayout();
}
}
I wanted to do is to have two different layouts, one layout to another to link1 and link2
The second action (PrecosMargens/example2) is trying to find a method indexAction() in a separate class lbonus_PrecosMargens_Example2Controller. You need two controllers for the two actions.
You could have one controller instead. Change the actions to PrecosMargens/example/custos and PrecosMargens/example/vendas which cause the matching methods custosAction() and vendasAction() to be used.
Addendum
The action (which becomes part of the URL) is in the form "router/controller/action". The router is matched to your module by the <routers> section of that module's config.xml file.
The controller becomes the class name with "Controller" appended to it, so in this case the "example" becomes your module's "ExampleController".
The action part leads to that class' method with "Action" appended to it. You can see "custos" becomes the custosAction() method.
When one of these parts is missing it defaults to "index", so a default controller is "IndexController" and a default action is "indexAction". If you just used "PrecosMargens" it would be used as if it were "PrecosMargens/index/index".

Is it good practice to add own file in lib/Varien/Data/Form/Element folder

I need to create module in Magento which will have few database tables. One of the function of the module is adding multiple images.
For example while being on the "Add new item" or "Edit item" page in the admin, from the left side I have tabs, one of them is "Item Images". When being clicked I want the content of this tab to be my own custom one.
After digging into the code, found out that the way it renders this content, Magento is using one of the Varien_Data_Form_Element classes for each element in the full form. I want to add my own class here that will render form elements the way I want.
Is this a good practice to do so, or there is some other more elegant way of adding own content in the admin forms?
EDIT: I must add that none of the existing classes is helping my problem.
SOLUTION EDIT:
I have a controller in my custom module that is in Mypackage/Mymodule/controllers/Adminhtml/Item.php. In the editAction() method which I am using for adding and creating new items, I am creating 2 blocks, one for the form and one left for the tabs:
$this->_addContent($this->getLayout()->createBlock('item/adminhtml_edit'))
->_addLeft($this->getLayout()->createBlock('item/adminhtml_edit_tabs'));
$this->renderLayout();
The Block/Adminhtml/Edit/Tabs.php block is creating 2 tabs on the left: General Info and Item Images, each of them are rendering different content on the right side using Block classes.
protected function _beforeToHtml()
{
$this->addTab('item_info', array(
'label' => Mage::helper('mymodule')->__('Item Info'),
'content'=> $this->getLayout()->createBlock('item/adminhtml_edit_tab_form')->toHtml(),
));
$this->addTab('item_images', array(
'label' => Mage::helper('mymodule')->__('Item Images'),
'active' => ( $this->getRequest()->getParam('tab') == 'item_images' ) ? true : false,
'content' => $this->getLayout()->createBlock('item/adminhtml_images')->toHtml(),
));
return parent::_beforeToHtml();
}
I wanted the tab item_images to render my own form elements and values, not the default varien form elements.
class Mypackage_Mymodule_Block_Adminhtml_Images extends Mage_Core_Block_Template
{
public function __construct()
{
parent::__construct();
$this->setTemplate('item/images.phtml'); //This is in adminhtml design
}
public function getPostId()
{
return $this->getRequest()->getParam('id');
}
public function getExistingImages()
{
return Mage::getModel('mymodule/item')->getImages($this->getPostId());
}
}
Then in the template app/design/adminhtml/default/default/template/item/images.phtml you can use these values:
//You can add your own custom form fields here and all of them will be included in the form
foreach($this->getExistingImages() as $_img):
//Do something with each image
endforeach;
//You can add your own custom form fields here and all of them will be included in the form
No, it's not. You should never edit or add to files that provided by a vendor. If you absolutely must replace a class file you should use the local code pool. For example, if you wanted to change the behavior of a text field,
lib/Varien/Data/Form/Element/Text.php
You should place a file in the local or community code pool
app/code/local/Varient/Data/Form/Element/Text.php
However, doing the replaces the class, and it becomes your responsibility to maintain compatibility with future versions. That means if Magento Inc. changes lib/Varien/Data/Form/Element/Text.php, you need to update your version to be compatible.
Based on what you said I'd look into creating a class rewrite for the Block class that renders the form.

The url from an image via custom field (wordpress)

Am not even sure if this can be done but...
Ive added a feed from my forums to wordpress it works great but I need it to auto add the url of the image in a custom field from the images in the post (feed) first image would be fine as its only ahve a slider
Is there any way to do this?
Details
Ok I think I did not explain this very well so made a few screen shots
This is my slider at the minute with my
This is an imported post one other feed I was using
On this image you can see the custom field (which I have to fill in after every import)
Adding the image url into the custom field
and finaly a view of the slider working
This is what am trying to do (auto) so my feed from my booru / forums / 2 other of my sites and (2 other peoples) sites make my home page on a new site
Hope this explain it alot more
This uses the external Simple Pie library built into WordPress to fetch the feed, get the image url and create a new post for each item and save the image url as a custom field.
To activate the process we have to hook into wp_cron. The code below does it daily but it would probably be better to do it weekly to prevent overlap. Some overlap will probably occur so this still needs a way to check if we have already imported the image
First we need a function to save the custom field after the post has been created. This section comes from another answer I found on WordPress Answers.
Edit:
This needs to be wrapped in a plugin to schedule the cron event and the cron event was missing the action to make it fire.
Edit:
Final version below tested and it works but the feed the OP is getting is using relative url's so the domain name needs to be added somewhere in the output code.
<?php
/*
Plugin Name: Fetch The Feed Image
Version: 0.1
Plugin URI: http://c3mdigital.com
Description: Sample plugin code to fetch feed image from rss and save it in a post
Author: Chris Olbekson
Author URI: http://c3mdigital.com
License: Unlicense For more information, please refer to <http://unlicense.org/>
*/
//Register the cron event on plugin activation and remove it on deactivation
register_activation_hook(__FILE__, 'c3m_activation_hook');
register_deactivation_hook(__FILE__, 'c3m_deactivation_hook');
add_action( 'c3m_scheduled_event', 'create_rss_feed_image_post');
function c3m_activation_hook() {
wp_schedule_event(time(), 'weekly', 'c3m_scheduled_event');
}
function c3m_deactivation_hook() {
wp_clear_scheduled_hook('c3m_scheduled_event');
}
function create_rss_feed_image_post() {
if(function_exists('fetch_feed')) {
include_once(ABSPATH . WPINC . '/feed.php'); // include the required file
$feed = fetch_feed('http://animelon.com/booru/rss/images'); // specify the source feed
}
foreach ($feed->get_items() as $item) :
// global $user_ID;
$new_post = array(
'post_title' => $item->get_title(),
'post_status' => 'published',
'post_date' => date('Y-m-d H:i:s'),
//'post_author' => $user_ID,
'post_type' => 'post',
'post_category' => array(0)
);
$post_id = wp_insert_post($new_post);
if ($enclosure = $item->get_enclosure() )
update_post_meta( $post_id, 'feed_image_url', $enclosure->get_link() );
endforeach;
}

Resources