Jump to content

Module - Possibilité d'uploader des images


Recommended Posts

Bonjour à tous,

 

Je développe actuellement un module très simple avec quelques zone à remplir. Il me faudrait également une zone où je pourrais uploader une image. Impossible à trouver un développement complet sur le net.

 

J'ai bien le champ pour uploader l'image, je peux la sélectionner mais dès que j'enregistre j'ai le petit message d'erreur et aucune image à cet endroit.

 

Voici mon code (en le résumant uniquement à l'image et pas ce qu'il y a autour : Tout le reste devrait être bon car les autres champs textes fonctionnent parfaitement) :

 

 

 

 

public function hookDisplayHome($params)

{

$this->context->smarty->assign(

array(

'image_gammespinee' => Configuration::get('image_gammespinee')

)

);

return $this->display(__FILE__, 'gammespinee.tpl');

}

 

 

public function getContent()

{

$output = null;

 

if (Tools::isSubmit('submit'.$this->name))

{

$image_gammespinee = strval(Tools::getValue('image_gammespinee'));

if (!$image_gammespinee || empty($image_gammespinee) || !Validate::isGenericName($image_gammespinee))

$output .= $this->displayError( $this->l('Invalid Configuration value') );

else

{

Configuration::updateValue('image_gammespinee', $image_gammespinee);

}

}

return $output.$this->displayForm();

}

 

 

 

 

public function displayForm()

