Converting module Drupal7 to Drupal8 - php

I want to convert drupal7 module to drupal8. As I know that drupal8 is object oriented but still there are some issue in my code.
I wrote the code in oop but it cannot run properly and when I run the code it shows error that function is not defined. The function of my module is to redirect folders in root directory.
A little help will be appreciated.
<?php
namespace Drupal\afridi\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Database\Database;
use Drupal\Core\Form\FormStateInterface;
use \Drupal\Core\Form\FormValidatorInterface;
use \Drupal\Core\Form\FormSubmitterInterface;
use Drupal\Core\Form\ConfigFormBase;
use Symfony\Component\HttpFoundation\Request;
/**
* Class DefaultForm.
*/
class DefaultForm extends FormBase {
// public function afridi_trigger_import_redirects($path, $path_to, $exceptions, $folder_scan = NULL);
/**
* {#inheritdoc}
*/
public function getFormId() {
return 'default_form';
}
/**
* {#inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form = array();
$form['files_autoredirect']['title'] = array(
'#markup' => t('<h2>Folder Redirect</h2><p>Before moving the media folder from old location to new location, add the folder path & destination path in order to automatically generate <b>301 redirect</b> for all the files in folder. Once the redirects are generated, move the folder from the old location to the new location & verify by visiting old url if it redirects correctly to the new file location.</p>'),
);
$form['afridi']['scan_folder'] = array(
'#type' => 'textfield',
'#title' => t('Folder to scan'),
'#default_value' => !empty(\Drupal::state()->get('afridi_scan_folder')) ? \Drupal::state()->get('afridi_scan_folder') : '',
'#size' => 60,
'#maxlength' => 128,
'#description' => t('This folder must exsist & accessible under the path so all the files inside can be scanned and a redirect rule is added for each file.<br>Example: For <b>root/content</b> folder add <b>content</b>.'),
'#required' => TRUE,
);
$form['afridi']['check'] = array(
'#title' => t("Same as folder path"),
'#type' => 'checkbox',
'#default_value' => !empty(\Drupal::state()->get('afridi_check')) ? \Drupal::state()->get('afridi_check') : '',
'#description' => t('Uncheck if the <b>redirect from</b> path is different.'),
'#ajax' => array(
'callback' => 'testprb_ajaxtest',
'wrapper' => 'testprb_replace_field_div',
),
);
$form['afridi']['path_check'] = array(
'#type' => 'container',
'#states' => array(
"visible" => array(
"input[name='check']" => array("checked" => FALSE),
),
),
);
$form['afridi']['path_check']['path_from'] = array(
'#type' => 'textfield',
'#title' => t('Redirect from path'),
'#default_value' => !empty(\Drupal::state()->get('afridi_from')) ? \Drupal::state()->get('afridi_from') : '',
'#size' => 60,
'#maxlength' => 128,
'#description' => t('Example: For <b>root/content</b> folder add <b>content</b>. If left blank scanned folder will be chosen as base path.'),
);
$form['afridi']['path_to'] = array(
'#type' => 'textfield',
'#title' => t('Redirect to path'),
'#default_value' => !empty(\Drupal::state()->get('afridi_to')) ? \Drupal::state()->get('afridi_to') : '',
'#size' => 60,
'#maxlength' => 128,
'#description' => t('Example: <b>sites/default/files/</b> for <b>root/sites/default/files</b> folder. Trailing slash must be provided.'),
'#required' => TRUE,
);
$form['afridi']['exception'] = array(
'#title' => t('Exceptions'),
'#type' => 'textarea',
'#description' => t('Exception rules, files or directories added in the list will be ignored. Add one entry per row.'),
'#default_value' => !empty(\Drupal::state()->get('afridi_exceptions')) ? implode(\Drupal::state()->get('afridi_exceptions')) : implode(PHP_EOL, array(
'. ',
'.. ',
'.DS_Store ',
)),
);
$form['submit'][] = array(
'#type' => 'submit',
'#value' => t('Generate Redirects'),
);
return $form;
}
/**
* {#inheritdoc}
*/
function submitForm(array &$form, FormStateInterface $form_state) {
if ($form_state->hasValue(array('exception'))) {
$exceptions = explode(PHP_EOL, trim($form_state->getValues('exception')));
\Drupal::state()->set('folder_redirect_exceptions', $exceptions);
}
\Drupal::state()->set('folder_redirect_check', $form_state->getValues('check'));
\Drupal::state()->set('folder_redirect_scan_folder', $form_state->getValues('scan_folder'));
\Drupal::state()->set('folder_redirect_from', $form_state->getValues('path_from'));
\Drupal::state()->set('folder_redirect_to', $form_state->getValues('path_to'));
if (!empty(\Drupal::state()->get('folder_redirect_scan_folder', '')) && !empty(\Drupal::state()->get('folder_redirect_to'))) {
if (\Drupal::state()->get('folder_redirect_check','')) {
\Drupal::state()->delete('folder_redirect_from');
if (afridi_trigger_import_redirects(\Drupal::state()->get('folder_redirect_scan_folder' , ''), \Drupal::state()->get('folder_redirect_to', ''), \Drupal::state()->get('folder_redirect_exceptions', ''))) {
drupal_set_message(t('Url redirects generated, Redirects List', array('#base-url' => url('/admin/config/search/redirect'))), 'status', TRUE);
}
else {
drupal_set_message(t('Looks like "<i> %dir </i>" doesn\'t exsist or inaccessible, please check the permission if exsists', array('%dir' => \Drupal::state()->get('folder_redirect_scan_folder') )), 'error', TRUE);
}
}
else {
if (afridi_trigger_import_redirects(\Drupal::state()->get('folder_redirect_from', ''), \Drupal::state()->get('folder_redirect_to', ''), \Drupal::state()->get('folder_redirect_exceptions', ''), \Drupal::state()->get('folder_redirect_scan_folder','')))
{
drupal_set_message(t('Url redirects generated, Redirects List', array('#base-url' => url('/admin/config/search/redirect'))), 'status', TRUE);
}
else {
drupal_set_message(t('Looks like "<i> %dir </i>" doesn\'t exsist or inaccessible, please check the permission if exsists', array('%dir' => variable_get('folder_redirect_scan_folder'))), 'error', TRUE);
}
}
}
else {
drupal_set_message(t('Invalid configurations, please try again'), 'error', TRUE);
}
}
/**
* Helper function to set important variables.
*/
function afridi_trigger_import_redirects($path, $path_to, $exceptions, $folder_scan = NULL) {
$root = DRUPAL_ROOT . "/";
$root_preg = preg_replace("/([\/]+)/", "\\/", $root);
$path_from_preg = preg_replace("/([\/]+)/", "\\/", $path);
if ($folder_scan) {
$scan_folder = $root . $folder_scan;
if (is_dir($scan_folder)) {
afridi_list_all_files($scan_folder, $path_from_preg, $path_to, $root, $root_preg, $exceptions, $path);
return TRUE;
}
else {
return FALSE;
}
}
else {
$path = $root . $path;
if (is_dir($path)) {
afridi_list_all_files($path, $path_from_preg, $path_to, $root, $root_preg, $exceptions);
return TRUE;
}
else {
return FALSE;
}
}
}
/**
* Helper function to scan the dir and its sub-dir.
*/
function afridi_list_all_files($path, $path_from_preg, $path_to, $root, $root_preg, $exceptions, $different_path_from = '') {
if (!isset($redirects)) {
$redirects = array();
}
$files = array_diff(scandir($path), array_map('trim', $exceptions));
foreach ($files as $file) {
if (is_dir($path . "/{$file}")) {
if (!empty($different_path_from)) {
afridi_list_all_files($path . "/{$file}", $path_from_preg, $path_to, $root, $root_preg, $exceptions, $different_path_from);
}
else {
afridi_list_all_files($path . "/{$file}", $path_from_preg, $path_to, $root, $root_preg, $exceptions);
}
}
else {
if (!empty($different_path_from)) {
preg_match("/" . $root_preg . "(...+)/", $path . "/{$file}", $out);
preg_match("/([a-zA-Z0-9-_]+)([\/])([.a-zA-Z0-9-_\/]+)/", $out[1], $out1);
$redirect_from = $different_path_from . '/' . $out1[3];
$redirect_to = $path_to . $out1[3];;
}
else {
preg_match("/" . $root_preg . "(...+)/", $path . "/{$file}", $out);
$redirect_from = $out[1];
preg_match("/" . $path_from_preg . "\/(...+)/", $redirect_from, $out1);
$redirect_to = $path_to . $out1[1];
}
$redirects[$redirect_from] = $redirect_to;
}
}
afridi_import_redirects($redirects);
}
/**
* Helper function to import redirects.
*/
function afridi_import_redirect($redirect_from, $redirect_to) {
$redirect = new stdClass();
module_invoke(
'redirect',
'object_prepare',
$redirect,
array(
'source' => $redirect_from,
'source_options' => array(),
'redirect' => $redirect_to,
'redirect_options' => array(),
'language' => LANGUAGE_NONE,
)
);
module_invoke('redirect', 'save', $redirect);
}
/**
* Helper function to import bulk redirects.
*/
function afridi_import_redirects($redirects) {
foreach ($redirects as $from_url => $to_url) {
if (!redirect_load_by_source($from_url)) {
$redirect = new stdClass();
redirect_object_prepare(
$redirect,
array(
'source' => $from_url,
'source_options' => array(),
'redirect' => $to_url,
'redirect_options' => array(),
'language' => LANGUAGE_NONE,
)
);
redirect_save($redirect);
}
else {
drupal_set_message(t('Redirect already exsists for path<i> "#path" </i>', array('#path' => $from_url)), 'warning', TRUE);
}
}
}
}
I want to redirect the folder path in this section but there are some issues. It show error that function is undefined.

