Creating a block using PhantomJS Capture module - php

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'];
}

Related

Converting module Drupal7 to Drupal8

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.

How to insert an image in a template using HelperForm?

I am creating a custom module using PrestaShop 1.7 and I want to be be able to upload an image for the background. The image should be displayed if the field background_image is defined.
I am able to do it, but the image is outside of the form, as you can see in the image below.
The image should be displayed immediately above the background image field, like this (see below).
Here is my .tpl file:
{if isset($background_image)}
<div>
<div class="col-lg-3"></div>
<div>
<img src="/modules/cb_sectionaboutus/img/{$background_image}" class="img-thumbnail" width="400" />
</div>
</div>
{/if}
And here is part of the main PHP file of the module:
/**
* Load the configuration form
*/
public function getContent()
{
/**
* If values have been submitted in the form, process.
*/
if (((bool)Tools::isSubmit('submitCb_sectionaboutusModule')) == true) {
$this->postProcess();
}
$this->context->smarty->assign('module_dir', $this->_path);
/* Passes the background image to the template */
$data = $this->getDataFromDB();
$background_image = $data['background_image'];
$this->context->smarty->assign('background_image', $background_image);
// About section & Documentation
$output = $this->context->smarty->fetch($this->local_path.'views/templates/admin/configure.tpl');
return $output.$this->renderForm();
}
/**
* Create the form that will be displayed in the configuration of your module.
*/
protected function renderForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->module = $this;
$helper->default_form_language = $this->context->language->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitCb_sectionaboutusModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
.'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id
);
return $helper->generateForm(array($this->getConfigForm()));
}
/**
* Create the structure of your form.
*/
protected function getConfigForm()
{
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'textarea',
'label' => $this->l('Title'),
'name' => 'title',
'desc' => $this->l('Enter the title'),
'class' => 'rte',
'autoload_rte' => true
),
array(
'type' => 'file',
'label' => $this->l('Background Image'),
'name' => 'background_image',
'desc' => $this->l('Maximum image size: ') . $this->upload_file_size_limit_in_mb . ' MB.',
'display_image' => true
)
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
}
/**
* Set values for the inputs.
*/
protected function getConfigFormValues()
{
$data = $this->getDataFromDB();
return array(
'title' => $data['title'],
'background_image' => $data['background_image']
);
}
/**
* Get the data from the database
*/
public function getDataFromDB()
{
$sql = 'SELECT * FROM ' . _DB_PREFIX_ . $this->name . ' WHERE id_' . $this->name . ' = ' . 1;
return Db::getInstance()->ExecuteS($sql)[0];
}
/**
* Save form data.
*/
protected function postProcess()
{
/* Current data */
$data_from_db = $this->getDataFromDB();
/* New data */
$form_values = $this->getConfigFormValues();
/* Sets the background image as the old value, in case there is no new upload */
$form_values['background_image'] = $data_from_db['background_image'];
/* Validates the background image file */
$file_name = $this->validateFile();
/* Checks whether the background image has been successfully uploaded */
if ($file_name) {
/* Sets the new background image */
$form_values['background_image'] = $file_name;
}
// Has rows in table --> UPDATE
if ($data_from_db) {
$sql = $sql = "UPDATE " . _DB_PREFIX_ . $this->name . " SET ";
foreach (array_keys($form_values) as $key) {
$sql .= $key . " = '" . $form_values[$key] . "', ";
}
$sql = trim($sql, " "); // first trim last space
$sql = trim($sql, ","); // then trim trailing and prefixing commas
$sql .= " WHERE id_" . $this->name . " = " . 1;
}
// No rows in table --> INSERT
else {
$columns = "id_cb_sectionaboutus, " . implode(", ", array_keys($form_values));
$values = array_map('Tools::getValue', array_keys($form_values));
$values = "1, " . "'" . implode("', '", array_values($values)) . "'";
$sql = 'INSERT INTO ' . _DB_PREFIX_ . $this->name . ' (' . $columns . ') VALUES (' . $values . ')';
}
Db::getInstance()->ExecuteS($sql);
}
How can I insert the uploaded image in the middle of the form using HelperForm?
I would prefer a solution with HelperForm, but I don't know if it works, so I will accept any answer tha gives me a good solution.
PHP file - getConfigForm function
protected function getConfigForm()
{
// ADDED THESE LINES
$image = '';
$background_image = $this->getDataFromDB()['background_image'];
if ($background_image) {
$image_url = $background_image ? '/modules/cb_sectionaboutus/img/' . $background_image : '';
$image = '<div class="col-lg-6"><img src="' . $image_url . '" class="img-thumbnail" width="400"></div>';
}
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'file',
'label' => $this->l('Background Image'),
'name' => 'background_image',
'desc' => $this->l('Maximum image size: ') . $this->upload_file_size_limit_in_mb . ' MB.',
'display_image' => true,
'image' => $image // ADDED THIS OPTION
),
array(
'type' => 'textarea',
'label' => $this->l('Title'),
'name' => 'title',
'desc' => $this->l('Enter the title'),
'class' => 'rte',
'autoload_rte' => true
)
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
}
and remove everything from the template.