{

// Get default Language

$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');

 

// Init Fields form array

$fields_form[0]['form'] = array(

'legend' => array(

'title' => $this->l('Modifications des données'),

),

 

'input' => array(

 

array(

'type' => 'file',

'label' => $this->l('Sélectionner une image'),

'desc' => $this->l('Format : 105px x 140px. Formats autorisés : jpeg, png, jpg, gif.'),

'name' => 'image_gammespinee',

'required' => true,

'lang' => false,

'display_image' => true,

),

),

'submit' => array(

'title' => $this->l('Save'),

'class' => 'button'

)

);

 

$helper->fields_value['image_gammespinee'] = Configuration::get('image_gammespinee');

 

 

 

 

 

Ne faites pas attention aux ouvertures et fermetures (elles sont bonnes mais j'en ai peut-être coupées certaines sans le faire exprès).

 

 

Si quelqu'un a une idée ou un lien vers un tuto qui expliquerait comment ajouter un file upload à un module, ce serait parfait ! MERCI A TOUS

Link to comment
Share on other sites

Salut,

 

Tu peux donner le fichier PHP plutôt car là c'est pas très lisible.

 

Déjà tu as une ligne qui ne sert à rien:

$helper->fields_value['image_gammespinee'] = Configuration::get('image_gammespinee');

Un input file ne peut recevoir de valeur.

 

Sinon c'est dans la méthode postProcess que tu dois gérer la récupération du fichier, tu peux de baser sur le controller admin AdminAttachmentsController qui est un bon exemple.

 

Attention toutefois à ajouter un contrôle de fichier sur l'extention et/ou le mime type.

Pour cela tu peux utiliser la class ImageManager et la méthode isRealImage, tu trouveras d'autres méthodes utiles pour créer des miniatures etc...

 

 

A+

Edited by Matt75 (see edit history)
Link to comment
Share on other sites

<?php

if (!defined('_PS_VERSION_'))

exit;

 

class GammeSpinee extends Module // CHANGER LA CLASSE POUR UN NOUVEAU MODULE

{

public function __construct()

{

$this->name = 'gammespinee';

$this->tab = 'front_office_features';

$this->version = '1.0';

$this->author = 'dev04';

$this->need_instance = 0;

$this->ps_versions_compliancy = array('min' => '1.5', 'max' => '1.6');

$this->dependencies = array('blockcart');

$this->fieldImageSettings = array('name' => 'image', 'dir' => 'example');

 

parent::__construct();

 

$this->displayName = $this->l('LA GAMME SPINNE');

$this->description = $this->l('Bloc se trouvant sur la page d\'accueil');

 

 

$this->confirmUninstall = $this->l('dbcreation ne sera pas tenu responsable de la suppression de ce module');

 

if (!Configuration::get('MYMODULE_NAME'))

$this->warning = $this->l('No name provided');

}

 

public function install()

{

if (parent::install() == false)

return false;

return true;

 

return parent::install() &&

$this->registerHook('leftColumn') &&

$this->registerHook('Home') &&

$this->registerHook('header') &&

Configuration::updateValue('MYMODULE_NAME', 'my friend');

}

 

 

public function hookDisplayHome($params)

{

$this->context->smarty->assign(

array(

'my_module_name' => Configuration::get('MYMODULE_NAME'),

'titre_gammespinee' => Configuration::get('titre_gammespinee'),

'bloc_gammespinee' => Configuration::get('bloc_gammespinee'),

'textlien_gammespinee' => Configuration::get('textlien_gammespinee'),

'lien_gammespinee' => Configuration::get('lien_gammespinee'),

'image_gammespinee' => Configuration::get('image_gammespinee'),

'my_module_link' => $this->context->link->getModuleLink('gammespinee', 'display')

)

);

return $this->display(__FILE__, 'gammespinee.tpl');

}

 

public function hookDisplayRightColumn($params)

{

return $this->hookDisplayLeftColumn($params);

}

 

public function hookDisplayHeader()

{

$this->context->controller->addCSS($this->_path.'css/gammespinee.css', 'all');

}

 

 

public function uninstall()

{

if (!parent::uninstall())

Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'gammespinee`');

parent::uninstall();

}

 

 

 

 

public function getContent()

{

$output = null;

 

if (Tools::isSubmit('submit'.$this->name))

{

$titre_gammespinee = strval(Tools::getValue('titre_gammespinee'));

if (!$titre_gammespinee || empty($titre_gammespinee) || !Validate::isGenericName($titre_gammespinee))

$output .= $this->displayError( $this->l('Invalid Configuration value') );

else

{

Configuration::updateValue('titre_gammespinee', $titre_gammespinee);

$output .= $this->displayConfirmation($this->l('Settings updated'));

}

 

$bloc_gammespinee = strval(Tools::getValue('bloc_gammespinee'));

if (!$bloc_gammespinee || empty($bloc_gammespinee) || !Validate::isGenericName($bloc_gammespinee))

$output .= $this->displayError( $this->l('Invalid Configuration value') );

else

{

Configuration::updateValue('bloc_gammespinee', $bloc_gammespinee);

}

 

$textlien_gammespinee = strval(Tools::getValue('textlien_gammespinee'));

if (!$textlien_gammespinee || empty($textlien_gammespinee) || !Validate::isGenericName($textlien_gammespinee))

$output .= $this->displayError( $this->l('Invalid Configuration value') );

else

{

Configuration::updateValue('textlien_gammespinee', $textlien_gammespinee);

}

 

$lien_gammespinee = strval(Tools::getValue('lien_gammespinee'));

if (!$lien_gammespinee || empty($lien_gammespinee) || !Validate::isGenericName($lien_gammespinee))

$output .= $this->displayError( $this->l('Invalid Configuration value') );

else

{

Configuration::updateValue('lien_gammespinee', $lien_gammespinee);

}

 

$image_gammespinee = strval(Tools::getValue('image_gammespinee'));

if (!$image_gammespinee || empty($image_gammespinee) || !Validate::isGenericName($image_gammespinee))

$output .= $this->displayError( $this->l('Invalid Configuration value') );

else

{

Configuration::updateValue('image_gammespinee', $image_gammespinee);

}

}

return $output.$this->displayForm();

}

 

 

public function displayForm()

{

// Get default Language

$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');

 

// Init Fields form array

$fields_form[0]['form'] = array(

'legend' => array(

'title' => $this->l('Modifications des données'),

),

'input' => array(

array(

'type' => 'text',

'label' => $this->l('Titre du bloc'),

'name' => 'titre_gammespinee',

'size' => 40,

'required' => true

),

array(

'type' => 'textarea',

'label' => $this->l('Contenu du bloc'),

'name' => 'bloc_gammespinee',

'rows' => 5,

'cols' => 40,

'desc' => $this->l('ATTENTION A LA LONGEUR DU TEXTE')

),

array(

'type' => 'text',

'label' => $this->l('En savoir plus'),

'name' => 'textlien_gammespinee',

'size' => 40

),

array(

'type' => 'text',

'label' => $this->l('Lien'),

'name' => 'lien_gammespinee',

'size' => 40

),

array(

'type' => 'file',

'label' => $this->l('Sélectionner une image'),

'desc' => $this->l('Format : 105px x 140px. Formats autorisés : jpeg, png, jpg, gif.'),

'name' => 'image_gammespinee',

'required' => true,

'lang' => false,

'display_image' => true,

),

),

'submit' => array(

'title' => $this->l('Save'),

'class' => 'button'

)

);

 

$helper = new HelperForm();

 

// Module, token and currentIndex

$helper->module = $this;

$helper->name_controller = $this->name;

$helper->token = Tools::getAdminTokenLite('AdminModules');

$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;

 

// Language

$helper->default_form_language = $default_lang;

$helper->allow_employee_form_lang = $default_lang;

 

// Title and toolbar

$helper->title = $this->displayName;

$helper->show_toolbar = true; // false -> remove toolbar

$helper->toolbar_scroll = true; // yes - > Toolbar is always visible on the top of the screen.

$helper->submit_action = 'submit'.$this->name;

$helper->toolbar_btn = array(

'save' =>

array(

'desc' => $this->l('Save'),

'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.

'&token='.Tools::getAdminTokenLite('AdminModules'),

),

'back' => array(

'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),

'desc' => $this->l('Back to list')

)

);

 

// Load current value

$helper->fields_value['titre_gammespinee'] = Configuration::get('titre_gammespinee');

$helper->fields_value['bloc_gammespinee'] = Configuration::get('bloc_gammespinee');

$helper->fields_value['textlien_gammespinee'] = Configuration::get('textlien_gammespinee');

$helper->fields_value['lien_gammespinee'] = Configuration::get('lien_gammespinee');

$helper->fields_value['image_gammespinee'] = Configuration::get('image_gammespinee');

 

return $helper->generateForm($fields_form);

}

 

 

}

?>

Link to comment
Share on other sites

J'espère que comme cela ce sera plus clair. Désolé j'ai pas l'habitude du forum

 

<?php
if (!defined('_PS_VERSION_'))
 exit;

class GammeSpinee extends Module  // CHANGER LA CLASSE POUR UN NOUVEAU MODULE
{
 public function __construct()
 {
   $this->name = 'gammespinee';
   $this->tab = 'front_office_features';
   $this->version = '1.0';
   $this->author = 'Squid Studio';
   $this->need_instance = 0;
   $this->ps_versions_compliancy = array('min' => '1.5', 'max' => '1.6');
   $this->dependencies = array('blockcart');
 $this->fieldImageSettings = array('name' => 'image', 'dir' => 'example');

   parent::__construct();

   $this->displayName = $this->l('LA GAMME SPINNE');
   $this->description = $this->l('Bloc se trouvant sur la page d\'accueil');


   $this->confirmUninstall = $this->l('dbcreation ne sera pas tenu responsable de la suppression de ce module');

   if (!Configuration::get('MYMODULE_NAME'))	  
  $this->warning = $this->l('No name provided');
 }

public function install()
{
  if (parent::install() == false)
 return false;
   return true;

  return parent::install() &&
 $this->registerHook('leftColumn') &&
 $this->registerHook('Home') &&
 $this->registerHook('header') &&
 Configuration::updateValue('MYMODULE_NAME', 'my friend');
}


public function hookDisplayHome($params)
{
  $this->context->smarty->assign(
   array(
 'my_module_name' => Configuration::get('MYMODULE_NAME'),
 'titre_gammespinee' => Configuration::get('titre_gammespinee'),
 'bloc_gammespinee' => Configuration::get('bloc_gammespinee'),
 'textlien_gammespinee' => Configuration::get('textlien_gammespinee'),
 'lien_gammespinee' => Configuration::get('lien_gammespinee'),
 'image_gammespinee' => Configuration::get('image_gammespinee'),
 'my_module_link' => $this->context->link->getModuleLink('gammespinee', 'display')
   )
  );
  return $this->display(__FILE__, 'gammespinee.tpl');
}

public function hookDisplayRightColumn($params)
{
  return $this->hookDisplayLeftColumn($params);
}

public function hookDisplayHeader()
{
  $this->context->controller->addCSS($this->_path.'css/gammespinee.css', 'all');
}


public function uninstall()
{
  if (!parent::uninstall())
 Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'gammespinee`');
  parent::uninstall();
}




public function getContent()
{
 $output = null;

 if (Tools::isSubmit('submit'.$this->name))
 {
  $titre_gammespinee = strval(Tools::getValue('titre_gammespinee'));
  if (!$titre_gammespinee  || empty($titre_gammespinee) || !Validate::isGenericName($titre_gammespinee))
   $output .= $this->displayError( $this->l('Invalid Configuration value') );
  else
  {
   Configuration::updateValue('titre_gammespinee', $titre_gammespinee);
   $output .= $this->displayConfirmation($this->l('Settings updated'));
  }

  $bloc_gammespinee = strval(Tools::getValue('bloc_gammespinee'));
  if (!$bloc_gammespinee  || empty($bloc_gammespinee) || !Validate::isGenericName($bloc_gammespinee))
   $output .= $this->displayError( $this->l('Invalid Configuration value') );
  else
  {
   Configuration::updateValue('bloc_gammespinee', $bloc_gammespinee);
  }

  $textlien_gammespinee = strval(Tools::getValue('textlien_gammespinee'));
  if (!$textlien_gammespinee  || empty($textlien_gammespinee) || !Validate::isGenericName($textlien_gammespinee))
   $output .= $this->displayError( $this->l('Invalid Configuration value') );
  else
  {
   Configuration::updateValue('textlien_gammespinee', $textlien_gammespinee);
  }

  $lien_gammespinee = strval(Tools::getValue('lien_gammespinee'));
  if (!$lien_gammespinee  || empty($lien_gammespinee) || !Validate::isGenericName($lien_gammespinee))
   $output .= $this->displayError( $this->l('Invalid Configuration value') );
  else
  {
   Configuration::updateValue('lien_gammespinee', $lien_gammespinee);
  }

  $image_gammespinee = strval(Tools::getValue('image_gammespinee'));
  if (!$image_gammespinee  || empty($image_gammespinee) || !Validate::isGenericName($image_gammespinee))
   $output .= $this->displayError( $this->l('Invalid Configuration value') );
  else
  {
   Configuration::updateValue('image_gammespinee', $image_gammespinee);
  }
 }
 return $output.$this->displayForm();
}


public function displayForm()
{
 // Get default Language
 $default_lang = (int)Configuration::get('PS_LANG_DEFAULT');

 // Init Fields form array
 $fields_form[0]['form'] = array(
  'legend' => array(
   'title' => $this->l('Modifications des données'),
  ),
  'input' => array(
   array(
 'type' => 'text',
 'label' => $this->l('Titre du bloc'),
 'name' => 'titre_gammespinee',
 'size' => 40,
 'required' => true
   ),
   array(
 'type' => 'textarea',
 'label' => $this->l('Contenu du bloc'),
 'name' => 'bloc_gammespinee',
 'rows' => 5,
 'cols' => 40,
 'desc' => $this->l('ATTENTION A LA LONGEUR DU TEXTE')
		 ),
   array(
 'type' => 'text',
 'label' => $this->l('En savoir plus'),
 'name' => 'textlien_gammespinee',
 'size' => 40
   ),
   array(
 'type' => 'text',
 'label' => $this->l('Lien'),
 'name' => 'lien_gammespinee',
 'size' => 40
   ),
   array(
  'type'   =>   'file',
  'label'  =>   $this->l('Sélectionner une image'),
  'desc'  =>  $this->l('Format : 105px x 140px. Formats autorisés : jpeg, png, jpg, gif.'),
  'name'   =>   'image_gammespinee',
  'required' =>   true,
  'lang'  =>  false,
  'display_image' => true,
 ),
  ),
  'submit' => array(
   'title' => $this->l('Save'),
   'class' => 'button'
  )
 );

 $helper = new HelperForm();

 // Module, token and currentIndex
 $helper->module = $this;
 $helper->name_controller = $this->name;
 $helper->token = Tools::getAdminTokenLite('AdminModules');
 $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;

 // Language
 $helper->default_form_language = $default_lang;
 $helper->allow_employee_form_lang = $default_lang;

 // Title and toolbar
 $helper->title = $this->displayName;
 $helper->show_toolbar = true;	    // false -> remove toolbar
 $helper->toolbar_scroll = true;	  // yes - > Toolbar is always visible on the top of the screen.
 $helper->submit_action = 'submit'.$this->name;
 $helper->toolbar_btn = array(
  'save' =>
  array(
   'desc' => $this->l('Save'),
   'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.
   '&token='.Tools::getAdminTokenLite('AdminModules'),
  ),
  'back' => array(
   'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
   'desc' => $this->l('Back to list')
  )
 );

 // Load current value
 $helper->fields_value['titre_gammespinee'] = Configuration::get('titre_gammespinee');
 $helper->fields_value['bloc_gammespinee'] = Configuration::get('bloc_gammespinee');
 $helper->fields_value['textlien_gammespinee'] = Configuration::get('textlien_gammespinee');
 $helper->fields_value['lien_gammespinee'] = Configuration::get('lien_gammespinee');
 $helper->fields_value['image_gammespinee'] = Configuration::get('image_gammespinee');

 return $helper->generateForm($fields_form);
}


}
?>

