Wordpress + Elementor: cyrillic in PDF - php

To generate a PDF file with data from the submitted form, I use Dynamic Content PDF Generator for Elementor Pro Form. The problem is with Cyrillic characters - they are displayed in the created pdf file as question marks. The file «DCE_Extension_Form_PDF.php» contains the following code:
<?php
namespace DynamicContentForElementor\Extensions;
use Elementor\Controls_Manager;
use DynamicContentForElementor\DCE_Helper;
use DynamicContentForElementor\DCE_Tokens;
if (!defined('ABSPATH'))
exit; // Exit if accessed directly
function _dce_extension_form_pdf($field) {
switch ($field) {
case 'enabled':
return true;
case 'docs':
return 'https://www.dynamic.ooo/widget/pdf-generator-for-elementor-pro-form/';
case 'description' :
return __('Add PDF Creation Actions to Elementor PRO Form', 'dynamic-content-for-elementor');
}
}
if (!DCE_Helper::is_plugin_active('elementor-pro') || !class_exists('ElementorPro\Modules\Forms\Classes\Action_Base')) {
class DCE_Extension_Form_PDF extends DCE_Extension_Prototype {
public $name = 'Form PDF';
private $is_common = false;
public static $depended_plugins = ['elementor-pro'];
static public function is_enabled() {
return _dce_extension_form_pdf('enabled');
}
public static function get_description() {
return _dce_extension_form_pdf('description');
}
public function get_docs() {
return _dce_extension_form_pdf('docs');
}
}
} else {
class DCE_Extension_Form_PDF extends \ElementorPro\Modules\Forms\Classes\Action_Base {
public $name = 'Form PDF';
public static $depended_plugins = ['elementor-pro'];
public $has_action = true;
static public function is_enabled() {
return _dce_extension_form_pdf('enabled');
}
public static function get_description() {
return _dce_extension_form_pdf('description');
}
public function get_docs() {
return _dce_extension_form_pdf('docs');
}
public static function get_plugin_depends() {
return self::$depended_plugins;
}
static public function get_satisfy_dependencies($ret = false) {
return true;
}
public function get_script_depends() {
return [];
}
public function get_style_depends() {
return [];
}
/**
* Get Name
*
* Return the action name
*
* #access public
* #return string
*/
public function get_name() {
return 'dce_form_pdf';
}
/**
* Get Label
*
* Returns the action label
*
* #access public
* #return string
*/
public function get_label() {
return __('PDF', 'dynamic-content-for-elementor');
}
/**
* Register Settings Section
*
* Registers the Action controls
*
* #access public
* #param \Elementor\Widget_Base $widget
*/
public function register_settings_section($widget) {
$widget->start_controls_section(
'section_dce_form_pdf',
[
'label' => $this->get_label(), //__('DCE', 'dynamic-content-for-elementor'),
'condition' => [
'submit_actions' => $this->get_name(),
],
]
);
$widget->add_control(
'dce_form_pdf_name', [
'label' => __('Name', 'dynamic-content-for-elementor'),
'type' => Controls_Manager::TEXT,
'default' => '[date|U]',
'description' => __('The PDF file name, the .pdf extension will automatically added', 'dynamic-content-for-elementor'),
'label_block' => true,
]
);
$widget->add_control(
'dce_form_pdf_folder', [
'label' => __('Folder', 'dynamic-content-for-elementor'),
'type' => Controls_Manager::TEXT,
'default' => 'elementor/pdf/[date|Y]/[date|m]',
'description' => __('The directory inside /wp-content/uploads/xxx where save the PDF file', 'dynamic-content-for-elementor'),
'label_block' => true,
]
);
$widget->add_control(
'dce_form_pdf_template',
[
'label' => __('Template', 'dynamic-content-for-elementor'),
'type' => 'ooo_query',
'placeholder' => __('Template Name', 'dynamic-content-for-elementor'),
'label_block' => true,
'query_type' => 'posts',
'object_type' => 'elementor_library',
'description' => __('Use a Elementor Template as body fo this PDF', 'dynamic-content-for-elementor'),
]
);
$paper_sizes = array_keys(\Dompdf\Adapter\CPDF::$PAPER_SIZES);
$tmp = array();
foreach ($paper_sizes as $asize) {
$tmp[$asize] = strtoupper($asize);
}
$paper_sizes = $tmp;
$widget->add_control(
'dce_form_pdf_size',
[
'label' => __('Page Size', 'dynamic-content-for-elementor'),
'type' => Controls_Manager::SELECT,
'default' => 'a4',
'options' => $paper_sizes,
]
);
$widget->add_control(
'dce_form_pdf_orientation', [
'label' => __('Page Orientation', 'dynamic-content-for-elementor'),
'type' => Controls_Manager::CHOOSE,
'options' => [
'portrait' => [
'title' => __('Portrait', 'dynamic-content-for-elementor'),
'icon' => 'fa fa-arrows-v',
],
'landscape' => [
'title' => __('Landscape', 'dynamic-content-for-elementor'),
'icon' => 'fa fa-arrows-h',
]
],
'toggle' => false,
'default' => 'portrait',
]
);
$widget->add_control(
'dce_form_pdf_margin', [
'label' => __('Page Margin', 'dynamic-content-for-elementor'),
'type' => Controls_Manager::DIMENSIONS,
'size_units' => ['px', '%', 'em'],
]
);
$widget->add_control(
'dce_form_section_page', [
'label' => __('Sections Page', 'dynamic-content-for-elementor'),
'type' => Controls_Manager::SWITCHER,
'description' => __('Force every Template Section in a new page', 'dynamic-content-for-elementor'),
]
);
/*$widget->add_control(
'dce_form_pdf_background',
[
'label' => __('background', 'elementor'),
'type' => Controls_Manager::MEDIA,
'dynamic' => [
'active' => true,
'categories' => $refl->getConstants(),
],
'placeholder' => __('Select condition field', 'elementor'),
]
);*/
$widget->add_control(
'dce_form_pdf_save', [
'label' => __('Save', 'dynamic-content-for-elementor'),
'type' => Controls_Manager::SWITCHER,
'description' => __('Save the generated PDF file as Media', 'dynamic-content-for-elementor'),
]
);
$widget->add_control(
'dce_form_pdf_title', [
'label' => __('Title', 'dynamic-content-for-elementor'),
'type' => Controls_Manager::TEXT,
'default' => 'Form data by [field id="name"] in [date|Y-m-d H:i:s]',
'description' => __('The PDF file Title', 'dynamic-content-for-elementor'),
'label_block' => true,
'condition' => [
'dce_form_pdf_save!' => '',
],
]
);
$widget->add_control(
'dce_form_pdf_content', [
'label' => __('Description', 'dynamic-content-for-elementor'),
'type' => Controls_Manager::TEXT,
'default' => '[field id="message"]',
'description' => __('The PDF file Description', 'dynamic-content-for-elementor'),
'label_block' => true,
'condition' => [
'dce_form_pdf_save!' => '',
],
]
);
$widget->add_control(
'dce_form_pdf_help', [
'type' => \Elementor\Controls_Manager::RAW_HTML,
'raw' => '<div id="elementor-panel__editor__help" class="p-0"><a id="elementor-panel__editor__help__link" href="'.$this->get_docs().'" target="_blank">'.__( 'Need Help', 'elementor' ).' <i class="eicon-help-o"></i></a></div>',
'separator' => 'before',
]
);
$widget->end_controls_section();
}
/**
* Run
*
* Runs the action after submit
*
* #access public
* #param \ElementorPro\Modules\Forms\Classes\Form_Record $record
* #param \ElementorPro\Modules\Forms\Classes\Ajax_Handler $ajax_handler
*/
public function run($record, $ajax_handler) {
$settings = $record->get('form_settings');
$fields = DCE_Helper::get_form_data($record);
$settings = DCE_Helper::get_dynamic_value($settings, $fields);
$this->dce_elementor_form_pdf($fields, $settings, $ajax_handler);
}
/**
* On Export
*
* Clears form settings on export
* #access Public
* #param array $element
*/
public function on_export($element) {
$tmp = array();
if (!empty($element)) {
foreach ($element as $key => $value) {
if (substr($key, 0, 4) == 'dce_') {
$element[$key];
}
}
}
}
function dce_elementor_form_pdf($fields, $settings = null, $ajax_handler = null) {
global $dce_form, $post;
if (empty($settings['dce_form_pdf_template'])) {
$ajax_handler->add_error_message(__('Error: PDF Template not found or not setted', 'dynamic-content-for-elementor'));
return;
}
// verify Template
$template = get_post($settings['dce_form_pdf_template']);
if (!$template || $template->post_type != 'elementor_library') {
$ajax_handler->add_error_message(__('Error: PDF Template not setted correctly', 'dynamic-content-for-elementor'));
return;
}
$post = get_post($fields['submitted_on_id']); // to retrive dynamic data from post where the form was submitted
$pdf_folder = '/' . $settings['dce_form_pdf_folder'] . '/';
$upload = wp_upload_dir();
$pdf_dir = $upload['basedir'] . $pdf_folder;
$pdf_url = $upload['baseurl'] . $pdf_folder;
$pdf_name = $settings['dce_form_pdf_name'] . '.pdf';
$dce_form['pdf']['path'] = $pdf_dir . $pdf_name;
$dce_form['pdf']['url'] = $pdf_url . $pdf_name;
//var_dump($dce_form); die();
$pdf_html = do_shortcode('[dce-elementor-template id="' . $settings['dce_form_pdf_template'] . '"]');
$pdf_html = DCE_Helper::get_dynamic_value($pdf_html, $fields);
// add CSS
$css = DCE_Helper::get_post_css($settings['dce_form_pdf_template']);
// from flex to table
$css .= '.elementor-section .elementor-container { display: table !important; width: 100% !important; }';
$css .= '.elementor-row { display: table-row !important; }';
$css .= '.elementor-column { display: table-cell !important; }';
$css .= '.elementor-column-wrap, .elementor-widget-wrap { display: block !important; }';
$css = str_replace(':not(.elementor-motion-effects-element-type-background) > .elementor-element-populated', ':not(.elementor-motion-effects-element-type-background)', $css);
$css .= '.elementor-column .elementor-widget-image .elementor-image img { max-width: none !important; }';
$cssToInlineStyles = new \TijsVerkoyen\CssToInlineStyles\CssToInlineStyles();
$pdf_html = $cssToInlineStyles->convert(
$pdf_html,
$css
);
$pdf_html = DCE_Helper::template_unwrap($pdf_html);
// link image from url to path
$site_url = site_url();
//$pdf_html = str_replace('src="'.$site_url, 'src="'.$upload['basedir'], $pdf_html);
// from div to table
//$pdf_html = DCE_Helper::tablefy($pdf_html);
if (is_rtl()) {
// fix for arabic and hebrew
$pdf_html .= '<style>* { font-family: DejaVu Sans, sans-serif; }</style>';
}
if (!empty($settings['dce_form_section_page'])) {
//$pdf_html .= '<style>.elementor-top-section:not(:first-child) { page-break-before: always; }</style>';
$pdf_html .= '<style>.elementor-top-section { page-break-before: always; }.elementor-top-section:first-child { page-break-before: no; }</style>';
}
if (!empty($settings['dce_form_pdf_background'])) {
$bg_path = get_attached_file($settings['dce_form_pdf_background']);
$pdf_html .= '<style>body { background-image: url("'.$bg_path.'"); }</style>';
$pdf_html .= '<style>body { background-repeat: no-repeat; background-position: center; background-size: cover; }</style>';
/*
$data = file_get_contents($bg_path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
$pdf_html .= '<style>body { background-image: url(<?php echo $base64 ?>); }</style>';
*/
}
$pdf_html .= '<style>#page { margin: '.$settings['dce_form_pdf_margin']['top'].$settings['dce_form_pdf_margin']['unit'].' '.$settings['dce_form_pdf_margin']['right'].$settings['dce_form_pdf_margin']['unit'].' '.$settings['dce_form_pdf_margin']['bottom'].$settings['dce_form_pdf_margin']['unit'].' '.$settings['dce_form_pdf_margin']['left'].$settings['dce_form_pdf_margin']['unit'].'; }</style>';
//$ajax_handler->add_error_message($pdf_html); return false;
//echo $pdf_html; die();
if (!is_dir($pdf_dir)) {
// create dir
mkdir($pdf_dir, 0755, true);
}
// https://github.com/dompdf/dompdf
//$auth = base64_encode("username:password");
$context = stream_context_create(array(
'ssl' => array(
'verify_peer' => FALSE,
'verify_peer_name' => FALSE,
// 'allow_self_signed'=> TRUE
),
/*'http' => array(
'header' => "Authorization: Basic $auth"
)*/
));
$options = new \Dompdf\Options();
$options->set('isRemoteEnabled', TRUE);
$options->setIsRemoteEnabled(true);
//$options->set('defaultFont', 'Courier');
// instantiate and use the dompdf class
$dompdf = new \Dompdf\Dompdf($options);
$dompdf->setHttpContext($context);
$dompdf->loadHtml($pdf_html);
$dompdf->set_option('isRemoteEnabled', TRUE);
$dompdf->set_option('isHtml5ParserEnabled', true);
// (Optional) Setup the paper size and orientation
$dompdf->setPaper($settings['dce_form_pdf_size'], $settings['dce_form_pdf_orientation']);
// Render the HTML as PDF
$dompdf->render();
// Output the generated PDF to Browser
//$dompdf->stream();
$output = $dompdf->output();
if (!file_put_contents($pdf_dir . $pdf_name, $output)) {
$ajax_handler->add_error_message(__('Error generating PDF', 'dynamic-content-for-elementor'));
}
if ($settings['dce_form_pdf_save']) {
// Insert the post into the database
// https://codex.wordpress.org/Function_Reference/wp_insert_attachment
// $filename should be the path to a file in the upload directory.
$filename = $dce_form['pdf']['path'];
// The ID of the post this attachment is for.
$parent_post_id = $fields['submitted_on_id'];
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_status' => 'inherit',
'post_title' => $settings['dce_form_pdf_title'],
'post_content' => $settings['dce_form_pdf_content'],
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
//set_post_thumbnail( $parent_post_id, $attach_id );
// https://developer.wordpress.org/reference/functions/wp_insert_post/
/*$db_ins = array(
'post_title' => $settings['dce_form_pdf_title'],
'post_status' => 'public',
'post_type' => 'attachment',
'post_content' => $settings['dce_form_pdf_content'],
);
$obj_id = wp_insert_post($db_ins);*/
if ($attach_id) {
$dce_form['pdf']['id'] = $attach_id;
$dce_form['pdf']['title'] = $settings['dce_form_pdf_title'];
$dce_form['pdf']['description'] = $settings['dce_form_pdf_content'];
if (!empty($fields) && is_array($fields)) {
foreach ($fields as $akey => $adata) {
update_post_meta($attach_id, $akey, $adata);
}
}
} else {
$ajax_handler->add_error_message(__('Error saving PDF as Media', 'dynamic-content-for-elementor'));
}
}
}
}
}
I have tried different ways to add fonts and encodings to this code, but my programming knowledge is not enough, so I either received an error when submitting the form, or I received a file with the same question marks.

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.