Drupal 8 Custom Field // Primitive error

I see text field and ckeditor field on node edit page, but when i try to save node i receive "This value should be of the correct primitive type. " error.
<?php
namespace Drupal\custom_field\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;
/**
* Plugin implementation of the 'Program' field type.
*
* #FieldType(
* id = "program",
* label = #Translation("Programmation"),
* description = #Translation("Stores a Program n date string in various format"),
* default_widget = "program_default",
* default_formatter = "program_default",
* )
*/
class ProgramItem extends FieldItemBase implements FieldItemInterface {
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return array(
'columns' => array(
'date' => array(
'description' => 'Programmation du jour.(date)',
'type' => 'varchar',
'length' => 255,
'size' => 'normal',
),
'programmation' => array(
'description' => 'Programmation. (Concerts)',
'type' => 'varchar',
'length' => 5000,
'size' => 'normal',
),
),
);
}
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['date'] = DataDefinition::create('string')
->setLabel(t('Date du jour'));
$properties['programmation'] = DataDefinition::create('string')
->setLabel(t('Programmation du jour'));
return $properties;
}
public function isEmpty() {
$value = $this->get('date')->getValue();
return empty($value);
}
public static function mainPropertyName() {
return 'date';
}
}
<?php
namespace Drupal\custom_field\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Field\WidgetBaseInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'Program' widget.
*
* #FieldWidget(
* id = "program_default",
* label = #Translation("Programmation"),
* field_types = {
* "program"
* }
* )
*/
class ProgramWidget extends WidgetBase implements WidgetBaseInterface {
/**
* #param FieldItemListInterface $items
* #param int $delta
* #param array $element
* #param array $form
* #param FormStateInterface $form_state
* #return array
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element['date'] = array(
'#type' => 'textfield',
'#title' => $this->t('Date'),
'#placeholder' => $this->getSetting('placeholder_date'),
'#default_value' => isset($items[$delta]->date) ? $items[$delta]->date : NULL,
'#required' => $element['#required'],
);
$element['programmation'] = array(
'#type' => 'text_format',
'#title' => $this->t('Programmation'),
'#placeholder' => $this->getSetting('placeholder_programmation'),
'#default_value' => isset($items[$delta]->programmation) ? $items[$delta]->programmation : NULL,
'#format' => 'full_html',
);
$element['field_widget_display']['#access'] = true;
$element['field_widget_display_settings']['#access'] = true;
die('ProgramWidget');
return $element;
}
}
I saw that I could use the massageFormValues () method in WidgetBase, but I do not know how to use it.
A little help would be welcome.
Thank you
finaly i add to ProgramWidget :
/**
* {#inheritdoc}
*/
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
foreach ($values as &$value) {
if (count($value['programmation'])) {
$value['programmation'] = $value['programmation']['value'];
} else {
$value['programmation'] = $value['programmation'] !== '' ? $value['programmation'] : '0';
}
}
return $values;
}
}
And now it s working
it seems because of
$element['programmation'] = array(
'#type' => 'text_format',
'#title' => $this->t('Programmation'),
'#placeholder' => $this->getSetting('placeholder_programmation'),
'#default_value' => isset($items[$delta]->programmation) ? $items[$delta]->programmation : NULL,
'#format' => 'full_html',
);
but i don't know how override method massageFormValues ..?

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'];
}

Magento - Can't upload files in custom module