Link to comment
Share on other sites

Il y a pas mal de chose qui ne vont pas dans ton code.

Il faut revoir les méthodes install et uninstall pour créér/supprimer les champs que tu as ajouté dans ConfigurationObject et retirer la requête SQL qui supprime une table que tu n'as jamais créé.

 

Dans ta méthode getContent, attention aux contrôles de saisie ! Tu utilises toujours isGenericName ce qui n'est pas approprié pour certains de tes champs.

C'est dans cette méthode que tu dois ajouter la gestion du fichier que tu envois, prends exemple sur la méthode postProcess du controller admin AdminAttachmentsController.

Attention toutefois à ajouter un contrôle de fichier sur l'extention et/ou le mime type.

Pour cela tu peux utiliser la class ImageManager et la méthode isRealImage, tu trouveras d'autres méthodes utiles pour créer des miniatures etc...

 

Dans ta méthode displayForm, cette ligne est inutile:

$helper->fields_value['image_gammespinee'] = Configuration::get('image_gammespinee');

En effet on ne peut affecter de valeur à un input file.

 

Globalement il faut nettoyer ton code.

Edited by Matt75 (see edit history)
Link to comment
Share on other sites

Merci pour ta réponse. Je suis débutant en prestashop et c'est pas toujours évident de comprendre l'ensemble de tes demandes. Je sais qu'il a quelques futes mais je n'arrive pas à faire fonctionner cet upload. Voici le code que j'ai actuellement (même si j'ai essayé pas mal de possibilités).

 