fileUploadErrorAttack file was illegally uploaded. This could be a possible attack

I am working on multiple image uploads i got the problem that 1st image is uploading properly and for second image it shows out the file upload error attack
Can you help me to find out the problem
Controller
public function mimageAction()
{
$form = new MultipleImageForm();
$form->get('submit')->setValue('Submit');
$request = $this->getRequest();
if($request->isPost())
{
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('file');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//print_r($data); die;
$form->setData($data);
if ($form->isValid())
{
$count = count($data['varad']);
// $dataNew=array(
// 'test'=>trim($data['test']),
// 'file'=>trim($data['file']['name']),
// 'image'=>trim($data['image']['name'])
// );
$request = new Request();
$files = $request->getFiles();
for($i=0;$i<$count;$i++)
{
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination('public/img/upload/'); // Returns all known internal file information
//$adapter->addFilter('File\Rename', array('target' =>"public/img/upload" . DIRECTORY_SEPARATOR .$data['varad'][$i]['name'] , 'overwrite' => true));
$filter = new \Zend\Filter\File\RenameUpload("public/img/upload/");
$filter->filter($files['varad'][$i]['name']);
$filter->setUseUploadName(true);
$filter->filter($files['varad'][$i]['name']);
if(!$adapter->receive())
{
$messages = $adapter->getMessages();
print_r($messages);
}
else
{
echo "Image Uploaded";
}
}
// $adapter = new \Zend\File\Transfer\Adapter\Http();
// $adapter->setDestination('public/img/upload/'); // Returns all known internal file information
// $adapter->addFilter('File\Rename', array('target' =>"public/img/upload" . DIRECTORY_SEPARATOR .$image2, 'overwrite' => true));
//
// if(!$adapter->receive())
// {
// $messages = $adapter->getMessages();
// print_r($messages);
// }
// else
// {
// echo "Image Uploaded";
// }
}
}
return array('form' => $form);
}
Form
public function __construct($name = null)
{
parent::__construct('stall');
$this->setAttribute("method","post");
$this->setAttribute("enctype","multipart/form-data");
$this->add(array(
'name' => 'varad',
'attributes' => array(
'type' => 'file',
'multiple'=>'multiple',
),
'options' => array(
'label' => 'First Image',
),
'validators' => array(
'Size' => array('max' => 10*1024*1024),
)
));
$this->add(array(
'name' => 'test',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Text Box',
),
));
$this->add(array(
'name' => 'varad',
'attributes' => array(
'type' => 'file',
'multiple'=>'multiple',
),
'options' => array(
'label' => 'Second Image',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'submit',
));
}
Here i also tried by getting different names for images as well as different procedures for images
I think u can't use
$request->getFiles();
for this solution.
Please try to use $adapter->getFileInfo()
It's getting files from const _FILES.
I give my example for u:
$adapter = new Zend_File_Transfer_Adapter_Http();
$newInfoData = [];
$path = $this->getBannerDirByBannerId($banner->getId());
foreach ($adapter->getFileInfo() as $key => $fileInfo) {
if (!$fileInfo['name']) {
continue;
}
if (!$adapter->isValid($key)) {
return $this->getPartialErrorResult($adapter->getErrors(), $key);
}
$fileExtension = pathinfo($fileInfo['name'], PATHINFO_EXTENSION);
$newFileName = $key . '.' . $fileExtension;
if (!is_dir($path)) {
#mkdir($path, 0755, true);
}
$adapter->addFilter('Rename', array(
'target' => $path . $newFileName,
'overwrite' => true
));
$isReceive = $adapter->receive($key);
if ($isReceive) {
$newInfoData[$key] = $newFileName;
}
}
if (!empty($newInfoData)) {
$newInfoData['id'] = $banner->getId();
return BannerModel::getInstance()->updateBanner($newInfoData);
} else {
return new Model_Result();
}

