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();
}
Related
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.
Attempting to generate thumbnails with Image_moo & CodeIgniter framework. Image_moo does not output any errors, however, thumbnail images are never generated.
dir structure
app
- controllers/
Admin.php
...
- libraries/
Image_moo.php
...
- models/
Admin_photos_model.php
Admin.php
public function photo_upload() {
$rules = [
[
'field' => 'caption',
'label' => 'Caption'//,
//'rules' => 'required'
],[
'field' => 'description',
'label' => 'Description'//,
//'rules' => 'required'
],[
'field' => 'series',
'label' => 'Series',
'rules' => 'required'
]
];
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() == FALSE) {
$this->load->view('admin/photos/upload');
} else {
$series = str_replace(' ', '', strtolower($_POST['series']));
$upload_path = './img/photos/'.$series.'/';
$config = [
'upload_path' => $upload_path, //'./img/photos/'.$series.'/',
'allowed_types' => 'gif|jpg|jpeg|png'
];
$this->load->library('upload', $config);
if (!file_exists($upload_path)) { //check if series dir exists
mkdir($upload_path, 0777, true); // create dir if !exist
$num = 1; //init
} else {
$num = $this->db->where('series', $series)->count_all_results('photos') + 1;
};
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('admin/photos/upload', $error);
} else {
$file = $this->upload->data();
$caption = $_POST['caption'];
$description = $_POST['description'];
$data = [
'filename' => $file['file_name'],
'series' => $series,
'num' => $num,
'caption' => $caption,
'description' => $description
];
$this->Admin_photos_model->upload($data);
$this->load->library('image_moo'); //create thumbnail, upload
$file_raw_name = $this->upload->data('raw_name');
$file_ext = $this->upload->data('file_ext');
$file_width = $this->upload->data('image_width');
$file_height = $this->upload->data('image_height');
$file_uploaded = $upload_path.$data['filename']; //$field_info->upload_path.'/'.$uploader_response[0]->name;
if ($file_width > 1024 && $file_height > 720) {
$this->image_moo->load($file_uploaded)
->resize_crop(1024,720)->save($upload_path.$file_raw_name.'_thumb_xl'.$file_ext)
->resize_crop(800,562)->save($upload_path.$file_raw_name.'_thumb_lg'.$file_ext)
->resize_crop(640,450)->save($upload_path.$file_raw_name.'_thumb_med'.$file_ext)
->resize_crop(450,316)->save($upload_path.$file_raw_name.'_thumb_sm'.$file_ext)
->resize_crop(222,156)->save($upload_path.$file_raw_name.'_thumb_xs'.$file_ext);
$data = [
'has_thumb_xl' => 1,
'has_thumb_lg' => 1,
'has_thumb_med' => 1,
'has_thumb_sm' => 1,
'has_thumb_xs' => 1,
'thumb_xl_filename' => $file_raw_name.'_thumb_xl'.$file_ext,
'thumb_lg_filename' => $file_raw_name.'_thumb_lg'.$file_ext,
'thumb_med_filename' => $file_raw_name.'_thumb_med'.$file_ext,
'thumb_sm_filename' => $file_raw_name.'_thumb_sm'.$file_ext,
'thumb_xs_filename' => $file_raw_name.'_thumb_xs'.$file_ext
];
};
if ($this->image_moo->error) {
print $this->image_moo->display_errors();
};
$this->Admin_photos_model->thumbnails($data);
$this->session->set_flashdata('message','file uploaded: '.$file_uploaded.'New image has been added..'.'series dir: '.$series.'last num of series: '.$num.'thumb:'.$file_raw_name.'_thumb_xl'.$file_ext.'errors: '.$this->image_moo->display_errors());
redirect('admin/photos');
};
Admin_photos_model
<?php
class Admin_photos_model extends CI_Model {
public function __construct(){
$this->load->database();
}
public function upload($data) {
try {
$this->db->insert('photos', $data);
return true;
} catch (Exception $e) {
echo $e->getMessage();
};
}
public function thumbnails($data) {
try {
$this->db->insert('photos', $data);
return true;
} catch (Exception $e) {
echo $e->getMessage();
};
}
}
Attempting to generate thumbnails, I'm separating the photos by series. If the series hasn't started, a new dir is created. Ideally, uploading 'waterfall.jpg' with series 'nature' would yield:
app
...
public_html/
img/
photos/
nature/
waterfall.jpg
waterfall_thumb_xl.jpg
waterfall_thumb_lg.jpg
waterfall_thumb_med.jpg
waterfall_thumb_sm.jpg
waterfall_thumb_xs.jpg
Any help would be appreciated.
Reading the image_moo documentation, the save function needs to have an overwrite=FALSE/TRUE. Doing so seemed to fix it.
"save($x,$overwrite=FALSE) - Saved the manipulated image (if
applicable) to file $x - JPG, PNG, GIF supported. If overwrite is not
set file write may fail. The file saved will be dependant on
processing done to the image, or a simple copy if nothing has been
done."
I am a begineer in yii. I am making a basic structure - an employee. I am uploading their images and saving image name in database and also showing it on my view page. But I want to change the image name to employee id.
For Ex:
desert.jpg changes to 01.jpg or any other employee id.
Please help me.
CONTROLLER:
public function actioncreate(){
$dept_list = department_mod::model()->dept_list();
$data['dept_list'] = CHtml::listData($dept_list,'value', 'text');
$team_list = team_mod::model()->team_list();
$data['team_list'] = CHtml::listData($team_list,'value', 'text');
$des_list = employee_mod::model()->des_list();
$data['des_list'] = CHtml::listData($des_list,'value', 'text');
$report_to_list = report_to_mod::model()->report_to_list();
$data['report_to_list'] = CHtml::listData($report_to_list,'value', 'text');
$model_upload = new upload_mod;
$data['model_upload'] = $model_upload;
$this->render('create',$data);
}
public function actionsave(){
$q = Employee_mod::model()->data_save($_POST);
$data = $_POST;
$exp = 'profile';
$emp_upload_path = 'assests/images/';
$p = $emp_upload_path;
echo $p;
if (!is_dir($p)) {
mkdir($p,0777);
}
$path = $p.$exp.'/';
if (!is_dir($path)) {
mkdir($path,0777);
}
$model_upload = new upload_mod;
$file_name = "";
$model_upload->upload_file = CUploadedFile::getInstance($model_upload,'userfile');
if($model_upload->validate()) {
$model_upload->upload_file->saveAs($path . $model_upload->upload_file);
$file_name = $model_upload->upload_file;
}else{
var_dump($model_upload->getErrors());
}
$data['file_name'] = $file_name;
$q = Employee_mod::model()->imagesave($q , $file_name);
$this->redirect(array('employee/list'));
MODEL:
function data_save($data)
{
$input = array(
'first_name' => $data['first_name'],
'middle_name' => $data['middle_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'cnic' => $data['cnic'],
'dob' => $data['dob'],
'department' => $data['dept_id'],
'location' => $data['location'],
'created_by' => 'admin',
'team' => $data['id'],
'des' => $data['des_id'],
'report_to' => $data['id'],
'joining_date' => $data['joining_date'],
);
$q = Yii::app()->db->createCommand();
$q->insert('emp',$input);
$insert_id = Yii::app()->db->getLastInsertID();
return $insert_id;
}
function imagesave($empno , $file_name)
{
$file = array(
'image' => $file_name
);
$q = Yii::app()->db->createCommand();
$q->update('emp', $file, 'empno=' . $empno);
}
function imageeditsave($empno , $file_name)
{
$file = array(
'image' => $file_name
);
$q = Yii::app()->db->createCommand();
$q->update('emp', $file, 'empno=' . $empno);
}
function data_editsave($data,$emp_no)
{
$input = array(
'first_name' => $data['first_name'],
'middle_name' => $data['middle_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'cnic' => $data['cnic'],
'dob' => $data['dob'],
'department' => $data['dept_id'],
'location' => $data['location'],
'created_by' => $data['created_by'],
'team' => $data['id'],
'des' => $data['des_id'],
'report_to' => $data['id'],
'joining_date' => $data['joining_date'],
);
$q = Yii::app()->db->createCommand();
$q-> update('emp',$input,'empno =' . $emp_no);
$insert_id = Yii::app()->db->getLastInsertID();
return $insert_id;
}
The problem is here:
$q = Yii::app()->db->createCommand();
$q->update('emp', $file, 'empno=' . $empno);
update is an ActiveRecord method and you are using it with createCommand! You need to change that code to this:
Employee_mod::model()->updateByPk($empno, array('image' => $file_name));
I am trying to add an additional image upload field to a gallery extension. The code for the extension controller is below. I've added an extra column to the database called galpic_popup_image with the same values as the existing galpic_image column.
I've managed to get the upload working, so images are saved on the server, however it isn't saving the filename in the database and therefore I can't call it on the frontend.
class ParadoxLabs_Gallery_Adminhtml_GalleryController extends Mage_Adminhtml_Controller_Action
{
public function indexAction()
{
$this->loadLayout();
$this->_setActiveMenu('cms/gallery');
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Gallery'), Mage::helper('adminhtml')->__('Gallery'));
$this->renderLayout();
}
public function editAction()
{
$this->loadLayout();
$this->_setActiveMenu('cms/gallery');
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Gallery'), Mage::helper('adminhtml')->__('Gallery'));
$this->_addContent($this->getLayout()->createBlock('gallery/adminhtml_gallery_edit'));
$this->renderLayout();
}
public function newAction()
{
$this->editAction();
}
public function saveAction()
{
if ( $this->getRequest()->getPost() ) {
// Image uploading code modified from https://magento2.atlassian.net/wiki/spaces/m1wiki/pages/14024884/How+to+create+an+image+or+video+uploader+for+the+Magento+Admin+Panel
if(isset($_FILES['image']['name']) && (file_exists($_FILES['image']['tmp_name'])))
{
try{
$uploader = new Varien_File_Uploader('image');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'p_gallery' . DS ;
$uploader->save($path, $_FILES['image']['name']);
$data['image'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'p_gallery/'. $_FILES['image']['name'];
}catch(Exception $e){}
}
else
{
if(isset($data['fileinputname']['delete']) && $data['fileinputname']['delete'] == 1){
$data['image_main'] = '';
}
else{
unset($data['image']);
}
}
if(isset($_FILES['popup_image']['name']) && (file_exists($_FILES['popup_image']['tmp_name'])))
{
try{
$uploader = new Varien_File_Uploader('popup_image');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'p_gallery' . DS ;
$uploader->save($path, $_FILES['popup_image']['name']);
$popupdata['popup_image'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'p_gallery/'. $_FILES['popup_image']['name'];
}catch(Exception $e){}
}
else
{
if(isset($popupdata['fileinputname']['delete']) && $popupdata['fileinputname']['delete'] == 1){
$popupdata['popup_image_main'] = '';
}
else{
unset($popupdata['popup_image']);
}
}
try {
if( intval($this->getRequest()->getParam('id')) == 0 ) { // New
$model = Mage::getModel('gallery/gallery')
->setGalpicId ( $this->getRequest()->getParam('id') )
->setGalpicStore( $this->getRequest()->getParam('store') )
->setGalpicDate ( date('Y-m-d', time()) )
->setGalpicName ( $this->getRequest()->getParam('name') )
->setGalpicImage( $data['image'] )
->setGalpicPopupImage( $popupdata['popup_image'] )
->save();
}
else { // Edit
$model = Mage::getModel('gallery/gallery')
->setGalpicId ( $this->getRequest()->getParam('id') )
->setGalpicStore( $this->getRequest()->getParam('store') )
->setGalpicName ( $this->getRequest()->getParam('name') )
->setGalpicImage( $data['image'] )
->setGalpicPopupImage( $popupdata['popup_image'] )
->save();
}
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Galpic was successfully saved'));
$this->_redirect('*/*/');
return;
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;
}
}
$this->_redirect('*/*/');
}
public function deleteAction()
{
if( $this->getRequest()->getParam('id') > 0 ) {
try {
$model = Mage::getModel('gallery/gallery');
$model->setGalpicId($this->getRequest()->getParam('id'))
->delete();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Galpic was successfully deleted'));
$this->_redirect('*/*/');
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
}
}
$this->_redirect('*/*/');
}
protected function _isAllowed()
{
return Mage::getSingleton('admin/session')->isAllowed('cms/gallery');
}
}
And here is the form used to capture the data:
class ParadoxLabs_Gallery_Block_Adminhtml_Gallery_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareLayout()
{
parent::_prepareLayout();
if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) {
$this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
}
}
protected function _prepareForm()
{
$form = new Varien_Data_Form(array(
'enctype' => 'multipart/form-data',
'id' => 'edit_form',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
));
$fieldset = $form->addFieldset('gallery_form', array(
'legend' => Mage::helper('gallery')->__('Galpic'),
'class' => 'fieldset-wide'
)
);
$fieldset->addField('galpic_name', 'text', array(
'name' => 'name',
'label' => Mage::helper('gallery')->__('Name'),
'class' => 'required-entry',
'required' => true,
));
$fieldset->addField('galpic_image', 'image', array(
'name' => 'image',
'label' => Mage::helper('gallery')->__('Image'),
'class' => 'required-entry',
'required' => true,
));
$fieldset->addField('galpic_popup_image', 'image', array(
'name' => 'popup_image',
'label' => Mage::helper('gallery')->__('Popup Image'),
'class' => 'required-entry',
'required' => true,
));
$fieldset->addField('galpic_store', 'select', array(
'name' => 'store',
'label' => Mage::helper('core')->__('Store View'),
'title' => Mage::helper('core')->__('Store View'),
'required' => true,
'values' => Mage::getSingleton('adminhtml/system_store')->getStoreValuesForForm(false, true),
));
if (Mage::registry('gallery')) {
$form->setValues(Mage::registry('gallery')->getData());
}
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
}
Ok, I fixed it!
It was suggested to make sure the columns were in the same order as the controller saves the items so I did that. It didn't seem to have an effect (but it may have done).
I changed the second image upload code to the following (basically removed 'popup' from $popupdata as Kiatng suggested) above:
if(isset($_FILES['popup_image']['name']) && (file_exists($_FILES['popup_image']['tmp_name'])))
{
try{
$uploader = new Varien_File_Uploader('popup_image');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media') . DS . 'p_gallery' . DS ;
$uploader->save($path, $_FILES['popup_image']['name']);
$data['popup_image'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'p_gallery/'. $_FILES['popup_image']['name'];
}catch(Exception $e){}
}
else
{
if(isset($data['fileinputname']['delete']) && $data['fileinputname']['delete'] == 1){
$data['image_main'] = '';
}
else{
unset($data['popup_image']);
}
}
Actually I'm developing a simple file uploader.
In the ImageUploader.php file I define the getInputFilter function, all works unless I try to add a File\MimeType validator:
<?php
namespace Admin\Model;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
use Zend\Validator\File\MimeType; //tried also with use Zend\Validator\File;
[...]
public function getInputFilter()
{
[...]
$inputFilter->add($factory->createInput(array(
'name' => 'image',
'required' => true,
'validators' => array(
array(
'name' => 'MimeType', //tried also with File\MimeType
'options' => array(
'mimeType' => array('image/jpeg'),
),
),
),
)));
[...]
}
What's the correct way to define a File\Validator\MimeType?
Thank you in advance.
Here is a sample from my project with a couple of other useful features (renaming for example):
use Zend\File\Transfer\Adapter\Http,
Zend\Validator\File\Size,
Zend\Validator\File\IsImage;
[...]
public function editAction() {
[...]
if ($request->isPost()) {
$params = $this->params()->fromPost();
$files = $this->params()->fromFiles();
$images = array();
if(!empty($files['main_image']['name'])) $images['main_image'] = $files['main_image']['name'];
if(!empty($files['detailed_image']['name'])) $images['detailed_image'] = $files['detailed_image']['name'];
if(!empty($images)) {
$adapter = new Http();
$size = new Size(array('max'=>1000000));
$is_image = new IsImage();
$image_errors = array();
foreach ($images as $field => $filename) {
$adapter->setValidators(array($size,$is_image), $filename);
if (!$adapter->isValid($filename)) {
$adapter_errors = $adapter->getMessages();
$errors = array();
foreach($adapter_errors as $key=>$row) {
$errors[] = $row;
}
if(!empty($errors)) {
array_push($image_errors, $errors);
$form->setMessages(array($field => $errors));
}
} else {
$adapter->setDestination(IMAGES_PATH);
$fileinfo = $adapter->getFileInfo();
preg_match('/.+\/(.+)/', $fileinfo[$field]['type'], $matches);
$extension = $matches[1];
$old_filename = $item->__get($field);
$new_filename = $item->id.'_'.$field.'.'.$extension;
$adapter->addFilter('File\Rename',
array(
'target' => IMAGES_PATH.$new_filename,
'overwrite' => true,
)
);
if($adapter->receive($fileinfo[$field]['name'])) {
if(!empty($old_filename) && $old_filename != $new_filename &&
file_exists(IMAGES_PATH.$old_filename)) {
unlink(IMAGES_PATH.$old_filename);
}
$params[$field] = $new_filename;
}
}
}
}
}
[...]
}
[...]
The code however could be refactored to move the logic to some lib or model.
Not sure which version you are using now but with Zendframework 2.4 you can now do this. Hope this helps.
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'fileupload',
'required' => true,
'allow_empty' => false,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'Zend\Validator\File\UploadFile',
'name' => 'Zend\Validator\File\MimeType',
'options' => array(
'mimeType' => 'audio, video, image',
),
),
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}