<?php
if (!defined('_PS_VERSION_'))
 exit;

class GammeSpinee extends Module  // CHANGER LA CLASSE POUR UN NOUVEAU MODULE
{
 public function __construct()
 {
   $this->name = 'gammespinee';
   $this->tab = 'front_office_features';
   $this->version = '1.0';
   $this->author = 'DEV04';
   $this->need_instance = 0;
   $this->ps_versions_compliancy = array('min' => '1.5', 'max' => '1.6');
   $this->dependencies = array('blockcart');
 $this->fieldImageSettings = array('name' => 'image', 'dir' => 'example');
$this->fields_list = array('file' => array('title' => $this->l('File')));

   parent::__construct();

   $this->displayName = $this->l('LA GAMME SPINNE');
   $this->description = $this->l('Bloc se trouvant sur la page d\'accueil');


   $this->confirmUninstall = $this->l('dbcreation ne sera pas tenu responsable de la suppression de ce module');

   if (!Configuration::get('MYMODULE_NAME'))	  
  $this->warning = $this->l('No name provided');
 }

public function install()
{
  if (parent::install() == false)
 return false;
   return true;

  return parent::install() &&
 $this->registerHook('leftColumn') &&
 $this->registerHook('Home') &&
 $this->registerHook('header') &&
 Configuration::updateValue('MYMODULE_NAME', 'my friend');
}


public function hookDisplayHome($params)
{
  $this->context->smarty->assign(
   array(
 'my_module_name' => Configuration::get('MYMODULE_NAME'),
 'titre_gammespinee' => Configuration::get('titre_gammespinee'),
 'bloc_gammespinee' => Configuration::get('bloc_gammespinee'),
 'textlien_gammespinee' => Configuration::get('textlien_gammespinee'),
 'lien_gammespinee' => Configuration::get('lien_gammespinee'),
 'file' => Configuration::get('file'),
 'my_module_link' => $this->context->link->getModuleLink('gammespinee', 'display')
   )
  );
  return $this->display(__FILE__, 'gammespinee.tpl');
}

public function hookDisplayRightColumn($params)
{
  return $this->hookDisplayLeftColumn($params);
}

public function hookDisplayHeader()
{
  $this->context->controller->addCSS($this->_path.'css/gammespinee.css', 'all');
}


public function uninstall()
{
  if (!parent::uninstall())
 Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'gammespinee`');
  parent::uninstall();
}