In PHP, method calls always need to provide the object instance ($this), or the class name if it is a static method call. So for your case, you cannot directly call afridi_trigger_import_redirects, or afridi_list_all_files as they were ordinary functions.
The quick fix would be to call them with the $this instance. For example, this:
if (afridi_trigger_import_redirects(\Drupal::state()->get('folder_redirect_scan_folder' , ''), \Drupal::state()->get('folder_redirect_to', ''), \Drupal::state()->get('folder_redirect_exceptions', ''))) {
drupal_set_message(t('Url redirects generated, Redirects List', array('#base-url' => url('/admin/config/search/redirect'))), 'status', TRUE);
}
Should be rewritten into this:
if ($this->afridi_trigger_import_redirects(\Drupal::state()->get('folder_redirect_scan_folder' , ''), \Drupal::state()->get('folder_redirect_to', ''), \Drupal::state()->get('folder_redirect_exceptions', ''))) {
drupal_set_message(t('Url redirects generated, Redirects List', array('#base-url' => url('/admin/config/search/redirect'))), 'status', TRUE);
}
A more elegant way is to rewrite all methods that do not reference instance attributes as static methods. For example, this:
function ($path, $path_to, $exceptions, $folder_scan = NULL) {
should be rewritten as this:
public static function ($path, $path_to, $exceptions, $folder_scan = NULL) {
And all afridi_trigger_import_redirects calls should be rewritten in DefaultForm::afridi_trigger_import_redirects format.

Related

Cannot add any stylesheets to module in prestashop 1.7

I've encountered problem with adding any stylesheets to prestashop front office. I was reading multiple articles, tried multiple solutions and I can't get it to work. Adding styles to back office was not a problem (but that this code for adding styles to back office is workaround I think). Here is the module code. (I've added stylesheet import in multiple places to check every solution. In other modules this methods works as intended). Sorry for messy code I'm not that good in PHP.
<?php
if (!defined('_PS_VERSION_'))
exit();
class PromotionBanner extends Module
{
public function __construct()
{
$this->name = 'promotionbanner';
$this->tab = 'front_office_features';
$this->version = '1.0.0';
$this->author = 'example';
$this->author_uri = 'https://example.com';
$this->ps_versions_compliancy = array('min' => '1.7.1.0', 'max' => _PS_VERSION_);
$this->bootstrap = true;
$this->need_instance = 0;
$this->dir = '/modules/promotionbanner';
$this->css_path = Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->name
. '/' . $this->_path . 'views/css/';
parent::__construct();
$this->displayName = $this->l('Promotion Banner', 'promotionbanner');
$this->description = $this->l('This module provides configurable promotion banner on your website');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall the module?', 'promotionbanner');
}
private function updateConf()
{
Configuration::updateValue('banner_text', $this->l('Wybrane produkty taƄsze o 15%! Kod rabatowy: '));
Configuration::updateValue('banner_coupon_code', $this->l('Wybierz kupon rabatowy'));
}
public function install()
{
$this->updateConf();
return parent::install() && $this -> registerHook('displayWrapperTop') && $this->registerHook('header');
}
public function uninstall()
{
if (!parent::uninstall() || !Configuration::deleteByName('promotionbanner_module') &&
!Configuration::deleteByName('banner_coupon_code'))
return false;
return true;
}
public function hookDisplayWrapperTop($params)
{
$this->context->smarty->assign(
array(
'banner_text' => Configuration::get('banner_text'),
'banner_coupon_code' => Configuration::get('banner_coupon_code')
)
);
$this->context->controller->registerStylesheet(
'modules-promotion-banner2', //This id has to be unique
'modules/'.$this->name.'/views/css/front.css',
array('media' => 'all', 'priority' => 150)
);
return $this->display(__FILE__, 'promotionbanner.tpl');
}
public function hookHeader() {
$this->context->controller->addCSS($this->_path . 'views/css/front.css', 'all');
$this->context->controller->registerStylesheet(
'modules-promotion-banner', //This id has to be unique
'modules/'.$this->name.'/views/css/front.css',
array('media' => 'all', 'priority' => 150)
);
}
public function hookActionFrontControllerSetMedia($params) {
$this->context->controller->registerStylesheet(
'module-promotionbanner-style',
'modules/'.$this->name.'/views/css/front.css',
[
'media' => 'all',
'priority' => 200,
]
);
}
public function getPromotions()
{
$cart_rule = _DB_PREFIX_ . 'cart_rule';
$request = "SELECT $cart_rule.id_cart_rule, " . _DB_PREFIX_ . "cart_rule_lang.name, $cart_rule.code " .
"FROM $cart_rule INNER JOIN " . _DB_PREFIX_ . 'cart_rule_lang ON ' . _DB_PREFIX_ . 'cart_rule.id_cart_rule='
. _DB_PREFIX_ . 'cart_rule_lang.id_cart_rule WHERE ' . _DB_PREFIX_ . 'cart_rule.code IS NOT NULL';
$db = Db::getInstance();
$cupons = $db->executeS($request);
$parsedCupons = array();
foreach ($cupons as $cupon) {
array_push($parsedCupons, array(
'code' => $cupon['code'],
'name' => $cupon['name']
));
}
return $parsedCupons;
}
public function displayForm()
{
$form = $this->renderForm();
$this->context->smarty->assign(array(
'banner_text' => Configuration::get('banner_text'),
'banner_coupon_code' => Configuration::get('banner_coupon_code'),
'form_url' => AdminController::$currentIndex . '&configure=' . $this->name . '&token=' . Tools::getAdminTokenLite('AdminModules'),
'name' => $this->name,
'form_tpl' => $form,
'coupon_codes' => $this->getPromotions()
));
$this->context->controller->addCSS(array(
$this->css_path . 'fontawesome-all.min.css',
$this->css_path . 'module.css'
));
$this->output = $this->context->smarty->fetch($this->local_path . 'views/templates/admin/menu.tpl');
return $this->output;
}
public function renderForm()
{
$helper = new HelperForm();
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex . '&configure=' . $this->name;
$helper->title = $this->displayName;
$helper->show_toolbar = false;
$helper->toolbar_scroll = false;
$helper->submit_action = 'submit' . $this->name;
$helper->toolbar_btn = array(
'save' =>
array(
'desc' => $this->l('Save'),
'href' => AdminController::$currentIndex . '&configure=' . $this->name . '&save' . $this->name .
'&token=' . Tools::getAdminTokenLite('AdminModules'),
)
);
$helper->fields_value = array(
'banner_text' => Configuration::get('banner_text'),
'banner_coupon_code' => Configuration::get('banner_coupon_code')
);
return $helper->generateForm(array($this->getConfigForm()));
}
public function getConfigForm()
{
$fields_form = array(
'form' => array(
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Banner text before code: '),
'name' => 'banner_text',
'lang' => false,
'required' => true,
'size' => 20
),
array(
'type' => 'select',
'label' => $this->l('Coupon code: '),
'name' => 'banner_coupon_code',
'required' => true,
'options' => array(
'query' => $this->getPromotions(),
'id' => 'code',
'name' => 'name'
)
)
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'btn btn-default pull-right'
)
)
);
return $fields_form;
}
public function getContent()
{
$output = "";
if (Tools::isSubmit('submit' . $this->name)) {
$banner_text = strval(Tools::getValue('banner_text'));
$banner_coupon_code = strval(Tools::getValue('banner_coupon_code'));
if (!isset($banner_text) || !isset($banner_coupon_code))
$output .= $this->displayError($this->l('Please insert something in this field.'));
else {
Configuration::updateValue('banner_text', $banner_text);
Configuration::updateValue('banner_coupon_code', $banner_coupon_code);
$output .= $this->displayConfirmation($this->l('Field updated successfully!'));
}
}
return $output . $this->displayForm();
}
}
Okay so I've managed to successfully register the stylesheet in the prestashop 1.7.6.1. But I think this is a good time to mention some of my mistakes and address some of the problems.
Checklist of registering a stylesheet in front office
Use correct hook for the job.
My problem has been unsolved because I've used a wrong hook.
Make sure that your __construct() registered a official hook for registering stylesheets (prestashop 1.7.x). The correct hook is: $this->registerHook('actionFrontControllerSetMedia'); you can find official docs here (If you don't have front controller in your module): https://devdocs.prestashop.com/1.7/themes/getting-started/asset-management/#without-a-front-controller-module
Make sure that you registered your hook function with $params (I don't know why but it doesn't work without a function parameter defined... This also stopped me from successfull register). The proper function should look like this:
$this->context->controller->registerStylesheet(
'stylesheet-id', //This id has to be unique
'modules/'.$this->name.'/views/css/front.css',
array('server' => 'local', 'priority' => 10)
);
}
As #bakis mentioned. After every try clear your browser cache + prestashop cache for chrome or chromium users I would suggest to disable the browser cache in inspector window completely.
I know that $this->context->controller->addCSS still exists, but this function is useful only for back office stylesheet register. Even the official docs are saying about it
Backward compatibility is kept for the addJS(), addCSS(), addJqueryUI() and addJqueryPlugin() methods.
That's pretty much everything about this question. I hope it will help someone in the future who is searching for answer.

AJAX callback no response in custom Drupal block

I added a PhantomJS Capture module to my Drupal website. Test function showed my configuration works and I can use it from an administration interface. Now, I want to put it on a website, as a custom block so an end user could paste a website link and get screenshot of it back.
I implemented this piece of the code at the end of the module and form appears on a website.
/**
* Implements hook_block_info().
*/
function phantomjs_capture_block_info() {
$blocks = array();
$blocks['Scraping Block'] = array(
'info' => t('scraping block'),
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function phantomjs_capture_block_view($delta = '') {
$block = array();
switch ($delta) {
case 'Scraping Block':
$block['subject'] = 'Scraper';
$block['content'] = phantomjs_capture_admin_form();
break;
}
return $block;
}
However ajax callback is not firing on submit. How can I test this problem? Or is something wrong with my understanding of this module?
This is all code I've got in phantomjs_capture.module, I haven't changed any other files.
<?php
/**
* #file
* Defines the administration interface and utility functions to use PhantomJS
* and test screenshot capture functions.
*/
// #todo: hook_help.
/**
* Implements hook_menu().
*/
function phantomjs_capture_menu() {
$items = array();
$items['admin/config/user-interface/phantomjs_capture'] = array(
'title' => 'PhantomJS Screen capture',
'description' => 'Screen capture with PhantomJS',
'page callback' => 'drupal_get_form',
'page arguments' => array('phantomjs_capture_admin_form'),
'access arguments' => array('adminster site'),
);
return $items;
}
/**
* The administration form that allows site admins to enter information about
* the systems installation of PhantomJS.
*
* #return array $form
* Drupal form array witht the administration form.
*/
function phantomjs_capture_admin_form() {
$form = array();
$form['phantomjs_settings'] = array(
'#type' => 'fieldset',
'#title' => t('PhantomJS settings'),
'#collapsible' => FALSE,
);
$form['phantomjs_settings']['phantomjs_capture_binary'] = array(
'#type' => 'textfield',
'#required' => TRUE,
'#title' => t('Path to phantomJS'),
'#description' => t('This module requries that you install PhantomJS on your server and enter the path to the executable. The program is not include in the module due to linces and operation system constrains. See !url for information about download.', array(
'!url' => l('PhantomJs.org', 'http://phantomjs.org/'),
)),
'#default_value' => variable_get('phantomjs_capture_binary', _phantomjs_capture_get_binray()),
);
$form['phantomjs_settings']['phantomjs_capture_dest'] = array(
'#type' => 'textfield',
'#required' => TRUE,
'#title' => t('Default destination'),
'#description' => t('The default destination for screenshots captures with PhantomJS'),
'#default_value' => variable_get('phantomjs_capture_dest', 'phantomjs'),
);
$form['phantomjs_settings']['phantomjs_capture_script'] = array(
'#type' => 'textfield',
'#required' => TRUE,
'#title' => t('PhantomJS capture script'),
'#description' => t('The script used by PhantomJS to capture the screen. It captures full HD images (1920 x 1080).'),
'#default_value' => variable_get('phantomjs_capture_script', drupal_get_path('module', 'phantomjs_capture') . '/js/phantomjs_capture.js'),
);
$form['phantomjs_capture_test'] = array(
'#type' => 'fieldset',
'#title' => t('Phantom JS test'),
'#description' => t('You can use the form in this section to test your installation of PhantomJS.'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#tree' => TRUE,
);
$form['phantomjs_capture_test']['url'] = array(
'#type' => 'textfield',
'#title' => t('URL'),
'#description' => t('Absolute URL to the homepage that should be capture (it has to be a complet URL with http://).'),
'#default_value' => 'http://www.google.com',
);
$form['phantomjs_capture_test']['format'] = array(
'#type' => 'select',
'#title' => 'File format',
'#options' => array(
'.png' => 'png',
'.jpg' => 'jpg',
'.pdf' => 'pdf',
),
);
$form['phantomjs_capture_test']['result'] = array(
'#prefix' => '<div id="phantomjs-capture-test-result">',
'#suffix' => '</div>',
'#markup' => '',
);
$form['phantomjs_capture_test']['button'] = array(
'#type' => 'button',
'#value' => t('Capture'),
"#ajax" => array(
"callback" => "phantomjs_capture_test_submit",
"wrapper" => "phantomjs-capture-test-result",
"method" => 'replace',
"effect" => "fade"
)
);
return $form;
}
/**
* Ajax callback for the test PhantomJS form on the administration page.
*
* #param type $form
* #param type $form_state
* #return type
*/
function phantomjs_capture_test_submit($form, $form_state) {
// Build urls and destionation.
$url = $form_state['values']['phantomjs_capture_test']['url'];
$file = 'test' . $form_state['values']['phantomjs_capture_test']['format'];
$dest = file_default_scheme() . '://' . variable_get('phantomjs_capture_dest', 'phantomjs');
// Get the screenshot and create success/error message.
$output = '<div class="messages status"><ul><li>' . t('File have been generated. You can get it !url', array('!url' => l(t('here'), file_create_url($dest . '/' . $file)))) . '.</ul></li></div>';
if (!phantomjs_capture_screen($url, $dest, $file)) {
$output = '<div class="messages error"><ul><li>' . t('The address entered could not be retrieved.') . '</ul></li></div>';
}
// Return
return array(
'phantomjs_capture_test' => array(
'result' => array(
'#prefix' => '<div id="phantomjs-capture-test-result">',
'#suffix' => '</div>',
'#markup' => $output,
),
),
);
}
/**
* Validation of the administration form. It tests that the locations given
* exists and that the PhantomJS binary is executable (by getting its version
* number).
*
* #param type $form
* #param type $form_state
*/
function phantomjs_capture_admin_form_validate(&$form, &$form_state) {
// Check that phantomjs exists.
if (!file_exists($form_state['values']['phantomjs_capture_binary'])) {
form_set_error('phantomjs_capture_binary', t('PhantomJS was not found at the location given.'));
}
else {
// Only show version message on "Save configuration" submit.
if ($form_state['clicked_button']['#value'] == t('Save configuration')) {
drupal_set_message(t('PhantomJS version #version found.', array(
'#version' => _phantomjs_capture_get_version($form_state['values']['phantomjs_capture_binary']),
)));
}
}
// Check that destination can be created.
$dest = file_default_scheme() . '://' . $form_state['values']['phantomjs_capture_dest'];
if (!file_prepare_directory($dest, FILE_CREATE_DIRECTORY)) {
form_set_error('phantomjs_capture_dest', t('The path was not writeable or could not be created.'));
}
// Check that capture script exists.
if (!file_exists($form_state['values']['phantomjs_capture_script'])) {
form_set_error('phantomjs_capture_script', t('PhantomJS script was not found at the location given.'));
}
// Remove test form.
unset($form_state['values']['phantomjs_capture_test']);
}
/**
* Returns the version number of the currently install PhantomJS.
*
* #param string $binary
* Optional absolute path with the PhantomJS binary. If not given the default
* location is used.
* #return string|boolean
* If PhantomJS is found and executeable the version number is returned else
* FALSE is returned.
*/
function _phantomjs_capture_get_version($binary = NULL) {
// If the binary is not given try the default path.
if (is_null($binary)) {
$binary = _phantomjs_capture_get_binray();
if (!$binary) {
drupal_set_message(t('PhantomJS binary was not found. Plase intall PhantomJS on the system.'));
return FALSE;
}
}
// Execute PhantomJS to get its version, if PhantomJS was found.
$output = array();
exec($binary . ' -v', $output);
return $output[0];
}
/**
* Returns the absolute path with the binray to the installed PhantomJS.
*
* #return string|boolean
* The executable PhantomJS binary or FALSE if not found.
*/
function _phantomjs_capture_get_binray() {
$binary = variable_get('phantomjs_capture_binary', '/usr/local/bin/phantomjs');
if (!file_exists($binary)) {
return FALSE;
}
return $binary;
}
/**
* Captures a screenshot using PhantomJS by calling the program.
*
* #param string $url
* The ULR/http(s) to render the screenshot from.
* #param type $dest
* The destionation for the rendered file (e.g. public://fecthed_images).
* #param type $filename
* The filename to store the file as in the destination.
* #param type $element
* The id of the DOM element to render in the document.
* #return boolean
* Returns TRUE if the screenshot was taken else FALSE on error.
*/
function phantomjs_capture_screen($url, $dest, $filename, $element = NULL) {
// Get PhantomJS binary.
$binary = _phantomjs_capture_get_binray();
if (!$binary) {
drupal_set_message(t('PhantomJS binary was not found. Plase intall PhantomJS on the system.'));
return FALSE;
}
// Check that destination is writeable.
if (!file_prepare_directory($dest, FILE_CREATE_DIRECTORY)) {
drupal_set_message(t('The PhantomJS destination path (#dest) was not writeable or could not be created.', array(
'#dest' => $dest,
)));
return FALSE;
}
// Get absolute path to PhantomJS script and the destionation file.
$script = realpath(variable_get('phantomjs_capture_script', drupal_get_path('module', 'phantomjs_capture') . '/js/phantomjs_capture.js'));
$dest = drupal_realpath($dest . '/' . $filename);
// Run PhantomJS to create the screen shot.
$output = array();
if ($element) {
exec($binary . ' ' . $script . ' ' . $url . ' ' . $dest . ' ' . escapeshellarg($element), $output);
} else {
exec($binary . ' ' . $script . ' ' . $url . ' ' . $dest, $output);
}
// Check that PhantomJS was able to load the page.
if ($output[0] == '500') {
return FALSE;
}
return TRUE;
}
/**
* Implements hook_block_info().
*/
function phantomjs_capture_block_info() {
$blocks = array();
$blocks['Scraping Block'] = array(
'info' => t('scraping block'),
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function phantomjs_capture_block_view($delta = '') {
$block = array();
switch ($delta) {
case 'Scraping Block':
$block['subject'] = 'Scraper';
$block['content'] = phantomjs_capture_admin_form();
break;
}
return $block;
}
I got the solution on a different website provided by #zaporylie. The problem wasn't AJAX but my approach to the problem. In short, he suggested to create a new custom module dependent on PhantomJS Capture and then to declare a block.
Here's working code with AJAX:
phantomjs_capture_block.info
name = PhantomJS Capture Block
description = Adds block with simple form.
core = 7.x
package = Other
dependencies[] = phantomjs_capture
phantomjs_capture_block.module
<?php
/**
* #file
* Simple form placed in block.
*/
/**
* Implements hook_block_info().
*/
function phantomjs_capture_block_block_info() {
$blocks['screenshot'] = array(
'info' => t('Screenshot'),
'cache' => DRUPAL_NO_CACHE,
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function phantomjs_capture_block_block_view($delta = '') {
$block = array();
if ($delta === 'screenshot') {
$block['title'] = t('Screenshot');
$block['content'] = drupal_get_form('phantomjs_capture_block_form');
}
return $block;
}
/**
* Simple form.
*/
function phantomjs_capture_block_form($form, &$form_state) {
$form['url'] = array(
'#type' => 'textfield',
'#title' => t('URL'),
'#ajax' => array(
'callback' => 'phantomjs_capture_block_form_callback',
'wrapper' => 'phantomjs-capture-block-form-preview',
'method' => 'replace',
),
);
$form['preview'] = array(
'#type' => 'container',
'#attributes' => array(
'id' => 'phantomjs-capture-block-form-preview',
),
);
if (!empty($form_state['values']['url'])) {
$directory = 'public://';
$filename = REQUEST_TIME . '.png';
if (phantomjs_capture_screen($form_state['values']['url'], $directory, $filename)) {
$form['preview']['image'] = array(
'#theme' => 'image',
'#path' => $directory . '/' . $filename,
'#width' => '100%',
);
}
else {
drupal_set_message(t('Unable to create screenshot'), 'error');
}
}
return $form;
}
function phantomjs_capture_block_form_callback($form, $form_state) {
return $form['preview'];
}

Creating a block using PhantomJS Capture module

I've added a PhantomJS Capture module to my Drupal website. Test function showed my configuration works and I can use it from an administration interface. Now, I want to put it on a website, as a custom block. I added this piece of the code at the end of the module, so the form appears on the website.
/**
* Implements hook_block_info().
*/
function phantomjs_capture_block_info() {
$blocks = array();
$blocks['Scraping Block'] = array(
'info' => t('scraping block'),
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function phantomjs_capture_block_view($delta = '') {
$block = array();
switch ($delta) {
case 'Scraping Block':
$block['subject'] = 'Scraper';
$block['content'] = phantomjs_capture_admin_form();
break;
}
return $block;
}
However ajax callback is not firing on submit. What's wrong with the code or my understanding of this module? Thanks.
This is all code I've got in phantomjs_capture.module, I haven't changed any other files.
<?php
/**
* #file
* Defines the administration interface and utility functions to use PhantomJS
* and test screenshot capture functions.
*/
// #todo: hook_help.
/**
* Implements hook_menu().
*/
function phantomjs_capture_menu() {
$items = array();
$items['admin/config/user-interface/phantomjs_capture'] = array(
'title' => 'PhantomJS Screen capture',
'description' => 'Screen capture with PhantomJS',
'page callback' => 'drupal_get_form',
'page arguments' => array('phantomjs_capture_admin_form'),
'access arguments' => array('adminster site'),
);
return $items;
}
/**
* The administration form that allows site admins to enter information about
* the systems installation of PhantomJS.
*
* #return array $form
* Drupal form array witht the administration form.
*/
function phantomjs_capture_admin_form() {
$form = array();
$form['phantomjs_settings'] = array(
'#type' => 'fieldset',
'#title' => t('PhantomJS settings'),
'#collapsible' => FALSE,
);
$form['phantomjs_settings']['phantomjs_capture_binary'] = array(
'#type' => 'textfield',
'#required' => TRUE,
'#title' => t('Path to phantomJS'),
'#description' => t('This module requries that you install PhantomJS on your server and enter the path to the executable. The program is not include in the module due to linces and operation system constrains. See !url for information about download.', array(
'!url' => l('PhantomJs.org', 'http://phantomjs.org/'),
)),
'#default_value' => variable_get('phantomjs_capture_binary', _phantomjs_capture_get_binray()),
);
$form['phantomjs_settings']['phantomjs_capture_dest'] = array(
'#type' => 'textfield',
'#required' => TRUE,
'#title' => t('Default destination'),
'#description' => t('The default destination for screenshots captures with PhantomJS'),
'#default_value' => variable_get('phantomjs_capture_dest', 'phantomjs'),
);
$form['phantomjs_settings']['phantomjs_capture_script'] = array(
'#type' => 'textfield',
'#required' => TRUE,
'#title' => t('PhantomJS capture script'),
'#description' => t('The script used by PhantomJS to capture the screen. It captures full HD images (1920 x 1080).'),
'#default_value' => variable_get('phantomjs_capture_script', drupal_get_path('module', 'phantomjs_capture') . '/js/phantomjs_capture.js'),
);
$form['phantomjs_capture_test'] = array(
'#type' => 'fieldset',
'#title' => t('Phantom JS test'),
'#description' => t('You can use the form in this section to test your installation of PhantomJS.'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#tree' => TRUE,
);
$form['phantomjs_capture_test']['url'] = array(
'#type' => 'textfield',
'#title' => t('URL'),
'#description' => t('Absolute URL to the homepage that should be capture (it has to be a complet URL with http://).'),
'#default_value' => 'http://www.google.com',
);
$form['phantomjs_capture_test']['format'] = array(
'#type' => 'select',
'#title' => 'File format',
'#options' => array(
'.png' => 'png',
'.jpg' => 'jpg',
'.pdf' => 'pdf',
),
);
$form['phantomjs_capture_test']['result'] = array(
'#prefix' => '<div id="phantomjs-capture-test-result">',
'#suffix' => '</div>',
'#markup' => '',
);
$form['phantomjs_capture_test']['button'] = array(
'#type' => 'button',
'#value' => t('Capture'),
"#ajax" => array(
"callback" => "phantomjs_capture_test_submit",
"wrapper" => "phantomjs-capture-test-result",
"method" => 'replace',
"effect" => "fade"
)
);
return $form;
}
/**
* Ajax callback for the test PhantomJS form on the administration page.
*
* #param type $form
* #param type $form_state
* #return type
*/
function phantomjs_capture_test_submit($form, $form_state) {
// Build urls and destionation.
$url = $form_state['values']['phantomjs_capture_test']['url'];
$file = 'test' . $form_state['values']['phantomjs_capture_test']['format'];
$dest = file_default_scheme() . '://' . variable_get('phantomjs_capture_dest', 'phantomjs');
// Get the screenshot and create success/error message.
$output = '<div class="messages status"><ul><li>' . t('File have been generated. You can get it !url', array('!url' => l(t('here'), file_create_url($dest . '/' . $file)))) . '.</ul></li></div>';
if (!phantomjs_capture_screen($url, $dest, $file)) {
$output = '<div class="messages error"><ul><li>' . t('The address entered could not be retrieved.') . '</ul></li></div>';
}
// Return
return array(
'phantomjs_capture_test' => array(
'result' => array(
'#prefix' => '<div id="phantomjs-capture-test-result">',
'#suffix' => '</div>',
'#markup' => $output,
),
),
);
}
/**
* Validation of the administration form. It tests that the locations given
* exists and that the PhantomJS binary is executable (by getting its version
* number).
*
* #param type $form
* #param type $form_state
*/
function phantomjs_capture_admin_form_validate(&$form, &$form_state) {
// Check that phantomjs exists.
if (!file_exists($form_state['values']['phantomjs_capture_binary'])) {
form_set_error('phantomjs_capture_binary', t('PhantomJS was not found at the location given.'));
}
else {
// Only show version message on "Save configuration" submit.
if ($form_state['clicked_button']['#value'] == t('Save configuration')) {
drupal_set_message(t('PhantomJS version #version found.', array(
'#version' => _phantomjs_capture_get_version($form_state['values']['phantomjs_capture_binary']),
)));
}
}
// Check that destination can be created.
$dest = file_default_scheme() . '://' . $form_state['values']['phantomjs_capture_dest'];
if (!file_prepare_directory($dest, FILE_CREATE_DIRECTORY)) {
form_set_error('phantomjs_capture_dest', t('The path was not writeable or could not be created.'));
}
// Check that capture script exists.
if (!file_exists($form_state['values']['phantomjs_capture_script'])) {
form_set_error('phantomjs_capture_script', t('PhantomJS script was not found at the location given.'));
}
// Remove test form.
unset($form_state['values']['phantomjs_capture_test']);
}
/**
* Returns the version number of the currently install PhantomJS.
*
* #param string $binary
* Optional absolute path with the PhantomJS binary. If not given the default
* location is used.
* #return string|boolean
* If PhantomJS is found and executeable the version number is returned else
* FALSE is returned.
*/
function _phantomjs_capture_get_version($binary = NULL) {
// If the binary is not given try the default path.
if (is_null($binary)) {
$binary = _phantomjs_capture_get_binray();
if (!$binary) {
drupal_set_message(t('PhantomJS binary was not found. Plase intall PhantomJS on the system.'));
return FALSE;
}
}
// Execute PhantomJS to get its version, if PhantomJS was found.
$output = array();
exec($binary . ' -v', $output);
return $output[0];
}
/**
* Returns the absolute path with the binray to the installed PhantomJS.
*
* #return string|boolean
* The executable PhantomJS binary or FALSE if not found.
*/
function _phantomjs_capture_get_binray() {
$binary = variable_get('phantomjs_capture_binary', '/usr/local/bin/phantomjs');
if (!file_exists($binary)) {
return FALSE;
}
return $binary;
}
/**
* Captures a screenshot using PhantomJS by calling the program.
*
* #param string $url
* The ULR/http(s) to render the screenshot from.
* #param type $dest
* The destionation for the rendered file (e.g. public://fecthed_images).
* #param type $filename
* The filename to store the file as in the destination.
* #param type $element
* The id of the DOM element to render in the document.
* #return boolean
* Returns TRUE if the screenshot was taken else FALSE on error.
*/
function phantomjs_capture_screen($url, $dest, $filename, $element = NULL) {
// Get PhantomJS binary.
$binary = _phantomjs_capture_get_binray();
if (!$binary) {
drupal_set_message(t('PhantomJS binary was not found. Plase intall PhantomJS on the system.'));
return FALSE;
}
// Check that destination is writeable.
if (!file_prepare_directory($dest, FILE_CREATE_DIRECTORY)) {
drupal_set_message(t('The PhantomJS destination path (#dest) was not writeable or could not be created.', array(
'#dest' => $dest,
)));
return FALSE;
}
// Get absolute path to PhantomJS script and the destionation file.
$script = realpath(variable_get('phantomjs_capture_script', drupal_get_path('module', 'phantomjs_capture') . '/js/phantomjs_capture.js'));
$dest = drupal_realpath($dest . '/' . $filename);
// Run PhantomJS to create the screen shot.
$output = array();
if ($element) {
exec($binary . ' ' . $script . ' ' . $url . ' ' . $dest . ' ' . escapeshellarg($element), $output);
} else {
exec($binary . ' ' . $script . ' ' . $url . ' ' . $dest, $output);
}
// Check that PhantomJS was able to load the page.
if ($output[0] == '500') {
return FALSE;
}
return TRUE;
}
/**
* Implements hook_block_info().
*/
function phantomjs_capture_block_info() {
$blocks = array();
$blocks['Scraping Block'] = array(
'info' => t('scraping block'),
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function phantomjs_capture_block_view($delta = '') {
$block = array();
switch ($delta) {
case 'Scraping Block':
$block['subject'] = 'Scraper';
$block['content'] = phantomjs_capture_admin_form();
break;
}
return $block;
}
I got the solution on a different website provided by #zaporylie. The problem wasn my approach to the problem. In short, he suggested to create a new custom module dependent on PhantomJS Capture and then to declare a block.
Here's working code:
phantomjs_capture_block.info
name = PhantomJS Capture Block
description = Adds block with simple form.
core = 7.x
package = Other
dependencies[] = phantomjs_capture
phantomjs_capture_block.module
<?php
/**
* #file
* Simple form placed in block.
*/
/**
* Implements hook_block_info().
*/
function phantomjs_capture_block_block_info() {
$blocks['screenshot'] = array(
'info' => t('Screenshot'),
'cache' => DRUPAL_NO_CACHE,
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function phantomjs_capture_block_block_view($delta = '') {
$block = array();
if ($delta === 'screenshot') {
$block['title'] = t('Screenshot');
$block['content'] = drupal_get_form('phantomjs_capture_block_form');
}
return $block;
}
/**
* Simple form.
*/
function phantomjs_capture_block_form($form, &$form_state) {
$form['url'] = array(
'#type' => 'textfield',
'#title' => t('URL'),
'#ajax' => array(
'callback' => 'phantomjs_capture_block_form_callback',
'wrapper' => 'phantomjs-capture-block-form-preview',
'method' => 'replace',
),
);
$form['preview'] = array(
'#type' => 'container',
'#attributes' => array(
'id' => 'phantomjs-capture-block-form-preview',
),
);
if (!empty($form_state['values']['url'])) {
$directory = 'public://';
$filename = REQUEST_TIME . '.png';
if (phantomjs_capture_screen($form_state['values']['url'], $directory, $filename)) {
$form['preview']['image'] = array(
'#theme' => 'image',
'#path' => $directory . '/' . $filename,
'#width' => '100%',
);
}
else {
drupal_set_message(t('Unable to create screenshot'), 'error');
}
}
return $form;
}
function phantomjs_capture_block_form_callback($form, $form_state) {
return $form['preview'];
}

ACL not working for some controller which have upload component & imageresize component in cakephp

My cakephp version is 1.3.10, I have added acl component for assign authorize policy.
Its working fine for all controller. But in two controller I have added Upload component (For upload files) and Image Resize component (For resize image)
var $components = array('Upload','ImageResize');
When i try to access my controller AffiliatesController and AwardsController it going in loop and i get error: page is not redirect properly.
If i commented those component then its working fine. Can anyone suggest me what is the issue?
My acl controller is looks like below,
<?php
class AclController extends AppController {
var $name = 'Aco';
var $components = array('Acl');
function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('*');
}
function build_aco() {
error_reporting(0);
if (!Configure::read('debug')) {
return $this->_stop();
}
$log = array();
$aco = $this->Acl->Aco;
$root = $aco->node('controllers');
if (!$root) {
$aco->create(array('parent_id' => null, 'model' => null, 'alias' => 'controllers'));
$root = $aco->save();
$root['Aco']['id'] = $aco->id;
$log[] = 'Created Aco node for controllers';
} else {
$root = $root[0];
}
App::import('Core', 'File');
$Controllers = App::objects('controller');
$appIndex = array_search('App', $Controllers);
if ($appIndex !== false ) {
unset($Controllers[$appIndex]);
}
$baseMethods = get_class_methods('Controller');
$baseMethods[] = 'build_acl';
$Plugins = $this->_getPluginControllerNames();
$Controllers = array_merge($Controllers, $Plugins);
// look at each controller in app/controllers
foreach ($Controllers as $ctrlName) {
$methods = $this->_getClassMethods($this->_getPluginControllerPath($ctrlName));
// Do all Plugins First
if ($this->_isPlugin($ctrlName)){
$pluginNode = $aco->node('controllers/'.$this->_getPluginName($ctrlName));
if (!$pluginNode) {
$aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $this->_getPluginName($ctrlName)));
$pluginNode = $aco->save();
$pluginNode['Aco']['id'] = $aco->id;
$log[] = 'Created Aco node for ' . $this->_getPluginName($ctrlName) . ' Plugin';
}
}
// find / make controller node
$controllerNode = $aco->node('controllers/'.$ctrlName);
if (!$controllerNode) {
if ($this->_isPlugin($ctrlName)){
$pluginNode = $aco->node('controllers/' . $this->_getPluginName($ctrlName));
$aco->create(array('parent_id' => $pluginNode['0']['Aco']['id'], 'model' => null, 'alias' => $this->_getPluginControllerName($ctrlName)));
$controllerNode = $aco->save();
$controllerNode['Aco']['id'] = $aco->id;
$log[] = 'Created Aco node for ' . $this->_getPluginControllerName($ctrlName) . ' ' . $this->_getPluginName($ctrlName) . ' Plugin Controller';
} else {
$aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $ctrlName));
$controllerNode = $aco->save();
$controllerNode['Aco']['id'] = $aco->id;
$log[] = 'Created Aco node for ' . $ctrlName;
}
} else {
$controllerNode = $controllerNode[0];
}
//clean the methods. to remove those in Controller and private actions.
foreach ($methods as $k => $method) {
if (strpos($method, '_', 0) === 0) {
unset($methods[$k]);
continue;
}
if (in_array($method, $baseMethods)) {
unset($methods[$k]);
continue;
}
$methodNode = $aco->node('controllers/'.$ctrlName.'/'.$method);
if (!$methodNode) {
$aco->create(array('parent_id' => $controllerNode['Aco']['id'], 'model' => null, 'alias' => $method));
$methodNode = $aco->save();
$log[] = 'Created Aco node for '. $method;
}
}
}
if(count($log)>0) {
debug($log);
}
exit;
}
function _getClassMethods($ctrlName = null) {
App::import('Controller', $ctrlName);
if (strlen(strstr($ctrlName, '.')) > 0) {
// plugin's controller
$num = strpos($ctrlName, '.');
$ctrlName = substr($ctrlName, $num+1);
}
$ctrlclass = $ctrlName . 'Controller';
$methods = get_class_methods($ctrlclass);
// Add scaffold defaults if scaffolds are being used
$properties = get_class_vars($ctrlclass);
if (array_key_exists('scaffold',$properties)) {
if($properties['scaffold'] == 'admin') {
$methods = array_merge($methods, array('admin_add', 'admin_edit', 'admin_index', 'admin_view', 'admin_delete'));
} else {
$methods = array_merge($methods, array('add', 'edit', 'index', 'view', 'delete'));
}
}
return $methods;
}
function _isPlugin($ctrlName = null) {
$arr = String::tokenize($ctrlName, '/');
if (count($arr) > 1) {
return true;
} else {
return false;
}
}
function _getPluginControllerPath($ctrlName = null) {
$arr = String::tokenize($ctrlName, '/');
if (count($arr) == 2) {
return $arr[0] . '.' . $arr[1];
} else {
return $arr[0];
}
}
function _getPluginName($ctrlName = null) {
$arr = String::tokenize($ctrlName, '/');
if (count($arr) == 2) {
return $arr[0];
} else {
return false;
}
}
function _getPluginControllerName($ctrlName = null) {
$arr = String::tokenize($ctrlName, '/');
if (count($arr) == 2) {
return $arr[1];
} else {
return false;
}
}
/**
* Get the names of the plugin controllers ...
*
* This function will get an array of the plugin controller names, and
* also makes sure the controllers are available for us to get the
* method names by doing an App::import for each plugin controller.
*
* #return array of plugin names.
*
*/
function _getPluginControllerNames() {
App::import('Core', 'File', 'Folder');
$paths = Configure::getInstance();
$folder =& new Folder();
$folder->cd(APP . 'plugins');
// Get the list of plugins
$Plugins = $folder->read();
$Plugins = $Plugins[0];
$arr = array();
// Loop through the plugins
foreach($Plugins as $pluginName) {
// Change directory to the plugin
$didCD = $folder->cd(APP . 'plugins'. DS . $pluginName . DS . 'controllers');
// Get a list of the files that have a file name that ends
// with controller.php
$files = $folder->findRecursive('.*_controller\.php');
// Loop through the controllers we found in the plugins directory
foreach($files as $fileName) {
// Get the base file name
$file = basename($fileName);
// Get the controller name
$file = Inflector::camelize(substr($file, 0, strlen($file)-strlen('_controller.php')));
if (!preg_match('/^'. Inflector::humanize($pluginName). 'App/', $file)) {
if (!App::import('Controller', $pluginName.'.'.$file)) {
debug('Error importing '.$file.' for plugin '.$pluginName);
} else {
/// Now prepend the Plugin name ...
// This is required to allow us to fetch the method names.
$arr[] = Inflector::humanize($pluginName) . "/" . $file;
}
}
}
}
#echo "<pre>";
#print_r ($arr);exit;
return $arr;
}
/**
* Setting up permissions, To allow ARO's access to ACO's
*/
function build_permission() {
$group =& $this->User->Group;
//Allow developers to everything
$group->id = 1;
$this->Acl->allow(array('model' => 'Group', 'foreign_key' => 1), 'controllers');
//Allow administrator to everything except "Admin Groups", "Payment Gateways"
$group->id = 2;
$this->Acl->allow(array('model' => 'Group', 'foreign_key' => 2), 'controllers');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Groups');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Users/view');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Users/add');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Users/edit');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Users/delete');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Staticpages');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Cmstags');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Cmstagpositions');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Cmspages');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Emailtemplates');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Affiliates');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Awards');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Faqs');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Newsletters');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Newslettersubscribers');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Packages');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Transactions');
$this->Acl->deny(array('model' => 'Group', 'foreign_key' => 2), 'controllers/Testimonials');
//we add an exit to avoid an ugly "missing views" error message
echo "all done";
exit;
}
}
?>

Magento Grid : Better way of using addColumn Actions?

This function sets up the Magento Grid to display a list of filenames with a corresponding 'Delete' action.
The problem is the Delete action never passes the parameter, 'filename.' (See http://www.premasolutions.com/content/magento-manage-category-product-grid-edit-link) I have TESTDUMP for verification but it never prints on the next page.
Is 'params' a legitimate action of 'addColumn->actions->url'?
Update: Added the construct and prepare collection for controller. Maybe it's because of the type of Collection I'm using?
class Rogue_Googlemerchant_Block_Adminhtml_Exporter_Grid
Rogue_Googlemerchant_Block_Adminhtml_Exporter_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
public function __construct()
{
parent::__construct();
$this->setId('googlemerchantGrid');
// This is the primary key of the database
$this->setDefaultSort('filename');
$this->setDefaultDir('ASC');
$this->setSaveParametersInSession(true);
}
protected function _prepareCollection()
{
$basePath = Mage::getBaseDir('base');
$feedPath = $basePath . '/opt/googlemerchant/';
$errPath = $basePath . '/var/log/googlemerchant/';
$flocal = new Varien_Io_File();
$flocal->open(array('path' => $feedPath));
$dataCollection = new Varien_Data_Collection();
foreach ($flocal->ls() as $item) {
$dataObject = new Varien_Object();
$dataObject->addData(
array(
'filename' => $item['text'],
'size' => $item['size'] / 1000 . ' kb',
'date_modified'=> $item['mod_date']
)
);
$dataCollection->addItem($dataObject);
}
$this->setCollection($dataCollection);
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
$this->addColumn('filename', array(
'header' => Mage::helper('googlemerchant')->__('File'),
'align' =>'left',
'index' => 'filename',
'width' => '200px',
));
$this->addColumn('action', array(
'header' => Mage::helper('googlemerchant')->__('Action'),
'width' => '50px',
'type' => 'action',
// 'getter' => 'getId',
'actions' => array(
array(
'caption' => Mage::helper('googlemerchant')->__('Delete'),
'url' =>
array(
'base' => '*/*/delete',
'params' => array('filename' => 'TESTDUMP')
),
'field' => 'filename'
)
),
'filter' => false,
'sortable' => false,
// 'index' => 'filename',
// 'is_system' => true,
));
}
}
class Rogue_Googlemerchant_Adminhtml_ExporterController
class Rogue_Googlemerchant_Adminhtml_ExporterController extends Mage_Adminhtml_Controller_Action
{
public function deleteAction()
{
$filename = $this->getRequest()->getParam('filename');
$basePath = Mage::getBaseDir('base');
$feedPath = $basePath . '/opt/googlemerchant/';
$errPath = $basePath . '/var/log/googlemerchant/';
$flocal = new Varien_Io_File();
$flocal->open(array('path' => $feedPath));
d($filename);
if ($filename) {
try{
$flocal->rm($filename);
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('googlemerchant')->__('The file has been deleted.'));
$this->_redirect('*/*/');
}
catch (Mage_Core_Exception $e) {
$this->log($e);
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/index');
return;
}
}
die('here');
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Unable to find the file to delete.'));
$this->_redirect('*/*/');
}
}
The getter of the action column is used on the collection items to retrieve the argument value for the field parameter.
I'm not sure why you are specifying the filename hardcoded or if that should work, but if you add the column configuration
'getter' => 'getFilename'
and remove the params from the action it should work.

Categories