I'm editing a custom plugin in magento in which I need add a field to upload an image and save it's path in the database together with other data. The form works fine with the additional data, as well as the database recording. However, it seems that the $_FILES variable always return empty. What is more curious is that an file called "cache_2ca019d1e2db75b611e5f3aa5c932970" is always generated in the media directory every time I try to upload an image in my module.
I've found people with similar problems here, but none of the presented solutions worked for me. I'm lost =/
This is my Form file:
<?php
class SmashingMagazine_BrandDirectory_Block_Adminhtml_Brand_Edit_Form
extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
// instantiate a new form to display our brand for editing
$form = new Varien_Data_Form(array(
'id' => 'edit_form',
'action' => $this->getUrl(
'smashingmagazine_branddirectory_admin/brand/edit',
array(
'_current' => true,
'continue' => 0,
)
),
'method' => 'post',
'enctype' => 'multipart/form-data'
));
$form->setUseContainer(true);
$this->setForm($form);
// define a new fieldset, we only need one for our simple entity
$fieldset = $form->addFieldset(
'general',
array(
'legend' => $this->__('Brand Details')
)
);
$brandSingleton = Mage::getSingleton(
'smashingmagazine_branddirectory/brand'
);
// add the fields we want to be editable
$this->_addFieldsToFieldset($fieldset, array(
'name' => array(
'label' => $this->__('Name'),
'input' => 'text',
'required' => true,
),
'url_key' => array(
'label' => $this->__('URL Key'),
'input' => 'text',
'required' => true,
),
'image' => array(
'label' => $this->__('Image'),
'input' => 'image',
'required' => true,
'disabled' => false,
'readonly' => true,
),
'visibility' => array(
'label' => $this->__('Visibility'),
'input' => 'select',
'required' => true,
'options' => $brandSingleton->getAvailableVisibilies(),
),
/**
* Note: we have not included created_at or updated_at,
* we will handle those fields ourself in the Model before save.
*/
));
return $this;
}
/**
* This method makes life a little easier for us by pre-populating
* fields with $_POST data where applicable and wraps our post data in
* 'brandData' so we can easily separate all relevant information in
* the controller. You can of course omit this method entirely and call
* the $fieldset->addField() method directly.
*/
protected function _addFieldsToFieldset(
Varien_Data_Form_Element_Fieldset $fieldset, $fields)
{
$requestData = new Varien_Object($this->getRequest()
->getPost('brandData'));
foreach ($fields as $name => $_data) {
if ($requestValue = $requestData->getData($name)) {
$_data['value'] = $requestValue;
}
// wrap all fields with brandData group
$_data['name'] = "brandData[$name]";
// generally label and title always the same
$_data['title'] = $_data['label'];
// if no new value exists, use existing brand data
if (!array_key_exists('value', $_data)) {
$_data['value'] = $this->_getBrand()->getData($name);
}
// finally call vanilla functionality to add field
$fieldset->addField($name, $_data['input'], $_data);
}
return $this;
}
/**
* Retrieve the existing brand for pre-populating the form fields.
* For a new brand entry this will return an empty Brand object.
*/
protected function _getBrand()
{
if (!$this->hasData('brand')) {
// this will have been set in the controller
$brand = Mage::registry('current_brand');
// just in case the controller does not register the brand
if (!$brand instanceof
SmashingMagazine_BrandDirectory_Model_Brand) {
$brand = Mage::getModel(
'smashingmagazine_branddirectory/brand'
);
}
$this->setData('brand', $brand);
}
return $this->getData('brand');
}
}
And this is my Controller File:
<?php
class SmashingMagazine_BrandDirectory_Adminhtml_BrandController
extends Mage_Adminhtml_Controller_Action
{
/**
* Instantiate our grid container block and add to the page content.
* When accessing this admin index page we will see a grid of all
* brands currently available in our Magento instance, along with
* a button to add a new one if we wish.
*/
public function indexAction()
{
// instantiate the grid container
$brandBlock = $this->getLayout()
->createBlock('smashingmagazine_branddirectory_adminhtml/brand');
// add the grid container as the only item on this page
$this->loadLayout()
->_addContent($brandBlock)
->renderLayout();
}
/**
* This action handles both viewing and editing of existing brands.
*/
public function editAction()
{
/**
* retrieving existing brand data if an ID was specified,
* if not we will have an empty Brand entity ready to be populated.
*/
$brand = Mage::getModel('smashingmagazine_branddirectory/brand');
if ($brandId = $this->getRequest()->getParam('id', false)) {
$brand->load($brandId);
if ($brand->getId() < 1) {
$this->_getSession()->addError(
$this->__('This brand no longer exists.')
);
return $this->_redirect(
'smashingmagazine_branddirectory_admin/brand/index'
);
}
}
// process $_POST data if the form was submitted
if ($postData = $this->getRequest()->getPost('brandData')) {
try {
// image upload
if(isset($_FILES['image']['name']) and (file_exists($_FILES['image']['tmp_name'])))
{
try
{
$path = Mage::getBaseDir('media') . DS . 'banner' . DS;
$uploader = new Varien_File_Uploader('image');
$uploader
->setAllowedExtensions(array('jpg','png','gif','jpeg'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$destFile = $path.$_FILES[$image]['name'];
$filename = $uploader->getNewFileName($destFile);
$uploader->save($path, $filename);
$data['img'] = $_FILES['image']['name'];
}
catch(Exception $e)
{
}
}
else
{
if(isset($data['image']['delete']) && $postData['image']['delete'] == 1)
$data['image'] = '';
else
unset($data['image']);
}
// continue
$brand->addData($postData);
$brand->save();
$this->_getSession()->addSuccess(
$this->__($_FILES['image']['name'])
);
// redirect to remove $_POST data from the request
return $this->_redirect(
'smashingmagazine_branddirectory_admin/brand/edit',
array('id' => $brand->getId())
);
} catch (Exception $e) {
Mage::logException($e);
$this->_getSession()->addError($e->getMessage());
}
/**
* if we get to here then something went wrong. Continue to
* render the page as before, the difference being this time
* the submitted $_POST data is available.
*/
}
// make the current brand object available to blocks
Mage::register('current_brand', $brand);
// instantiate the form container
$brandEditBlock = $this->getLayout()->createBlock(
'smashingmagazine_branddirectory_adminhtml/brand_edit'
);
// add the form container as the only item on this page
$this->loadLayout()
->_addContent($brandEditBlock)
->renderLayout();
}
public function deleteAction()
{
$brand = Mage::getModel('smashingmagazine_branddirectory/brand');
if ($brandId = $this->getRequest()->getParam('id', false)) {
$brand->load($brandId);
}
if ($brand->getId() < 1) {
$this->_getSession()->addError(
$this->__('This brand no longer exists.')
);
return $this->_redirect(
'smashingmagazine_branddirectory_admin/brand/index'
);
}
try {
$brand->delete();
$this->_getSession()->addSuccess(
$this->__('The brand has been deleted.')
);
} catch (Exception $e) {
Mage::logException($e);
$this->_getSession()->addError($e->getMessage());
}
return $this->_redirect(
'smashingmagazine_branddirectory_admin/brand/index'
);
}
/**
* Thanks to Ben for pointing out this method was missing. Without
* this method the ACL rules configured in adminhtml.xml are ignored.
*/
protected function _isAllowed()
{
/**
* we include this switch to demonstrate that you can add action
* level restrictions in your ACL rules. The isAllowed() method will
* use the ACL rule we have configured in our adminhtml.xml file:
* - acl
* - - resources
* - - - admin
* - - - - children
* - - - - - smashingmagazine_branddirectory
* - - - - - - children
* - - - - - - - brand
*
* eg. you could add more rules inside brand for edit and delete.
*/
$actionName = $this->getRequest()->getActionName();
switch ($actionName) {
case 'index':
case 'edit':
case 'delete':
// intentionally no break
default:
$adminSession = Mage::getSingleton('admin/session');
$isAllowed = $adminSession
->isAllowed('smashingmagazine_branddirectory/brand');
break;
}
return $isAllowed;
}
}
Thanks in advance.
// add the fields we want to be editable
$this->_addFieldsToFieldset($fieldset, array(
'name' => array(
'label' => $this->__('Name'),
'input' => 'text',
'required' => true,
),
'url_key' => array(
'label' => $this->__('URL Key'),
'input' => 'text',
'required' => true,
),
'image' => array(
'label' => $this->__('Image'),
'input' => 'image',
'name' => 'image',
'required' => true,
'disabled' => false,
),
'visibility' => array(
'label' => $this->__('Visibility'),
'input' => 'select',
'required' => true,
'options' => $brandSingleton->getAvailableVisibilies(),
),
/**
* Note: we have not included created_at or updated_at,
* we will handle those fields ourself in the Model before save.
*/
));
Try this by adding name attribute on image.

Categories