public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
{
 parent::getList((int)$id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop);

 if (count($this->_list))
 {
  $this->product_attachements = Attachment::getProductAttached((int)$id_lang, $this->_list);

  $list_product_list = array();
  foreach ($this->_list as $list)
  {
   $product_list = '';
   if (isset($this->product_attachements[$list['id_attachment']]))
   {
 foreach ($this->product_attachements[$list['id_attachment']] as $product)
  $product_list .= $product.', ';
   }
   $list_product_list[$list['id_attachment']] = $product_list;
  }

  // Assign array in list_action_delete.tpl
  $this->tpl_delete_link_vars = array(
   'product_list' => $list_product_list,
   'product_attachements' => $this->product_attachements
  );
 }
}

public function getContent()
{
 $output = null;

 if (Tools::isSubmit('submit'.$this->name))
 {
  $titre_gammespinee = strval(Tools::getValue('titre_gammespinee'));
  if (!$titre_gammespinee  || empty($titre_gammespinee) || !Validate::isGenericName($titre_gammespinee))
   $output .= $this->displayError( $this->l('Invalid Configuration value') );
  else
  {
   Configuration::updateValue('titre_gammespinee', $titre_gammespinee);
   $output .= $this->displayConfirmation($this->l('Settings updated'));
  }

  $bloc_gammespinee = strval(Tools::getValue('bloc_gammespinee'));
  if (!$bloc_gammespinee  || empty($bloc_gammespinee) || !Validate::isGenericName($bloc_gammespinee))
   $output .= $this->displayError( $this->l('Invalid Configuration value') );
  else
  {
   Configuration::updateValue('bloc_gammespinee', $bloc_gammespinee);
  }

  $textlien_gammespinee = strval(Tools::getValue('textlien_gammespinee'));
  if (!$textlien_gammespinee  || empty($textlien_gammespinee) || !Validate::isGenericName($textlien_gammespinee))
   $output .= $this->displayError( $this->l('Invalid Configuration value') );
  else
  {
   Configuration::updateValue('textlien_gammespinee', $textlien_gammespinee);
  }

  $lien_gammespinee = strval(Tools::getValue('lien_gammespinee'));
  if (!$lien_gammespinee  || empty($lien_gammespinee) || !Validate::isGenericName($lien_gammespinee))
   $output .= $this->displayError( $this->l('Invalid Configuration value') );
  else
  {
   Configuration::updateValue('lien_gammespinee', $lien_gammespinee);
  }

  $id = (int)Tools::getValue('id_attachment');
  if ($id && $a = new Attachment($id))
  {
   $_POST['file'] = $a->file;
   $_POST['mime'] = $a->mime;
  }
  if (!count($this->errors))
  {
   if (isset($_FILES['file']) && is_uploaded_file($_FILES['file']['tmp_name']))
   {
 if ($_FILES['file']['size'] > (Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 * 1024))
  $this->errors[] = sprintf(
   $this->l('File too large, maximum size allowed: %1$d kB. File size you\'re trying to upload is:  %2$d kB.'),
   (Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024),
   number_format(($_FILES['file']['size'] / 1024), 2, '.', '')
  );
 else
 {
  do $uniqid = sha1(microtime());
  while (file_exists(_PS_DOWNLOAD_DIR_.$uniqid));
  if (!copy($_FILES['file']['tmp_name'], _PS_DOWNLOAD_DIR_.$uniqid))
   $this->errors[] = $this->l('File copy failed');
  $_POST['file_name'] = $_FILES['file']['name'];
  @unlink($_FILES['file']['tmp_name']);
  $_POST['file'] = $uniqid;
  $_POST['mime'] = $_FILES['file']['type'];
 }
   }
   else if (array_key_exists('file', $_FILES) && (int)$_FILES['file']['error'] === 1)
   {
 $max_upload = (int)ini_get('upload_max_filesize');
 $max_post = (int)ini_get('post_max_size');
 $upload_mb = min($max_upload, $max_post);
 $this->errors[] = sprintf(
  $this->l('The File %1$s exceeds the size allowed by the server. The limit is set to %2$d MB.'),
  '<b>'.$_FILES['file']['name'].'</b> ',
  '<b>'.$upload_mb.'</b>'
 );
   }
   else if (!empty($_FILES['file']['tmp_name']))
 $this->errors[] = $this->l('No file or your file is not uploadable, please check your server configuration for the maximum upload size.');
   }
 }

 return $output.$this->displayForm();
}




