Jump to content

Ajouter Un Champ Image Dans Les Catégories [Résolu]


Recommended Posts

Bonjour la communauté ! 

 

Je viens vers vous car pour concorder avec la charte graphique de mes pages catégories, j'ai besoin d'avoir la possibilité d'ajouter deux images dans l'en-tête de celle-ci (une image de fond et une autre image simple). J'ai trouvé sur le web ce tutoriel que j'ai suivi à la lettre. 

 

Mais voilà, si j'ai mon champ d'ajout pour la seconde image, je ne peux ni l'appeler, ni la supprimer (page blank quand je m'y essaie). 

Le tuto a été fait pour la version 1.6 et je suis en 1.6.1. Par exemple, je ne possède pas ces lignes dans mon AdminCategoriesController : 

protected function uploadImage($id, $name, $dir, $ext = false, $width = null, $height = null)
{

qu'il mentionne dans son article. Je l'ai quand même copié collé dans mon override. 

 

Enfin, l'image principale est appelée de cette façon dans mon template (dans header.tpl) : 

{if $category->description || $category->id_image }
			<div class="content_scene_cat block" {if $category->id_image}style="background-size:cover;background-image:url({$link->getCatImageLink($category->link_rewrite, $category->id_image, 'category_default')});background-repeat:no-repeat;width:100%;"{/if}>

Or, impossible d'appeler l'image2 de cette façon, ni de la façon mentionnée dans le tuto. L'image n'est pas retrouvée (j'ai l'impression qu'il lui donne le nom dans la catégorie au lieu du nom avec lequel elle a été enregistrée). 

 

Je ne comprends pas où peut être le problème, d'autant que je ne suis pas la plus à l'aise avec le PHP. 

 

Quelqu'un a-t-il déjà testé ce tutoriel et aurait quelques pistes par rapport aux soucis que je rencontre ? 

 

Je vous remercie ! 

 

Bien cordialement,

 

Edited by Mélissa (see edit history)
Link to comment
Share on other sites

Bonjour,

La premiere des choses à faire quand on s'essaye à ce genre de chose est d'activer les erreurs comme ca quand ca arrive c'est pas tout blanc... et on peut rechercher ce qu'il ne va pas.

 

dans ton /config/defines.inc.php

/* Debug only */
if (!defined('_PS_MODE_DEV_'))
	define('_PS_MODE_DEV_', true); 

je vais essayer de regarder le tuto, mais pour t'aider donne moi le contenu de tes fichiers.

 

cdt

  • Like 1
Link to comment
Share on other sites

Bonjour et merci pour ton aide. 

 

C'est chose faite pour l'activation des erreurs. 

Alors, voici le contenu de mes différents fichiers : 

 

Dans override / controllers / admin / adminCategoriesController.php : 

 

 

<?php class AdminCategoriesController extends AdminCategoriesControllerCore
{
	public function renderForm()
	{
		$this->initToolbar();

		/** @var Category $obj */
		$obj = $this->loadObject(true);
        $context = Context::getContext();
		$id_shop = $context->shop->id;
		$selected_categories = array((isset($obj->id_parent) && $obj->isParentCategoryAvailable($id_shop))? (int)$obj->id_parent : (int)Tools::getValue('id_parent', Category::getRootCategory()->id));
		$unidentified = new Group(Configuration::get('PS_UNIDENTIFIED_GROUP'));
		$guest = new Group(Configuration::get('PS_GUEST_GROUP'));
		$default = new Group(Configuration::get('PS_CUSTOMER_GROUP'));

		$unidentified_group_information = sprintf($this->l('%s - All people without a valid customer account.'), '<b>'.$unidentified->name[$this->context->language->id].'</b>');
		$guest_group_information = sprintf($this->l('%s - Customer who placed an order with the guest checkout.'), '<b>'.$guest->name[$this->context->language->id].'</b>');
		$default_group_information = sprintf($this->l('%s - All people who have created an account on this site.'), '<b>'.$default->name[$this->context->language->id].'</b>');

		if (!($obj = $this->loadObject(true)))
			return;

		$image = _PS_CAT_IMG_DIR_.$obj->id.'.jpg';
		$image_url = ImageManager::thumbnail($image, $this->table.'_'.(int)$obj->id.'.'.$this->imageType, 350,
			$this->imageType, true, true);
		$image_size = file_exists($image) ? filesize($image) / 1000 : false;
		
		$image2 = _PS_CAT_IMG_DIR_.$obj->id.'_second.jpg';
$image_url2 = ImageManager::thumbnail($image2, $this->table.'_'.(int)$obj->id.'_second.'.$this->imageType, 350,
    $this->imageType, true, true);
$image_size2 = file_exists($image2) ? filesize($image2) / 1000 : false;

		$this->fields_form = array(
			'tinymce' => true,
			'legend' => array(
				'title' => $this->l('Category'),
				'icon' => 'icon-tags'
			),
			'input' => array(
				array(
					'type' => 'text',
					'label' => $this->l('Name'),
					'name' => 'name',
					'lang' => true,
					'required' => true,
					'class' => 'copy2friendlyUrl',
					'hint' => $this->l('Invalid characters:').' <>;=#{}',
				),
				array(
					'type' => 'switch',
					'label' => $this->l('Displayed'),
					'name' => 'active',
					'required' => false,
					'is_bool' => true,
					'values' => array(
						array(
							'id' => 'active_on',
							'value' => 1,
							'label' => $this->l('Enabled')
						),
						array(
							'id' => 'active_off',
							'value' => 0,
							'label' => $this->l('Disabled')
						)
					)
				),
				array(
					'type'  => 'categories',
					'label' => $this->l('Parent category'),
					'name'  => 'id_parent',
					'tree'  => array(
						'id'                  => 'categories-tree',
						'selected_categories' => $selected_categories,
						'disabled_categories' => (!Tools::isSubmit('add'.$this->table) && !Tools::isSubmit('submitAdd'.$this->table)) ? array($this->_category->id) : null,
                        'root_category'       => $context->shop->getCategory()
					)
				),
				array(
					'type' => 'textarea',
					'label' => $this->l('Description'),
					'name' => 'description',
					'autoload_rte' => true,
					'lang' => true,
					'hint' => $this->l('Invalid characters:').' <>;=#{}'
				),
				array(
					'type' => 'file',
					'label' => $this->l('Image'),
					'name' => 'image',
					'display_image' => true,
					'image' => $image_url ? $image_url : false,
					'size' => $image_size,
					'delete_url' => self::$currentIndex.'&'.$this->identifier.'='.$this->_category->id.'&token='.$this->token.'&deleteImage=1',
					'hint' => $this->l('Upload a category logo from your computer.'),
				),
				array(
					'type' => 'file',
					'label' => $this->l('Image2'),
					'name' => 'image2',
					'display_image' => true,
					'image' => $image_url2 ? $image_url2 : false,
					'size' => $image_size2,
					'delete_url' => self::$currentIndex.'&'.$this->identifier.'='.$this->_category->id.'&token='.$this->token.'&deleteImage2=1',
					'hint' => $this->l('Upload a secondary category logo from your computer.'),
				),
				array(
					'type' => 'textarea',
					'label' => $this->l('Meta title'),
					'name' => 'meta_title',
					'lang' => true,
					'rows' => 5,
					'cols' => 100,
					'hint' => $this->l('Forbidden characters:').' <>;=#{}'
				),
				array(
					'type' => 'textarea',
					'label' => $this->l('Meta description'),
					'name' => 'meta_description',
					'lang' => true,
					'rows' => 5,
					'cols' => 100,
					'hint' => $this->l('Forbidden characters:').' <>;=#{}'
				),
				array(
					'type' => 'tags',
					'label' => $this->l('Meta keywords'),
					'name' => 'meta_keywords',
					'lang' => true,
					'hint' => $this->l('To add "tags," click in the field, write something, and then press "Enter."').' '.$this->l('Forbidden characters:').' <>;=#{}'
				),
				array(
					'type' => 'text',
					'label' => $this->l('Friendly URL'),
					'name' => 'link_rewrite',
					'lang' => true,
					'required' => true,
					'hint' => $this->l('Only letters, numbers, underscore (_) and the minus (-) character are allowed.')
				),
				array(
					'type' => 'group',
					'label' => $this->l('Group access'),
					'name' => 'groupBox',
					'values' => Group::getGroups(Context::getContext()->language->id),
					'info_introduction' => $this->l('You now have three default customer groups.'),
					'unidentified' => $unidentified_group_information,
					'guest' => $guest_group_information,
					'customer' => $default_group_information,
					'hint' => $this->l('Mark all of the customer groups which you would like to have access to this category.')
				)
			),
			'submit' => array(
				'title' => $this->l('Save'),
				'name' => 'submitAdd'.$this->table.($this->_category->is_root_category && !Tools::isSubmit('add'.$this->table) && !Tools::isSubmit('add'.$this->table.'root') ? '': 'AndBackToParent')
			)
		);

		$this->tpl_form_vars['shared_category'] = Validate::isLoadedObject($obj) && $obj->hasMultishopEntries();
		$this->tpl_form_vars['PS_ALLOW_ACCENTED_CHARS_URL'] = (int)Configuration::get('PS_ALLOW_ACCENTED_CHARS_URL');
		$this->tpl_form_vars['displayBackOfficeCategory'] = Hook::exec('displayBackOfficeCategory');

		// Display this field only if multistore option is enabled
		if (Configuration::get('PS_MULTISHOP_FEATURE_ACTIVE') && Tools::isSubmit('add'.$this->table.'root'))
		{
			$this->fields_form['input'][] = array(
				'type' => 'switch',
				'label' => $this->l('Root Category'),
				'name' => 'is_root_category',
				'required' => false,
				'is_bool' => true,
				'values' => array(
					array(
						'id' => 'is_root_on',
						'value' => 1,
						'label' => $this->l('Yes')
					),
					array(
						'id' => 'is_root_off',
						'value' => 0,
						'label' => $this->l('No')
					)
				)
			);
			unset($this->fields_form['input'][2],$this->fields_form['input'][3]);
		}
		// Display this field only if multistore option is enabled AND there are several stores configured
		if (Shop::isFeatureActive())
			$this->fields_form['input'][] = array(
				'type' => 'shop',
				'label' => $this->l('Shop association'),
				'name' => 'checkBoxShopAsso',
			);

		// remove category tree and radio button "is_root_category" if this category has the root category as parent category to avoid any conflict
		if ($this->_category->id_parent == (int)Configuration::get('PS_ROOT_CATEGORY') && Tools::isSubmit('updatecategory'))
			foreach ($this->fields_form['input'] as $k => $input)
				if (in_array($input['name'], array('id_parent', 'is_root_category')))
					unset($this->fields_form['input'][$k]);

		if (!($obj = $this->loadObject(true)))
			return;

		$image = ImageManager::thumbnail(_PS_CAT_IMG_DIR_.'/'.$obj->id.'.jpg', $this->table.'_'.(int)$obj->id.'.'.$this->imageType, 350, $this->imageType, true);
		$image2 = ImageManager::thumbnail(_PS_CAT_IMG_DIR_.'/'.$obj->id.'_second.jpg', $this->table.'_'.(int)$obj->id.'_second.'.$this->imageType, 350, $this->imageType, true);
		 
		$this->fields_value = array(
			'image' => $image ? $image : false,
			'size' => $image ? filesize(_PS_CAT_IMG_DIR_.'/'.$obj->id.'.jpg') / 1000 : false,
			'image2' => $image2 ? $image2 : false,
			'size2' => $image2 ? filesize(_PS_CAT_IMG_DIR_.'/'.$obj->id.'_second.jpg') / 1000 : false
		);
		
		// Added values of object Group
		$category_groups_ids = $obj->getGroups();

		$groups = Group::getGroups($this->context->language->id);
		// if empty $carrier_groups_ids : object creation : we set the default groups
		if (empty($category_groups_ids))
		{
			$preselected = array(Configuration::get('PS_UNIDENTIFIED_GROUP'), Configuration::get('PS_GUEST_GROUP'), Configuration::get('PS_CUSTOMER_GROUP'));
			$category_groups_ids = array_merge($category_groups_ids, $preselected);
		}
		foreach ($groups as $group)
			$this->fields_value['groupBox_'.$group['id_group']] = Tools::getValue('groupBox_'.$group['id_group'], (in_array($group['id_group'], $category_groups_ids)));

		$this->fields_value['is_root_category'] = (bool)Tools::isSubmit('add'.$this->table.'root');

		return AdminController :: renderForm() ;
	}
	
	protected function postImage($id)
	{
		$ret = parent::postImage($id);
		$generate_hight_dpi_images = (bool)Configuration::get('PS_HIGHT_DPI');

		if (($id_category = (int)Tools::getValue('id_category')) &&
			isset($_FILES) && count($_FILES) && $_FILES['image']['name'] != null &&
			file_exists(_PS_CAT_IMG_DIR_.$id_category.'.jpg'))
		{
			$images_types = ImageType::getImagesTypes('categories');
			foreach ($images_types as $k => $image_type)
			{
				ImageManager::resize(
					_PS_CAT_IMG_DIR_.$id_category.'.jpg',
					_PS_CAT_IMG_DIR_.$id_category.'-'.stripslashes($image_type['name']).'.jpg',
					(int)$image_type['width'], (int)$image_type['height']
				);

				if ($generate_hight_dpi_images)
					ImageManager::resize(
						_PS_CAT_IMG_DIR_.$id_category.'.jpg',
						_PS_CAT_IMG_DIR_.$id_category.'-'.stripslashes($image_type['name']).'2x.jpg',
						(int)$image_type['width']*2, (int)$image_type['height']*2
					);
			}
		}

		$ret2 = $this->uploadImage($id.'_second', 'image2', $this->fieldImageSettings['dir'].'/');
				if (($id_category = (int)Tools::getValue('id_category')) &&
					isset($_FILES) && count($_FILES) && $_FILES['image2']['name'] != null &&
					file_exists(_PS_CAT_IMG_DIR_.$id_category.'_second.jpg'))
				{
					$images_types = ImageType::getImagesTypes('categories');
					foreach ($images_types as $k => $image_type)
					{
						ImageManager::resize(
							_PS_CAT_IMG_DIR_.$id_category.'_second.jpg',
							_PS_CAT_IMG_DIR_.$id_category.'_second-'.stripslashes($image_type['name']).'.jpg',
							(int)$image_type['width'], (int)$image_type['height']
						);
					}
				}
				 
				return $ret && $ret2;
	}
	
	protected function uploadImage($id, $name, $dir, $ext = false, $width = null, $height = null)
{
    if (isset($_FILES[$name]['tmp_name']) && !empty($_FILES[$name]['tmp_name']))
    {
        // Delete old image
		if (Validate::isLoadedObject($object = $this->loadObject()))
		{
			if($name == 'image2')
				$object->deleteImage2();
			else $object->deleteImage();
		} else
			return false;
		 
        // Check image validity
        $max_size = isset($this->max_image_size) ? $this->max_image_size : 0;
        if ($error = ImageManager::validateUpload($_FILES[$name], Tools::getMaxUploadSize($max_size)))
            $this->errors[] = $error;
 
        $tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
        if (!$tmp_name)
            return false;
 
        if (!move_uploaded_file($_FILES[$name]['tmp_name'], $tmp_name))
            return false;
 
        // Evaluate the memory required to resize the image: if it's too much, you can't resize it.
        if (!ImageManager::checkImageMemoryLimit($tmp_name))
            $this->errors[] = Tools::displayError('Due to memory limit restrictions, this image cannot be loaded. Please increase your memory_limit value via your server\'s configuration settings. ');
 
        // Copy new image
        if (empty($this->errors) && !ImageManager::resize($tmp_name, _PS_IMG_DIR_.$dir.$id.'.'.$this->imageType, (int)$width, (int)$height, ($ext ? $ext : $this->imageType)))
            $this->errors[] = Tools::displayError('An error occurred while uploading the image.');
 
        if (count($this->errors))
            return false;
        if ($this->afterImageUpload())
        {
            unlink($tmp_name);
            return true;
        }
        return false;
    }
    return true;
}
	
					public function postProcess()
				{
					if (!in_array($this->display, array('edit', 'add')))
						$this->multishop_context_group = false;
					if (Tools::isSubmit('forcedeleteImage') || (isset($_FILES['image']) && $_FILES['image']['size'] > 0) || Tools::getValue('deleteImage'))
					{
						$this->processForceDeleteImage();
						if (Tools::isSubmit('forcedeleteImage'))
							Tools::redirectAdmin(self::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminCategories').'&conf=7');
					} else if(Tools::getValue('deleteImage2'))
					{
						$category = $this->loadObject(true);
				 
						if (Validate::isLoadedObject($category))
							if($category->deleteImage2(true))
								Tools::redirectAdmin(self::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminCategories').'&updatecategory&id_category='.$category->id.'&conf=7');
					}
				 
					return parent::postProcess();
				}

	
	
}



?>

 

 

 

Dans Override / Controllers / classes / Category.php : 

 

 

<?php 
Class Category extends CategoryCore
{
 
   public function deleteImage2($force_delete = false)
    {
        if (!$this->id)
            return false;
         
        if ($force_delete || !$this->hasMultishopEntries())
        {
            /* Deleting object images and thumbnails (cache) */
            if ($this->image_dir)
            {
                if (file_exists($this->image_dir.$this->id.'_second.'.$this->image_format)
                    && !unlink($this->image_dir.$this->id.'_second.'.$this->image_format))
                    return false;
            }
            if (file_exists(_PS_TMP_IMG_DIR_.$this->def['table'].'_'.$this->id.'_second.'.$this->image_format)
                && !unlink(_PS_TMP_IMG_DIR_.$this->def['table'].'_'.$this->id.'_second.'.$this->image_format))
                return false;
            if (file_exists(_PS_TMP_IMG_DIR_.$this->def['table'].'_mini_'.$this->id.'_second.'.$this->image_format)
                && !unlink(_PS_TMP_IMG_DIR_.$this->def['table'].'_mini_'.$this->id.'_second.'.$this->image_format))
                return false;
     
            $types = ImageType::getImagesTypes();
            foreach ($types as $image_type)
                if (file_exists($this->image_dir.$this->id.'_second-'.stripslashes($image_type['name']).'.'.$this->image_format)
                && !unlink($this->image_dir.$this->id.'_second-'.stripslashes($image_type['name']).'.'.$this->image_format))
                    return false;
        }
        return true;
    }
	
	public function getSubCategories($id_lang, $active = true)
	{
		$sql_groups_where = '';
		$sql_groups_join = '';
		if (Group::isFeatureActive())
		{
			$sql_groups_join = 'LEFT JOIN `'._DB_PREFIX_.'category_group` cg ON (cg.`id_category` = c.`id_category`)';
			$groups = FrontController::getCurrentCustomerGroups();
			$sql_groups_where = 'AND cg.`id_group` '.(count($groups) ? 'IN ('.implode(',', $groups).')' : '='.(int)Group::getCurrent()->id);
		}

		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
		SELECT c.*, cl.id_lang, cl.name, cl.description, cl.link_rewrite, cl.meta_title, cl.meta_keywords, cl.meta_description
		FROM `'._DB_PREFIX_.'category` c
		'.Shop::addSqlAssociation('category', 'c').'
		LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (c.`id_category` = cl.`id_category` AND `id_lang` = '.(int)$id_lang.' '.Shop::addSqlRestrictionOnLang('cl').')
		'.$sql_groups_join.'
		WHERE `id_parent` = '.(int)$this->id.'
		'.($active ? 'AND `active` = 1' : '').'
		'.$sql_groups_where.'
		GROUP BY c.`id_category`
		ORDER BY `level_depth` ASC, category_shop.`position` ASC');

		foreach ($result as &$row)
		{
			$row['id_image'] = Tools::file_exists_cache(_PS_CAT_IMG_DIR_.$row['id_category'].'.jpg') ? (int)$row['id_category'] : Language::getIsoById($id_lang).'-default';
			$row['id_image2'] = Tools::file_exists_cache(_PS_CAT_IMG_DIR_.$row['id_category'].'_second.jpg') ? (int)$row['id_category'] .'_second' : Language::getIsoById($id_lang).'-default';
			$row['legend'] = 'no picture';
		}
		return $result;
	}


}

?>

 

 

 

Enfin, dans mon header.tpl : 

 

 

 

{if $page_name=='category'}	
			{if $category->description || $category->id_image }
			<div class="content_scene_cat block" {if $category->id_image}style="background-size:cover;background-image:url({$link->getCatImageLink($category->link_rewrite, $category->id_image, 'category_default')});background-repeat:no-repeat;width:100%;"{/if}>
				 <div class="cat-info">
					<div class="cat-info-inner">
                        <div class="col-lg-6">
                        <div id="product_manufacturer">
                            <span class="editable">
                               <!-- ICI LE LOGO -->
    <img class="replace-2x" src="{$link->getCatImageLink($subcategory.link_rewrite, $subcategory.id_image2, 'medium_default')|escape:'html':'UTF-8'}" alt="" />			
                    
                            </span>
                        </div>
                        </div>
						{if $category->description}
						 	<div class="col-lg-6">
                               <div class="cat_desc rte">
                                   {if Tools::strlen($category->description) > 400}
                                     <div id="category_description_short">{$description_short}</div>
                                     <div id="category_description_full" class="unvisible">{$category->description}</div>
                                     <a href="{$link->getCategoryLink($category->id_category, $category->link_rewrite)|escape:'html':'UTF-8'}" class="lnk_more">{l s='More'}</a>
                            {else}
                                 <!-- <div class="meta_title_cat">{$category->meta_description}</div>  -->
                                <div class="desc_cat">{$category->description}</div>
                            {/if}
                               </div>
                           </div>
						{/if}
					</div>	
				</div>            			
			</div>
			{/if}
			{/if}
					

 

 

 

 

Link to comment
Share on other sites

Quand je cherche à supprimer l'image : 

Fatal error: Call to undefined method Category::deleteImage2() in /Users/melissa/Documents/Sites/eshop/prestashop/override/controllers/admin/AdminCategoriesController.php on line 336

 

Il ne reconnaît pas ceci : 

if($category->deleteImage2(true))

Je remarque que j'ai aussi un problème quand je cherche à ajouter une nouvelle image : 

Fatal error: Call to undefined method Category::deleteImage2() in /Users/melissa/Documents/Sites/eshop/prestashop/override/controllers/admin/AdminCategoriesController.php on line 285

Link to comment
Share on other sites

Call to undefined method Category::deleteImage2

Ca veut dire que je ne trouve pas la methode (function) deleteImage2 dans la classe Category.php (la en l'occurence c'est dans l'override).

 

Donc soit tu n'as pas declaré la fonction deleteImage2, soit l'override n'est pas prit en compte, il faut effacer le fichier class_index du dossier cache.

Link to comment
Share on other sites

Je me demande si cela ne vient pas du fichier htaccess

 

 Ou vas tu chercher ca ! tu as beaucoup d'imagination :)

 

Essaye de remplacer:

 

    <img class="replace-2x" src="{$link->getCatImageLink($subcategory.link_rewrite, $subcategory.id_image2, 'medium_default')|escape:'html':'UTF-8'}" alt="" />			
par:

 

    <img class="replace-2x" src="{$link->getCatImageLink($category.link_rewrite, $category.id_image2, 'medium_default')|escape:'html':'UTF-8'}" alt="" />            
Peux tu activer la console debug et faire une capture d ecran sur la variable categorie et subcategorie ?
Link to comment
Share on other sites

Mais non, c'est à cause de ce que le Monsieur disait dans son tutoriel !

Cela dit, oui, quand je désespère j'imagine tout et n'importe quoi.  :D

 

Alors j'ai testé, ça ne change rien. Concrètement, il ne se passe rien dans les messages d'erreur sauf qu'en faisant un inspect élément dans le code, ça donne ça : 

 <img class="replace-2x" src="<br />
<b>Fatal error</b>:  Cannot use object of type Category as array in <b>/Users/melissa/Documents/Sites/eshop/prestashop/cache/smarty/compile/26/48/e2/2648e2b0a29917121dea4f60ca52d0173bb61a9c.file.header.tpl.php</b> on line <b>299</b><br />

ou ça : 

 <img class="img-responsive" src="<br />
<b>Notice</b>:  Undefined index: subcategory in <b>/Users/melissa/Documents/Sites/eshop/prestashop/tools/smarty/sysplugins/smarty_internal_templatebase.php(171) : eval()'d code</b> on line <b>301</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>/Users/melissa/Documents/Sites/eshop/prestashop/tools/smarty/sysplugins/smarty_internal_templatebase.php(171) : eval()'d code</b> on line <b>301</b><br />
<br />
<b>Notice</b>:  Undefined index: subcategory in <b>/Users/melissa/Documents/Sites/eshop/prestashop/tools/smarty/sysplugins/smarty_internal_templatebase.php(171) : eval()'d code</b> on line <b>301</b><br />
<br />
<b>Notice</b>:  Trying to get property of non-object in <b>/Users/melissa/Documents/Sites/eshop/prestashop/tools/smarty/sysplugins/smarty_internal_templatebase.php(171) : eval()'d code</b> on line <b>301</b><br />
http://localhost:8888/eshop/prestashop/c/-medium_default/.jpg" alt="" width="797" height="674" />

La console m'indique un not found sur la variable en subcategory. 

Edited by Mélissa (see edit history)
Link to comment
Share on other sites

Bon j'ai fais le tuto, un peu ardu j'avoue... chez moi ca marche.

 

Ca affiche la deuxieme images quand la categorie est considéré comme une sous categorie. Il faut bien sur inclure le code tpl dans le foreach pour que ca s'affiche.

 

{foreach from=$subcategories item=subcategory}

<img class="replace-2x" src="{$link->getCatImageLink($subcategory.link_rewrite, $subcategory.id_image2, 'medium_default')|escape:'html':'UTF-8'}" alt="" width="{$mediumSize.width}" height="{$mediumSize.height}" />

etc...
tjs desespéré ? Edited by Alexandre-KM (see edit history)
Link to comment
Share on other sites

Par ailleurs ce tuto ne fait pas exactement ce que tu souhaite:

j'ai besoin d'avoir la possibilité d'ajouter deux images dans l'en-tête de celle-ci (une image de fond et une autre image simple)

ca ajoute bien deux images mais il faut modifier le tuto pour que la deuxieme image ne s affiche pas en sous cat mais soit bien une image complementaire a la categorie.

Link to comment
Share on other sites

Hm d'accord, effectivement. Chez moi aussi, ça fonctionne comme ça. Ce qui me fait répondre par l'affirmative.

 

Donc, si je veux que la fameuse image 2 soit appelée de la même façon que la 1, sans qu'elle soit affichée en tant que sous-catégorie, je dois adapter la fin du tuto ? Ce que je ne comprends pas, et ce qui me fait revenir à ma première question, c'est pourquoi, dans ce tuto, on copie la façon dont est appelée l'image 1 mais qu'il ne nous est pas possible d'appeler l'image 2 directement en tant qu'image de catégorie ? 

 

Ah, je pense avoir compris. L'appel que l'on copie à dans category.php est lié au moment où on veut appeler l'image principale de la catégorie en tant que sous-catégorie. Je dois donc trouver comment configurer l'affichage en tant qu'image de catégorie. 

 

Suis-je sur la bonne voie si je considère que ce que je devrais modifier se trouve plutôt là ? : 

public function __construct($id_category = null, $id_lang = null, $id_shop = null)
	{
		parent::__construct($id_category, $id_lang, $id_shop);
		$this->id_image = ($this->id && file_exists(_PS_CAT_IMG_DIR_.(int)$this->id.'.jpg')) ? (int)$this->id : false;
		$this->image_dir = _PS_CAT_IMG_DIR_;
	}

Pardon si je pars encore dans tous les sens, je me débrouille avec les trois pauvres cours de PHP que j'ai reçu…!

Link to comment
Share on other sites

Pardon si je pars encore dans tous les sens, je me débrouille avec les trois pauvres cours de PHP que j'ai reçu…!

ah tu sais sur internet, tu peux tout apprendre tout seul... y a un bon site : le site du zero: https://openclassrooms.com/courses/programmez-en-oriente-objet-en-php ça c un cours avancé mais y en a un sur les bases php.

 

Bref pour faire ce que tu veux je pense que tu es sur le bon chemin. Fais nous part de ta réussite, ca pourra en aider certains et si jamais tu galère trop je peux me pencher sur cette modif.

 

cordialement.

Edited by Alexandre-KM (see edit history)
Link to comment
Share on other sites

Alors ! Pour ceux qui serait intéressés par le fait d'appeler deux images de catégorie, voilà la dernière manip à faire. À place dans l'override Category.php : 

public function __construct($id_category = null, $id_lang = null, $id_shop = null)
	{
		parent::__construct($id_category, $id_lang, $id_shop);
		$this->id_image = ($this->id && file_exists(_PS_CAT_IMG_DIR_.(int)$this->id.'.jpg')) ? (int)$this->id : false;
		  $this->id_image2 = ($this->id && file_exists(_PS_CAT_IMG_DIR_.(int)$this->id.'_second.jpg')) ? $this->id . '_second': false;
		$this->image_dir = _PS_CAT_IMG_DIR_;
	}

Voilà, ce ne fut pas sans difficultés, mais ça fonctionne ! 

 

Un grand merci pour ton aide et ta patience, Alexandre !

Edited by Mélissa (see edit history)
  • Like 1
Link to comment
Share on other sites

  • 9 months later...

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...