Arguments from Controller passed to View was not fetched in php

Im Using
PHP language , yii-1.1.13 framework and MySQL DB.
Views code of Main Page.
<?php
/**
* The view for the trip schedules page.
* #uses ManageTripSchedulesForm $model
* #uses VoyageServiceClassInfo $voyageServiceClassInfo
* #uses LocationInfo $locationInfo
* #uses PierInfo $pierInfo
* #uses VesselInfo $vesselInfo
* #uses ServiceClassInfo $serviceClassInfo
* #uses FareSetInfo $fareSetInfo
* #uses SearchTripsForm $searchTripsForm
* #uses FerryOperatorInfo $ferryOperatorInfo
* #uses ManageTripSchedulesFilterForm $filterForm
*/
$this->setPageTitle(SystemConstants::SITE_NAME . ' - Trip Schedules');
$baseUrl = Yii::app()->getBaseUrl();
$cs = Yii::app()->getClientScript();
// --- POS_HEAD
// a plug-in used in manageTripSchedules.js
$cs->registerScriptFile($baseUrl . '/js/jquery.blockUI.js', CClientScript::POS_HEAD);
// for this view
$cs->registerCssFile($baseUrl . '/css/manageTripSchedules.css');
$cs->registerScriptFile($baseUrl . '/js/manageTripSchedules.js', CClientScript::POS_HEAD);
$this->endWidget('zii.widgets.jui.CJuiDialog');
/**
* Maintenance Dialog widget
*/
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'dialog',
'options' => array(
'title' => 'Trip Schedules',
'autoOpen' => false,
'modal' => true,
'resizable' => false,
'width' => 600,
'dialogClass' => 'tripschedules-dialog-class',
'show'=>array(
'effect'=>'drop',
'duration'=>500,
),
'hide'=>array(
'effect'=>'drop',
'duration'=>500,
),
),
));
/**
* Render the maintenance dialog view.
*/
echo $this->renderPartial('manageTripSchedulesDialog', array(
'model' => $model,
'ferryOperatorInfo' => $ferryOperatorInfo,
'locationInfo' => $locationInfo,
'pierInfo' => $pierInfo,
'vesselInfo' => $vesselInfo,
'serviceClassInfo' => $serviceClassInfo,
'fareSetInfo' => $fareSetInfo
));
$this->endWidget('zii.widgets.jui.CJuiDialog');
<div id="grid-container" class="grid-div">
<?php
$pageSize = 10;
$helper = new TripSchedulesGridHelper($this);
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'tripschedules-grid',
'dataProvider' => $voyageServiceClassInfo->searchTripSchedules(Yii::app()->user->ferry_operator_id, $filterForm, $pageSize),
'emptyText' => 'No data found.',
'selectableRows' => 0,
'template' => '{items}{pager}', // to remove summary header
'pager' => array(
'header' => '', // to remove 'Go to page:'
),
'cssFile' => $baseUrl . '/css/manageTripSchedulesGrid.css',
'columns' => array(
array(
'name' => 'id',
'value' => '$data->voyage_service_class_id',
'headerHtmlOptions' => array('style' => 'display:none'),
'htmlOptions' => array('style' => 'display:none'),
),
'voyage.ferry_operator.name::Operator',
array(
'name' => 'Origin',
'value' => array($helper, 'formatOriginTerminal'),
),
array(
'name' => 'Destination',
'value' => array($helper, 'formatDestinationTerminal'),
),
array(
'name' => 'DepartureTime',
'header' => 'Departure',
'value' => array($helper, 'formatDepartureDate'),
),
array(
'name' => 'ArrivalTime',
'header' => 'Arrival',
'value' => array($helper, 'formatArrivalDate'),
),
array(
'name' => 'TripHrs',
'header' => 'Trip Hrs',
'value' => array($helper, 'formatTripDuration'),
),
'voyage.vessel.name::Vessel',
'service_class.name::Service Class',
'fare_set.fare_type::Fare Set',
array(
'class' => 'CButtonColumn',
'template'=>'{update}{delete1}',
'buttons'=>array(
'update' => array(
'label'=>'Edit',
'imageUrl'=>Yii::app()->baseUrl.'/images/gridview/update.png',
'url'=>'"#"',
'click'=>'function(){updateTripScheduleJs($(this).parent().parent().children(":nth-child(1)").text());}',
),
'delete1' => array(
'label'=>'Delete',
'imageUrl'=>Yii::app()->baseUrl.'/images/gridview/delete.png',
'url'=>'"#"',
'click'=>'function(){deleteTripScheduleJs($(this).parent().parent().children(":nth-child(1)").text());}',
),
),
),
),
));
?>
</div>
Views code of Add/Edit Dialog.
<?php
echo $form->dropDownList($model, 'service_class_id',
$serviceClassInfo->getAllServiceClassesForSelection2($model->ferry_operator_id,
$this->_ferryOperatorId , true, 'Select class'),
array(
'id' => 'service_class_id',
'class' => 'selectbox',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('loadFareSet'),
'update'=>'#fare_set_id',
'data'=>array('service_class_id'=>'js:this.value'),
))
);
?>
In my Controller, below is my code.
<?php
class SiteController extends Controller
{
public $_ferryOperatorId;
public function actionRetrieveTripSchedule() {
$voyageServiceClassInfo = new VoyageServiceClassInfo;
if (isset($_POST['id']))
{
if (Yii::app()->request->isAjaxRequest)
{
$voyageServiceClassInfo = VoyageServiceClassInfo::model()->with('voyage')->findByPk($_POST['id']);
if ($voyageServiceClassInfo != null)
{
$this->_ferryOperatorId = '3';
$_json = array(
array('name'=>'voyage_service_class_id', 'value'=>$voyageServiceClassInfo->voyage_service_class_id),
array('name'=>'ferry_operator_id', 'value'=>$voyageServiceClassInfo->voyage->ferry_operator_id),
array('name'=>'origin_location_id', 'value'=>$voyageServiceClassInfo->voyage->origin_location_id),
array('name'=>'origin_pier_id', 'value'=>$voyageServiceClassInfo->voyage->origin_pier_id),
array('name'=>'destination_location_id', 'value'=>$voyageServiceClassInfo->voyage->destination_location_id),
array('name'=>'destination_pier_id', 'value'=>$voyageServiceClassInfo->voyage->destination_pier_id),
array('name'=>'departure_date', 'value'=>$voyageServiceClassInfo->voyage->departure_date),
array('name'=>'departure_time', 'value'=>$voyageServiceClassInfo->voyage->departure_time),
array('name'=>'arrival_date', 'value'=>$voyageServiceClassInfo->voyage->arrival_date),
array('name'=>'arrival_time', 'value'=>$voyageServiceClassInfo->voyage->arrival_time),
array('name'=>'vessel_id', 'value'=>$voyageServiceClassInfo->voyage->vessel_id),
array('name'=>'service_class_id', 'value'=>$voyageServiceClassInfo->service_class_id),
array('name'=>'fare_set_id', 'value'=>$voyageServiceClassInfo->fare_set_id),
);
echo CJSON::encode(array(
'status'=>'success',
'messages'=>"Target data is retrieved normally.",
'val'=>$_json,
));
}
else
{
echo CJSON::encode(array(
'status'=>'failure',
'messages'=>"Target data can not be retrieved from server.",
'val'=>$_json,
));
}
}
}
}
}
Models code of Service class drop down lists.
public function getAllServiceClassesForSelection2(
$operatorId = null, $operatorIdEdit = null, $addInstructionRow = false, $instruction = null)
{
$serviceClassArray = array();
if ($addInstructionRow) {
if ($instruction == null) {
$instruction = 'Select a ServiceClass';
}
$serviceClassArray += array('' => $instruction);
}
$criteria = new CDbCriteria;
$criteria->select = 'service_class_id, name';
if ($operatorId != null || $operatorId != '')
{
$criteria->condition = 'ferry_operator_id = ' . $operatorId;
}
if ($operatorIdEdit != null || $operatorIdEdit != '' && $model->operation_mode == AdminGeneralHelper::OPERATION_MODE_UPDATE)
{
$criteria->condition = 'ferry_operator_id = ' . $operatorIdEdit;
}
$criteria->order = 'name';
$servceClassInfos = $this->findAll($criteria);
foreach ($servceClassInfos as $servceClassInfo) {
$serviceClassArray += array(
$servceClassInfo->service_class_id => $servceClassInfo->name,
);
}
return $serviceClassArray;
}
In my JS file, below is my code.
function updateTripScheduleJs(id) {
// Get target data via controller and set values to fields of dialog.
$.blockUI({
message: "Loading data...",
});
$("#dialog-msg").html(""); // clear the message area of dialog
// Ajax request
$.ajax({
url: 'retrieveTripSchedule',
type: 'POST',
datatype: 'json',
data: $.parseJSON('{"id": '+id+'}'),
timeout: 20000,
beforeSend: function(){
},
success: function(data){
$.unblockUI();
var res = eval('(' + data + ')');
if (res.status == 'success'){
for (var idx in res.val){
if (res.val[idx].name == 'departure_time' || res.val[idx].name == 'arrival_time'){
$('#'+res.val[idx].name).attr('value',formatAMPM(res.val[idx].value));
} else {
$('#'+res.val[idx].name).attr('value',res.val[idx].value);
}
}
$("#operation_mode").attr('value','U'); // Set update mode
$(".submit-button").attr('value','Update Trip Schedule'); // Set submit button label
$(".update-only-div").css('display','block'); // Show columns for update
$(".create-only-div").css('display','none'); // Hide columns for update
$("#dialog").dialog("open");
} else {
alert("Trip Schedule does not exist. It may be deleted by other user");
$.fn.yiiGridView.update('tripschedules-grid'); // Refresh the list of service class.
}
},
error: function(){
$.unblockUI();
alert("Ajax Communication Error. Please contact system administrator.");
}
}
);
}
Below is the scenario:
I clicked the pencil icon, dialog will show. It will load all the
details depend on the selected row. This is correct.
It will load all the details. This is correct.
No. of values in Drop down lists for service class is wrong.
My expected output of service class is only 4 (based on DB) but in actual, all service class was displayed.
I found out that $this->_ferryOperatorId = '3' from controller that was used in views
($serviceClassInfo->getAllServiceClassesForSelection2($model->ferry_operator_id,
$this->_ferryOperatorId , true, 'Select class'))
has no value.
In my models code, if the ferryOperatorId = null, it will display all the
service class.
My question is what is the correct code for me to get the value of $this->_ferryOperatorId from controller
then used the value in views.
:(
Please help me to solve this.

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