public function postProcess()
{
 if (_PS_MODE_DEMO_)
 {
  $this->errors[] = Tools::displayError('This functionality has been disabled.');
  return;
 }

 if (Tools::isSubmit('submitAdd'.$this->table))
 {
  $id = (int)Tools::getValue('id_attachment');
  if ($id && $a = new Attachment($id))
  {
   $_POST['file'] = $a->file;
   $_POST['mime'] = $a->mime;
  }
  if (!count($this->errors))
  {
   if (isset($_FILES['file']) && is_uploaded_file($_FILES['file']['tmp_name']))
   {
 if ($_FILES['file']['size'] > (Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 * 1024))
  $this->errors[] = sprintf(
   $this->l('File too large, maximum size allowed: %1$d kB. File size you\'re trying to upload is:  %2$d kB.'),
   (Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024),
   number_format(($_FILES['file']['size'] / 1024), 2, '.', '')
  );
 else
 {
  do $uniqid = sha1(microtime());
  while (file_exists(_PS_DOWNLOAD_DIR_.$uniqid));
  if (!copy($_FILES['file']['tmp_name'], _PS_DOWNLOAD_DIR_.$uniqid))
   $this->errors[] = $this->l('File copy failed');
  $_POST['file_name'] = $_FILES['file']['name'];
  @unlink($_FILES['file']['tmp_name']);
  $_POST['file'] = $uniqid;
  $_POST['mime'] = $_FILES['file']['type'];
 }
   }
   else if (array_key_exists('file', $_FILES) && (int)$_FILES['file']['error'] === 1)
   {
 $max_upload = (int)ini_get('upload_max_filesize');
 $max_post = (int)ini_get('post_max_size');
 $upload_mb = min($max_upload, $max_post);
 $this->errors[] = sprintf(
  $this->l('The File %1$s exceeds the size allowed by the server. The limit is set to %2$d MB.'),
  '<b>'.$_FILES['file']['name'].'</b> ',
  '<b>'.$upload_mb.'</b>'
 );
   }
   else if (!empty($_FILES['file']['tmp_name']))
 $this->errors[] = $this->l('No file or your file is not uploadable, please check your server configuration for the maximum upload size.');
  }
  $this->validateRules();
 }
 return parent::postProcess();
}

