onSave method for Editor Plugin in Joomla 3.6 - php

I try to create a plugin which will display some text after creation of article in the editor.
/editors/materialwords/materialwords.xml:
<?xml version="1.0" encoding="utf-8"?>
<extension version="3.1" type="plugin" group="editors">
<name>Editor Material Words Count Plugin</name>
<creationDate>December 2016</creationDate>
<author>Aleksandr Lapenko</author>
<authorEmail>lapenkoak#gmail.com</authorEmail>
<authorUrl>vk.com/web_rider</authorUrl>
<copyright>Copyright</copyright>
<license>GNU General Public License version 2 or later; see LICENSE.txt</license>
<version>1.0.0</version>
<description>Calculate articles words count</description>
<files>
<filename plugin="materialwords">materialwords.php</filename>
</files>
<config>
<fields name="params">
<fieldset name="basic">
<field name="displayCount" type="text"
label="Display Count"
description="Words display count"
required="true"
size="10"
class="inputbox" />
</fieldset>
</fields>
</config>
</extension>
/editors/materialwords/materialwords.php:
<?php
defined('_JEXEC') or die;
class PlgEditorMaterialwords extends JPlugin
{
public function onSave($id)
{
return 'alert("' . $id . '");';
}
}
I install plugin and enable it. But something wrong (nothing when I save article in editor).
Please, help.
Best regards, Aleksandr.

if you want a plugin before save or after save event
onExtensionBeforeSave
onExtensionAfterSave