public function displayForm()
{
 // Get default Language
 $default_lang = (int)Configuration::get('PS_LANG_DEFAULT');

 // Init Fields form array
 $fields_form[0]['form'] = array(
  'legend' => array(
   'title' => $this->l('Modifications des données'),
  ),
  'input' => array(
   array(
 'type' => 'text',
 'label' => $this->l('Titre du bloc'),
 'name' => 'titre_gammespinee',
 'size' => 40,
 'required' => true
   ),
   array(
 'type' => 'textarea',
 'label' => $this->l('Contenu du bloc'),
 'name' => 'bloc_gammespinee',
 'rows' => 5,
 'cols' => 40,
 'desc' => $this->l('ATTENTION A LA LONGEUR DU TEXTE')
		 ),
   array(
 'type' => 'text',
 'label' => $this->l('En savoir plus'),
 'name' => 'textlien_gammespinee',
 'size' => 40
   ),
   array(
 'type' => 'text',
 'label' => $this->l('Lien'),
 'name' => 'lien_gammespinee',
 'size' => 40
   ),
   array(
  'type'   =>   'file',
  'label'  =>   $this->l('Sélectionner une image'),
  'desc'  =>  $this->l('Format : 105px x 140px. Formats autorisés : jpeg, png, jpg, gif.'),
  'name'   =>   'file',
  'required' =>   true,
  'lang'  =>  false,
  'display_image' => true,
 ),
  ),
  'submit' => array(
   'title' => $this->l('Save'),
   'class' => 'button'
  )
 );

 $helper = new HelperForm();

 // Module, token and currentIndex
 $helper->module = $this;
 $helper->name_controller = $this->name;
 $helper->token = Tools::getAdminTokenLite('AdminModules');
 $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;

 // Language
 $helper->default_form_language = $default_lang;
 $helper->allow_employee_form_lang = $default_lang;

 // Title and toolbar
 $helper->title = $this->displayName;
 $helper->show_toolbar = true;	    // false -> remove toolbar
 $helper->toolbar_scroll = true;	  // yes - > Toolbar is always visible on the top of the screen.
 $helper->submit_action = 'submit'.$this->name;
 $helper->toolbar_btn = array(
  'save' =>
  array(
   'desc' => $this->l('Save'),
   'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.
   '&token='.Tools::getAdminTokenLite('AdminModules'),
  ),
  'back' => array(
   'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
   'desc' => $this->l('Back to list')
  )
 );

 // Load current value
 $helper->fields_value['titre_gammespinee'] = Configuration::get('titre_gammespinee');
 $helper->fields_value['bloc_gammespinee'] = Configuration::get('bloc_gammespinee');
 $helper->fields_value['textlien_gammespinee'] = Configuration::get('textlien_gammespinee');
 $helper->fields_value['lien_gammespinee'] = Configuration::get('lien_gammespinee');

 return $helper->generateForm($fields_form);
}


}
?>

 