Actually editors plugins are type of editors that you can use in joomla back office, if you go in system - configuration in back office, for default editor you'll can choose your plugin because it is an editors plugin.
If you want to perform some action after save an article you'll have to write a content plugin with method onContentAfterSave(). This method takes 3 arguments :
$context, in your case it should be com_content.article, so test it before soing anything else
$article, the instance of the article you are saving
$isNew, a boolean, true if it is a new article, false if it is an udpate
Plugin code
class PlgContentMaterialwords extends JPlugin {
public function onContentAfterSave($context, $article, $isNew){
if ($context != 'com_content.content'){
return true;
}
// do stuff
}
}
Plugin declaration
<?xml version="1.0" encoding="utf-8"?>
<extension version="3.1" type="plugin" group="content">
<name>Editor Material Words Count Plugin</name>
<creationDate>December 2016</creationDate>
<author>Aleksandr Lapenko</author>
<authorEmail>lapenkoak#gmail.com</authorEmail>
<authorUrl>vk.com/web_rider</authorUrl>
<copyright>Copyright</copyright>
<license>GNU General Public License version 2 or later; see LICENSE.txt</license>
<version>1.0.0</version>
<description>Calculate articles words count</description>
<files>
<filename plugin="materialwords">materialwords.php</filename>
</files>
<config>
<fields name="params">
<fieldset name="basic">
<field name="displayCount" type="text"
label="Display Count"
description="Words display count"
required="true"
size="10"
class="inputbox" />
</fieldset>
</fields>
</config>
</extension>
Plugin to override save in javascript
With previous method you can not add javascript in this page. If you want to do such you have to add a onBeforeRender method. When clicking on an admin button, javascript method Joomla.submitbutton is called, so you can override it (take care of saving it before so you can call it after your process).
class PlgContentMaterialwords extends JPlugin
{
public function onBeforeRender()
{
if ( JFactory::getApplication()->isAdmin() ){
$document = JFactory::getDocument();
$document->addScriptDeclaration('
var Myvar = {};
Myvar.submitbutton = Joomla.submitbutton;
Joomla.submitbutton = function(task) {
if ( task == "article.save" || task == "article.apply" || task == "article.save2new" ){
alert("foo");
}
Myvar.submitbutton(task);
}
');
}
}
}

Related

Joomla Component: View: Get values from field

I'm new to Joomla, especially to component development. Anyway, here's my question:
site\views\plaingallery\tmpl\default.xml
<?xml version="1.0" encoding="utf-8"?>
<metadata>
<layout title="COM_PLAINGALLERY_PLAINGALLERY_VIEW_DEFAULT_TITLE">
<message>
<![CDATA[COM_PLAINGALLERY_PLAINGALLERY_VIEW_DEFAULT_DESC]]>
</message>
</layout>
<fields name="request"
addfieldpath="/administrator/components/com_plaingallery/models/fields">
<fieldset name="request">
<field name="galleryFolder" type="folderlist" default="" recursive="true"
label="Select a folder" directory="images" filter="" exclude="" width="300"
hide_none="true" hide_default="true" stripext="" />
</fieldset>
</fields>
</metadata>
site\views\plaingallery\view.html.php
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla view library
jimport('joomla.application.component.view');
/**
* HTML View class for the PlainGallery Component
*/
class PlainGalleryViewPlainGallery extends JViewLegacy
{
// Overwriting JView display method
function display($tpl = null)
{
// Assign data to the view
$this->msg = 'I am new to Joomla';
// Display the view
parent::display($tpl);
}
}
My question is: How do I access the value from the field[name="galleryFolder"] the user provided in the menu configuration?
Thanks for your help! I really do appreciate it.
This parameter is located in the query variable of the menu item.
You can try this for example:
$app = JFactory::getApplication();
/* Default Page fallback*/
$active = $app->getMenu()->getActive();
if (NULL == $active) {
$active = $app->getMenu()->getDefault();
}
if ( isset($active->query['galleryFolder']) ) {
$galleryFolder = $active->query['galleryFolder'];
}

Magento Checkout, Trying to create a new module for free products

I'm triying to create a new module to bypass checkout process for free downloadable products. As I'm not a developer I need some help with xml files of module.
I've this folder structure:
app/etc/modules/Fe_Freecheckout.xml
app/code/local/Fe/Freecheckout/controllers/CheckoutController.php
app/code/local/Fe/Freecheckout/etc/config.xml
And these are the contents of files:
CheckoutController.php
<?php
public function purchaseAction() {
if (!Mage::getSingleton('customer/session')->isLoggedIn()) {
$this->_redirectUrl(Mage::getBaseUrl().'customer/account');
return;
}
$request = $this->getRequest();
$id = $request->getParam('id');
$product = Mage::getModel('catalog/product')
->load($id)
->setStoreId(Mage::app()->getStore()->getId());
if(!($product->getIsVirtual() && $product->getFinalPrice() == 0)){
Mage::getSingleton('checkout/session')->addError($this->__('Method only available for Free Downloadable Items'));
return $this;
}
$onepage = Mage::getSingleton('checkout/type_onepage');
/* #var $onepage Mage_Checkout_Model_Type_Onepage */
try{
$quote = $onepage->getQuote();
/* #var $quote Mage_Sales_Model_Quote */
$quote->addProduct($product);
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
$onepage->initCheckout();
$payment=array('method'=>'free');
$onepage->savePayment($payment);
$onepage->saveOrder();
$this->getResponse()->setRedirect('/downloadable/customer/products');
}
catch(Exception $e){
$result = $e->getMessage();
Mage::getSingleton('checkout/session')->addError($result);
}
}
?>
app/etc/modules/Fe_Freecheckout.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
<Fe_Freecheckout>
<!-- Whether our module is active: true or false -->
<active>true</active>
<!-- Which code pool to use: core, community or local -->
<codePool>local</codePool>
</Fe_Freecheckout>
</modules>
</config>
And this is app/code/local/Fe/Freecheckout/etc/config.xml
where i don't know how register my checkout controller:
<?xml version="1.0" encoding="UTF-8"?>
<!-- The root node for Magento module configuration -->
<config>
<!--
The module's node contains basic
information about each Magento module
-->
<modules>
<!--
This must exactly match the namespace and module's folder
names, with directory separators replaced by underscores
-->
<Fe_Freecheckout>
<!-- The version of our module, starting at 0.0.1 -->
<version>0.0.1</version>
</Fe_Freecheckout>
</modules>
</config>
Then in product/view.phtml I use the following code to checkout:
<?php if($_product->isVirtual() && $_product->getFinalPrice()==0) { ?>
<?php echo $this->__('Download and Install') ?>
<?php } ?>
I always get a Page not Found...Any directions, please?
Thank you.
I think you need to override onepagecontroller
<global>
<rewrite>
<Packag_modulename_checkout_onepagecontroller>
<from><![CDATA[#^/checkout/onepage/#]]></from> <!-- Mage_Checkout_OnepageController -->
<to>/modulename/checkout_onepage/</to> <!-- Package_ModuleName_Checkout_OnepageController -->
</Package_modulename_checkout_onepagecontroller>
</rewrite>
<helpers>
<modulename>
<class>Package_ModuleName_Helper</class>
</modulename>
</helpers>
</global>
this might help you.

Why does Magento core override not register until third request?

I am overriding the Mage_Core_Model_Encryption in my module to override hash, getHash, and validateHash methods.
Since urls in the admin side of things use hashing as well, I am overriding the Mage_Adminhtml_Model_Url getSecretKey method so that it will use (faster) md5 hashing in the urls.
The problem I have noticed is that when I clear my cache (config only is enabled) and load the admin/index my encyptor is not registered. It takes until the third request for it to be seen.
I have debugging statements in Mycompany_Encryption_Adminhtml_Url which show that it is immediately loaded with the module. After clearing my cache, I can see my debug statements are working.
When I use the following statement:
var_dump('Class name: '.get_class(Mage::helper('core')->getEncryptor() ) );
I see returned to admin/index (upon refreshing the page) that the class name is Mage_Core_Model_Encryption, then on the third refresh it shows me my class, Mycompany_Encryption_Model_Encryption.
Why does this take three requests? I have been searching all over and haven't found/figured out the problem yet. By all appearances, I have this configured correctly ( and have experimented with a bunch of alternatives).
Can anyone help me solve this issue?
(Below are config, Url class, and Encryption class snippets). Big thanks in advance for any help.
Update, am using modman, here is my modman too:
# Modman file allows Modman to generate links in Magento.
code app/code/local/Mycompany/Encryption/
Mycompany_Encryption.xml app/etc/modules/Mycompany_Encryption.xml
Here is my config:
<config>
<modules>
<Mycompany_Encryption>
<version>0.1</version>
<depends>
<Mage_Core />
</depends>
</Mycompany_Encryption>
</modules>
<phpunit>
<suite>
<modules>
<Mycompany_Encryption />
</modules>
</suite>
</phpunit>
<global>
<helpers>
<core>
<encryption_model>
<class>Mycompany_Encryption_Model_Encryption</class>
</encryption_model>
</core>
</helpers>
<models>
<mycompany_encryption>
<class>Mycompany_Encryption_Model</class>
</mycompany_encryption>
<core>
<rewrite>
<encryption>Mycompany_Encryption_Model_Encryption</encryption>
</rewrite>
</core>
<adminhtml>
<rewrite>
<url>Mycompany_Encryption_Model_Adminhtml_Url</url>
</rewrite>
</adminhtml>
</models>
</global>
</config>
Url class:
class Mycompany_Encryption_Model_Adminhtml_Url extends Mage_Adminhtml_Model_Url
{
/**
* Generate secret key for controller and action based on form key
*
* #param string $controller Controller name
* #param string $action Action name
* #return string
*/
public function getSecretKey($controller = null, $action = null)
{
$salt = Mage::getSingleton('core/session')->getFormKey();
$p = explode('/', trim($this->getRequest()->getOriginalPathInfo(), '/'));
if (!$controller) {
var_dump('Not Controller');
$controller = !empty($p[1]) ? $p[1] : $this->getRequest()->getControllerName();
}
if (!$action) {
var_dump('Not Action');
$action = !empty($p[2]) ? $p[2] : $this->getRequest()->getActionName();
}
$secret = $controller . $action . $salt;
// Here are my debug statements showing when class/method become available.
var_dump('Method exists: '.method_exists(Mage::helper('core')->getEncryptor(), 'urlHash'));
var_dump('Class name: '.get_class(Mage::helper('core')->getEncryptor() ) );
/* This is what I want to return - but sends error 500 until instantiated. */
//return Mage::helper('core')->getEncryptor()->urlHash($secret);
return false;
}
}
Encryption class:
class Mycompany_Encryption_Model_Encryption extends Mage_Core_Model_Encryption
{
public function hash($data)
{
return password_hash($data, PASSWORD_BCRYPT);
}
public function validateHash($password, $hash)
{
return password_verify($password, $hash);
}
public function getHash($value)
{
return $this->hash($value);
}
public function urlHash($value)
{
return md5($value);
}
}
Using the n98-magerun tool, I was able to config:dump and search for the global/helpers/core node.
With the above configuration, I was getting this badly formed config dump:
$ n98-magerun config:dump |cat |grep -A1 -B2 encryption_model
<helpers>
<core>
<encryption_model>Mage_Core_Model_Encryption<class>Mycompany_Encryption_Model_Encryption</class></encryption_model>
</core>
It appears to clear up if I remove the <class> tags in my config.xml:
<helpers>
...
<core>
<!-- Class tags were surrounding my encryption_model value before -->
<encryption_model>Mycompany_Encryption_Model_Encryption</encryption_model>
</core>
...
</helpers>
With this change, I clear cache and get a better config dump:
$ n98-magerun cache:clean config
config cache cleaned
$ n98-magerun config:dump |cat |grep -A1 -B2 encryption_model
<helpers>
<core>
<encryption_model>Mycompany_Encryption_Model_Encryption</encryption_model>
</core>
Please comment with a doc link or provide info if you know why this was happening! Thanks!

Magento: Setting custom shipping method programmatically

I'm pretty new to Magento, and having problems trying to set a custom shipping method programmatically. I'm converting an xml from a thrid party into an order, and everything else (that I've worked on so far) is working fine. Also I'm having problems spelling "programmatically" but I won't ask for you help with that.
I set up my custom shipping method as follows:
To activate the shipping module in
app/etc/modules/Extension_Shipping.xml
<?xml version=
"1.0"?>
<config>
<modules>
<Extension_Shipping>
<active>true</active>
<codePool>local</codePool>
<depends>
<Mage_Shipping/>
</depends>
</Extension_Shipping>
</modules>
</config>
then to configure it in
app/code/local/Extension/Shipping/etc/config.xml
<?xml version=
"1.0" ?>
<config>
<modules>
<Extension_Shipping>
<version>0.1.0</version>
</Extension_Shipping>
</modules>
<global>
<models>
<extension_shipping>
<class>Extension_Shipping_Model</class>
</extension_shipping>
</models>
</global>
<default>
<carriers>
<extension_myrate>
<active>1</active>
<model>extension_shipping/carrier_myrate</model>
<title>Extension Shipping</title>
<name>Default Rate</name>
</extension_myrate>
</carriers>
</default>
</config>
then to add the class in
app/code/local/Extension/Shipping/Model/Carrier/MyRate.php
<?php
class Extension_Shipping_Model_Carrier_MyRate
extends Mage_Shipping_Model_Carrier_Abstract
implements Mage_Shipping_Model_Carrier_Interface
{
protected $_code = 'extension_myrate';
protected $_isFixed = true;
public function collectRates(Mage_Shipping_Model_Rate_Request
$request)
{
if (!$this->getConfigFlag('active')) {
return false;
}
$result = Mage::getModel('shipping/rate_result');
$method = Mage::getModel('shipping/rate_result_method');
$method->setCarrier('extension_myrate');
$method->setCarrierTitle($this->getConfigData('title'));
$method->setMethod('extension_myrate');
$method->setMethodTitle($this->getConfigData('name'));
$method->setPrice(5);
$method->setCost(2);
$result->append($method);
return $result;
}
public function getAllowedMethods()
{
return array('extension_myrate' => $this->getConfigData('name'));
}
}
Basically I followed http://www.magentotricks.com/creating-a-customer-magento-shipping-method/
I thought it all worked fine, as the shipping method now shows up in the checkout screen, and can be set both by customers or in the admin "create new order." However, I'm not able to set it programmatically.
In my controller I'm trying to set the shipping method using the code
$shippingAddress = $quote->getShippingAddress()->addData($addressData);
$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('extension_myrate')
->setPaymentMethod('checkmo');
To add to my confusion, it worked once. but only once out of quite a few test orders. changing the "setShippingMethod" to "freeshipping_freeshipping" or "flatrate_flatrate" makes it update the shipping to those correctly. because of that and because I'm new and still having problems with the file structure, I'm guessing my problem is with setShippingMethod('extension_myrate') but I'm not entirely sure. Any advice would be helpful and appreciated.

Magento: Rendering blank page when calling template from Ajax

First off, I must apologize for my lack of knowledge on the subject. I'm still new to Magento, and with the information I've come across, I should've been able to get this working. I started off here. I'm able to get the Ajax method to make a call, but I'm getting a blank 2column-left.phtml as my output (So I'm seeing the header, left column, blank main column, and footer). I have my files set up as so:
app/local/MyModule/Featured/Block/Featured.php
<?php
class MyModule_Featured_Block_Featured extends Mage_Core_Block_Template
{
public function __construct()
{
$this->_controller = 'featured';
$this->_blockGroup = 'featured';
parent::__construct();
}
}
?>
app/local/MyModule/Featured/controllers/FeaturedController.php
<?php
class MyModule_Featured_FeaturedController extends Mage_Core_Controller_Front_Action
{
public function displayAction()
{
$this->loadLayout()->renderLayout();
}
}
?>
app/local/MyModule/Featured/etc/config.xml
<config>
<modules>
<MyModule_Featured>
<version>0.1.0</version>
</MyModule_Featured>
</modules>
<frontend>
<routers>
<featured>
<use>standard</use>
<args>
<module>MyModule_Featured</module>
<frontName>featured</frontName>
</args>
</featured>
</routers>
</frontend>
</config>
app/design/frontend/default/myLayout/layout/local.xml
<config>
<featured_featured_display>
<block type="module/block" name="root" output="toHtml" template="catalog/product/featured.phtml" />
</featured_featured_display>
</config>
Ajax Code on Homepage custom phtml:
var url = "<?php echo $this->getUrl('featured/featured/display') ;?>";
jQuery(document).ready(function() {
jQuery('#featured-products').load(url);
});
I believe the layout file's root node should be <layout> and not <config>.
P.S.
If you wanted to do without jQuery - to avoid bloat - Magento already has Prototype as standard and can do exactly the same.
var url = "<?php echo $this->getUrl('featured/featured/display') ?>";
document.observer('dom:loaded', function(){
new Ajax.Updater('featured-products', url);
});
Load layout includes the default handle normally, so my guess is that your assignment has no effect because there is a root note being loaded already. Try removing the root node first, and then add it back as your only node.

Categories