Pour la fonction getList je ne sais pas mais cela ne marche pas avec et sans non plus. J'ai pourtant réutilisé le postProcess. Pour ce qui est de la miniature c'est vraiment secondaire dans mon cas. Du moment que le nom du fichier actuel est indiqué...

 

Si quelqu'un pouvait m'aiguiller un peu. En sachant que je ne comprend pas grand chose aux fonctions.

Link to comment
Share on other sites

Salut,

 

J'ai fais un module d'exemple en reprenant ton code.

Pour modifier le texte, il te suffit d'utiliser l'outil de traduction de Prestashop. (Sur la page de configuration du module, en bas clique sur le drapeau Français)

A noter que tu peux redimensionner l'image si tu le souhaites à l'aide de la méthode resize de la classe ImageManager.

 

Lien de téléchargement supprimé, voir messages suivants.

 

A+

Edited by Matt75 (see edit history)
Link to comment
Share on other sites

Ca marche super bien, sauf qu'il n'y a pas de vignette ni le nom de l'image actuelle, mais ça c'est pas grave !

 

Je vais bien lire l'ensemble du code et essayer de comprendre comment tout cela fonctionne. En plus il y a un wysiwyg, URL,... Enfin bref tout pour faire mon bonheur à l'avenir.

 

Un très grand merci à toi.

Link to comment
Share on other sites

J'ai essayé de faire un code le plus propre et lisible possible, n'hésites pas à poser des questions sur les zones d'ombres.

 

MAJ : Ajout de la miniature sur la page de configuration

gammespinee.zip

 

Note : Lorsqu'on souhaite supprimer l'image, il y a un message d'erreur au dessus du message de confirmation de suppression de l'image.

L'image est bien supprimée, c'est juste un bug de AdminController qui ne vérifie pas si un id est spécifié ce qui pose problème.

L1805 de AdminController

if (isset($_GET['deleteImage']))

Devrait être

if (isset($_GET['deleteImage']) && $this->id_object)

Si quelqu'un pouvait proposer ça sur la forge...

 

A+

Edited by Matt75 (see edit history)
  • Like 1
  • Thanks 1
Link to comment
Share on other sites

  • 2 months later...
  • 6 months later...

Salut !

 

Je remonte ce post pour poser une simple question.
 

Matt75 : j'ai repris ton code pour l'upload de photo, so thx ! 

 

Ma question est : pourquoi je n'arrive pas à uploader des photos de plus de 2Mo ? Lorsque j'essaye, ca bloque à la partie copy : (File copy failed). Je n'arrive pas à comprendre pourquoi. J'ai regarder dans mon fichier config/config.inc.php, et la taille du 'upload_max_filesize' est à 100Mo (par défaut). 

 

Est ce au moment du hachage du nom du fichier ?

 

Merci d'avance ;)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...