PHP|Débutant :: Forums

Advertisement

Besoin d'aide ? N'hésitez pas, mais respectez les règles

Vous n'êtes pas identifié(e).

#1 Re : Forum Général PHP » Probleme variable smarty => php » 16-03-2016 11:14:32

Merci pour ton aide.
Te l'expliquer, non pas vraiment je suis plus que novice dans le domaine de la programmation (je m'y suis mis le jour meme du poste sur le forum ;-)  )
Pour le bout de code que j'ai mis il fait partie d'un fichier .tpl plus complet je te le post si dessous il est appelé par Product.php dont je te joint egalement le code.
Suis vraiment perdu et n'arrive pas a mais fin.... je vais t'avouer que je deprime completement de ne pas y arriver

product.tpl

{include file=$tpl_dir./errors.tpl}
{if $errors|@count == 0}
<script type="text/javascript">
// <![CDATA[

// PrestaShop internal settings
var currencySign = '{$currencySign|html_entity_decode:2:"UTF-8"}';
var currencyRate = '{$currencyRate|floatval}';
var currencyFormat = '{$currencyFormat|intval}';
C
var taxRate = {$product->tax_rate|floatval};
var jqZoomEnabled = {if $jqZoomEnabled}true{else}false{/if};

//JS Hook
var oosHookJsCodeFunctions = new Array();

// Parameters
var id_product = '{$product->id|intval}';
var productHasAttributes = {if isset($groups)}true{else}false{/if};
var quantitiesDisplayAllowed = {if $display_qties == 1}true{else}false{/if};
var quantityAvailable = {if $display_qties == 1 && $product->quantity}{$product->quantity}{else}0{/if};
var allowBuyWhenOutOfStock = {if $allow_oosp == 1}true{else}false{/if};
var availableNowValue = '{$product->available_now|escape:'quotes':'UTF-8'}';
var availableLaterValue = '{$product->available_later|escape:'quotes':'UTF-8'}';
var productPriceWithoutReduction = {$product->getPriceWithoutReduct()|default:'null'};
var reduction_percent = {if $product->reduction_percent}{$product->reduction_percent}{else}0{/if};
var reduction_price = {if $product->reduction_percent}0{else}{$product->getPrice(true, $smarty.const.NULL, 2, $smarty.const.NULL, true)}{/if};
var reduction_from = '{$product->reduction_from}';
var reduction_to = '{$product->reduction_to}';
var group_reduction = '{$group_reduction}';
var default_eco_tax = {$product->ecotax};
var currentDate = '{$smarty.now|date_format:'%Y-%m-%d'}';
var maxQuantityToAllowDisplayOfLastQuantityMessage = {$last_qties};
var noTaxForThisProduct = {if $no_tax == 1}true{else}false{/if};
var displayPrice = {$priceDisplay};

// Customizable field
var img_ps_dir = '{$img_ps_dir}';
var customizationFields = new Array();
{assign var='imgIndex' value=0}
{assign var='textFieldIndex' value=0}
{foreach from=$customizationFields item='field' name='customizationFields'}
{assign var='key' value='pictures_'|cat:$product->id|cat:'_'|cat:$field.id_customization_field}
  customizationFields[{$smarty.foreach.customizationFields.index|intval}] = new Array();
  customizationFields[{$smarty.foreach.customizationFields.index|intval}][0] = '{if $field.type|intval == 0}img{$imgIndex++}{else}textField{$textFieldIndex++}{/if}';
  customizationFields[{$smarty.foreach.customizationFields.index|intval}][1] = {if $field.type|intval == 0 AND $pictures.$key}2{else}{$field.required|intval}{/if};
{/foreach}

// Images
var img_prod_dir = '{$img_prod_dir}';
var combinationImages = new Array();
{foreach from=$combinationImages item='combination' key='combinationId' name='f_combinationImages'}
combinationImages[{$combinationId}] = new Array();
{foreach from=$combination item='image' name='f_combinationImage'}
combinationImages[{$combinationId}][{$smarty.foreach.f_combinationImage.index}] = {$image.id_image|intval};
{/foreach}
{/foreach}

combinationImages[0] = new Array();
{foreach from=$images item='image' name='f_defaultImages'}
combinationImages[0][{$smarty.foreach.f_defaultImages.index}] = {$image.id_image};
{/foreach}

// Translations
var doesntExist = '{l s='The product does not exist in this model. Please choose another.' js=1}';
var doesntExistNoMore = '{l s='This product is no longer in stock' js=1}';
var doesntExistNoMoreBut = '{l s='with those attributes but is available with others' js=1}';
var uploading_in_progress = '{l s='Uploading in progress, please wait...' js=1}';
var fieldRequired = '{l s='Please fill all required fields' js=1}';


{if isset($groups)}
  // Combinations
  {foreach from=$combinations key=idCombination item=combination}
    addCombination({$idCombination|intval}, new Array({$combination.list}), {$combination.quantity}, {$combination.price}, {$combination.ecotax}, {$combination.id_image}, '{$combination.reference|addslashes}');
  {/foreach}
  // Colors
  {if $colors|@count > 0}
    {if $product->id_color_default}var id_color_default = {$product->id_color_default|intval};{/if}
  {/if}
{/if}

//]]>
</script>

{include file=$tpl_dir./breadcrumb.tpl}


<div id="primary_block">

  <h2>{$product->name|escape:'htmlall':'UTF-8'}</h2>
  {if $confirmation}
  <p class="confirmation">
    {$confirmation}
  </p>
  {/if}

  <!-- right infos-->
  <div id="pb-right-column">
    <!-- product img-->
    <div id="image-block">
    {if $have_image}
        <img src="{$link->getImageLink($product->link_rewrite, $cover.id_image, 'large')}" {if $jqZoomEnabled}class="jqzoom" alt="{$link->getImageLink($product->link_rewrite, $cover.id_image, 'thickbox')}"{else} title="{$product->name|escape:'htmlall':'UTF-8'}" alt="{$product->name|escape:'htmlall':'UTF-8'}" {/if} id="bigpic"/>
    {else}
      <img src="{$img_prod_dir}{$lang_iso}-default-large.jpg" alt="" title="{$product->name|escape:'htmlall':'UTF-8'}" />
    {/if}
    </div>

    {if count($images) > 0}
    <!-- thumbnails -->
    <div id="views_block" {if count($images) < 2}class="hidden"{/if}>
    {if count($images) > 3}<span class="view_scroll_spacer"><a id="view_scroll_left" class="hidden" title="{l s='Other views'}" href="javascript:{ldelim}{rdelim}">{l s='Previous'}</a></span>{/if}
    <div id="thumbs_list">
      <ul style="width: {math equation="width * nbImages" width=80 nbImages=$images|@count}px" id="thumbs_list_frame">
        {foreach from=$images item=image name=thumbnails}
        {assign var=imageIds value=`$product->id`-`$image.id_image`}
        <li id="thumbnail_{$image.id_image}">
          <a href="{$link->getImageLink($product->link_rewrite, $imageIds, 'thickbox')}" rel="other-views" class="{if !$jqZoomEnabled}thickbox{/if} {if $smarty.foreach.thumbnails.first}shown{/if}" title="{$image.legend|htmlspecialchars}">
            <img id="thumb_{$image.id_image}" src="{$link->getImageLink($product->link_rewrite, $imageIds, 'medium')}" alt="{$image.legend|htmlspecialchars}" height="{$mediumSize.height}" width="{$mediumSize.width}" />
          </a>
        </li>
        {/foreach}
      </ul>
    </div>
    {if count($images) > 3}<a id="view_scroll_right" title="{l s='Other views'}" href="javascript:{ldelim}{rdelim}">{l s='Next'}</a>{/if}
    </div>
    {/if}
    {if count($images) > 1}<p class="align_center clear"><a id="resetImages" href="{$link->getProductLink($product)}" onclick="return (false);">{l s='Display all pictures'}</a></p>{/if}
    <!-- usefull links-->
    <ul id="usefull_link_block">
      {if $HOOK_EXTRA_LEFT}{$HOOK_EXTRA_LEFT}{/if}
      <li><a href="javascript:print();">{l s='Print'}</a><br class="clear" /></li>
      {if $have_image && !$jqZoomEnabled}
      <li><span id="view_full_size" class="span_link">{l s='View full size'}</span></li>
      {/if}
    </ul>
  </div>

  <!-- left infos-->
  <div id="pb-left-column">
    {if $product->description_short OR $packItems|@count > 0}
    <div id="short_description_block">
      {if $product->description_short}
        <div id="short_description_content" class="rte align_justify">{$product->description_short}</div>
      {/if}
      {if $product->description}
      <p class="buttons_bottom_block"><a href="javascript:{ldelim}{rdelim}" class="button">{l s='More details'}</a></p>
      {/if}
      {if $packItems|@count > 0}
        <h3>{l s='Pack content'}</h3>
        {foreach from=$packItems item=packItem}
          <div class="pack_content">
            {$packItem.pack_quantity} x <a href="{$link->getProductLink($packItem.id_product, $packItem.link_rewrite, $packItem.category)}">{$packItem.name|escape:'htmlall':'UTF-8'}</a>
            <p>{$packItem.description_short}</p>
          </div>
        {/foreach}
      {/if}
    </div>
    {/if}

    {if $colors}
    <!-- colors -->
    <div id="color_picker">
      <p>{l s='Pick a color:' js=1}</p>
      <div class="clear"></div>
      <ul id="color_to_pick_list">
      {foreach from=$colors key='id_attribute' item='color'}
        <li><a id="color_{$id_attribute|intval}" class="color_pick" style="background: {$color.value};" onclick="updateColorSelect({$id_attribute|intval});">{if file_exists($col_img_dir|cat:$id_attribute|cat:'.jpg')}<img src="{$img_col_dir}{$id_attribute}.jpg" alt="" title="{$color.name}" />{/if}</a></li>
      {/foreach}
      </ul>
        <a id="color_all" onclick="updateColorSelect(0);"><img src="{$img_dir}icon/cancel.gif" alt="" title="{$color.name}" /></a>
      <div class="clear"></div>
    </div>
    {/if}

    <!-- add to cart form-->
    <form id="buy_block" action="{$base_dir}cart.php" method="post">

      <!-- hidden datas -->
      <p class="hidden">
        <input type="hidden" name="token" value="{$static_token}" />
        <input type="hidden" name="id_product" value="{$product->id|intval}" id="product_page_product_id" />
        <input type="hidden" name="add" value="1" />
        <input type="hidden" name="id_product_attribute" id="idCombination" value="" />
      </p>

      <!-- prices -->
      <p class="price">
        {if $product->on_sale}
          <img src="{$img_dir}onsale_{$lang_iso}.gif" alt="{l s='On sale'}" class="on_sale_img"/>
          <span class="on_sale">{l s='On sale!'}</span>
        {elseif ($product->reduction_price != 0 || $product->reduction_percent != 0) && ($product->reduction_from == $product->reduction_to OR ($smarty.now|date_format:'%Y-%m-%d' <= $product->reduction_to && $smarty.now|date_format:'%Y-%m-%d' >= $product->reduction_from))}
          <span class="discount">{l s='Price lowered!'}</span>
        {/if}
        <br />
        <span class="our_price_display">
        {if !$priceDisplay || $priceDisplay == 2}
          <span id="our_price_display">{convertPrice price=$product->getPrice(true, $smarty.const.NULL, 2)}</span>
            {l s='tax incl.'}
        {/if}
        {if $priceDisplay == 1}
          <span id="our_price_display">{convertPrice price=$product->getPrice(false, $smarty.const.NULL, 2)}</span>
            {l s='tax excl.'}
        {/if}
        </span>
        {if $priceDisplay == 2}
          <br />
          <span id="pretaxe_price"><span id="pretaxe_price_display">{convertPrice price=$product->getPrice(false, $smarty.const.NULL, 2)}</span> {l s='tax excl.'}</span>
        {/if}
        <br />
      </p>
      {if ($product->reduction_price != 0 || $product->reduction_percent != 0) && ($product->reduction_from == $product->reduction_to OR ($smarty.now|date_format:'%Y-%m-%d' <= $product->reduction_to && $smarty.now|date_format:'%Y-%m-%d' >= $product->reduction_from))}
        <p id="old_price"><span class="bold">
        {if !$priceDisplay || $priceDisplay == 2}
          <span id="old_price_display">{convertPrice price=$product->getPriceWithoutReduct()}</span>
            {l s='tax incl.'}
        {/if}
        {if $priceDisplay == 1}
          <span id="old_price_display">{convertPrice price=$product->getPriceWithoutReduct(true)}</span>
            {l s='tax excl.'}
        {/if}
        </span>
        </p>
      {/if}
      {if $product->reduction_percent != 0 && ($product->reduction_from == $product->reduction_to OR ($smarty.now|date_format:'%Y-%m-%d' <= $product->reduction_to && $smarty.now|date_format:'%Y-%m-%d' >= $product->reduction_from))}
        <p id="reduction_percent">{l s='(price reduced by'} <span id="reduction_percent_display">{$product->reduction_percent|floatval}</span> %{l s=')'}</p>
      {/if}
      {if $packItems|@count}
        <p class="pack_price">{l s='instead of'} <span style="text-decoration: line-through;">{convertPrice price=$product->getNoPackPrice()}</span></p>
        <br class="clear" />
      {/if}
      {if $product->ecotax != 0}
        <p class="price-ecotax">{l s='include'} <span id="ecotax_price_display">{convertPrice price=$product->ecotax}</span> {l s='for green tax'}</p>
      {/if}

      {if isset($groups)}

      <!-- attributes -->
      <div id="attributes">
      {foreach from=$groups key=id_attribute_group item=group}
      <p>
        <label for="group_{$id_attribute_group|intval}">{$group.name|escape:'htmlall':'UTF-8'} :</label>
        {assign var='groupName' value='group_'|cat:$id_attribute_group}
        <select name="{$groupName}" id="group_{$id_attribute_group|intval}" onchange="javascript:findCombination();">
          {foreach from=$group.attributes key=id_attribute item=group_attribute}
            <option value="{$id_attribute|intval}"{if (isset($smarty.get.$groupName) && $smarty.get.$groupName|intval == $id_attribute) || $group.default == $id_attribute} selected="selected"{/if}>{$group_attribute|escape:'htmlall':'UTF-8'}</option>
          {/foreach}
        </select>
      </p>
      {/foreach}
      </div>
      {/if}

      {if $product->reference}<p id="product_reference" {if isset($groups)}style="display:none;"{/if}><label for="product_reference">{l s='Reference :'} </label><span class="editable">{$product->reference|escape}</span></p>{/if}

      <!-- quantity wanted -->
      <p id="quantity_wanted_p"{if (!$allow_oosp && $product->quantity == 0) || $virtual} style="display:none;"{/if}>
        <label>{l s='Quantity :'}</label>
        <input type="text" name="qty" id="quantity_wanted" class="text" value="{if isset($quantityBackup)}{$quantityBackup|intval}{else}1{/if}" size="2" maxlength="3" />
      </p>

      <!-- availability -->
      <p id="availability_statut"{if ($allow_oosp && $product->quantity == 0 && !$product->available_later) || (!$product->available_now && $display_qties != 1) } style="display:none;"{/if}>
        <span id="availability_label">{l s='Availability:'}</span>
        <span id="availability_value"{if $product->quantity == 0} class="warning-inline"{/if}>
          {if $product->quantity == 0}{if $allow_oosp}{$product->available_later}{else}{l s='This product is no longer in stock'}{/if}{else}{$product->available_now}{/if}
        </span>
      </p>

      <!-- number of item in stock -->
      <p id="pQuantityAvailable"{if $display_qties != 1 || ($allow_oosp && $product->quantity == 0)} style="display:none;"{/if}>
        <span id="quantityAvailable">{$product->quantity|intval}</span>
        <span{if $product->quantity > 1} style="display:none;"{/if} id="quantityAvailableTxt">{l s='item in stock'}</span>
        <span{if $product->quantity < 2} style="display:none;"{/if} id="quantityAvailableTxtMultiple">{l s='items in stock'}</span>
      </p>
     
      <!-- Out of stock hook -->
      <p id="oosHook"{if $product->quantity > 0} style="display:none;"{/if}>
        {$HOOK_PRODUCT_OOS}
      </p>

      <p class="warning-inline" id="last_quantities"{if ($product->quantity > $last_qties || $product->quantity == 0) || $allow_oosp} style="display:none;"{/if} >{l s='Warning: Last items in stock!'}</p>

      <p{if !$allow_oosp && $product->quantity == 0} style="display:none;"{/if} id="add_to_cart" class="buttons_bottom_block"><input type="submit" name="Submit" value="{l s='Add to cart'}" class="exclusive" /></p>
      {if $HOOK_PRODUCT_ACTIONS}
        {$HOOK_PRODUCT_ACTIONS}
      {/if}
    </form>
    {if $HOOK_EXTRA_RIGHT}{$HOOK_EXTRA_RIGHT}{/if}
  </div>
</div>
<br class="clear" />

{if $quantity_discounts}
<!-- quantity discount -->
<ul class="idTabs">
  <li><a style="cursor: pointer">{l s='Quantity discount'}</a></li>
</ul>
<div id="quantityDiscount">
  <table class="std">
      <tr>
        {foreach from=$quantity_discounts item='quantity_discount' name='quantity_discounts'}
        <th>{$quantity_discount.quantity|intval}
        {if $quantity_discount.quantity|intval > 1}
          {l s='quantities'}
        {else}
          {l s='quantity'}
        {/if}
        </th>
        {/foreach}
      </tr>
      <tr>
        {foreach from=$quantity_discounts item='quantity_discount' name='quantity_discounts'}
        <td>
        {if $quantity_discount.id_discount_type|intval == 1}
          -{$quantity_discount.value|floatval}%
        {else}
          -{convertPrice price=$quantity_discount.value|floatval}
        {/if}
        </td>
        {/foreach}
      </tr>
  </table>
</div>
{/if}

{$HOOK_PRODUCT_FOOTER}

<!-- description and features -->
{if $product->description || $features || $accessories || $HOOK_PRODUCT_TAB || $attachments}
<div id="more_info_block" class="clear">
  <ul id="more_info_tabs" class="idTabs idTabsShort">
    {if $product->description}<li><a id="more_info_tab_more_info" href="#idTab1">{l s='More info'}</a></li>{/if}
    {if $features}<li><a id="more_info_tab_data_sheet" href="#idTab2">{l s='Data sheet'}</a></li>{/if}
    {if $attachments}<li><a id="more_info_tab_attachments" href="#idTab9">{l s='Download'}</a></li>{/if}
    {if isset($accessories) AND $accessories}<li><a href="#idTab4">{l s='Accessories'}</a></li>{/if}
    {$HOOK_PRODUCT_TAB}
  </ul>
  <div id="more_info_sheets" class="sheets align_justify">
  {if $product->description}
    <!-- full description -->
    <div id="idTab1" class="rte" text-align="left" >
   
   
   
    <!-- test module {$product->description} c'est ici que ca merde-->

{assign var='prodConvert' value=$product->description} // assignation de la variable pour le transfere a php
 
{php}
 
$myVar = $this->get_template_vars('prodConvert'); // recuperation de la variable
 
 
echo  "$myVar<br /><br />"; // controle de cette variable, la il m'affiche bien l'adresse (du type : http://www.bacata.net/RSS/CT%20White_FR.xml)
 
//ouverture du fichier xml
 
$reader = new XMLReader();
 
$reader->open("$this->get_template_vars('prodConvert')"); //ici si je tape l'adresse manuellement ca fonctionne mais avec la variable ca ne fonctionne pas ???
 
//on parcours le fichier xml
 
while($reader->read())
  {
 
  //rechercher de l'élément nommé 'item'
 
  if ($reader->nodeType == XMLREADER::ELEMENT && $reader->localName == "description")
    {
     
      //Lecture de son contenu
 
      if ($reader->read())    
     
        {
        $valeur = ($reader->value);
        //afficher la valeur de l'élément
 
        echo  "$valeur<br /><br />";
        }
    }
  }
 
{/php}


    <!-- fin de test  -->
   
   
   
   
    </div>
  {/if}
  {if $features}
    <!-- product's features -->
    <ul id="idTab2" class="bullet">
    {foreach from=$features item=feature}
      <li><span>{$feature.name|escape:'htmlall':'UTF-8'}</span> {$feature.value|escape:'htmlall':'UTF-8'}</li>
    {/foreach}
    </ul>
  {/if}
  {if $attachments}
    <ul id="idTab9" class="bullet">
    {foreach from=$attachments item=attachment}
      <li><a href="{$base_dir}attachment.php?id_attachment={$attachment.id_attachment}">{$attachment.name|escape:'htmlall':'UTF-8'}</a><br />{$attachment.description|escape:'htmlall':'UTF-8'}</li>
    {/foreach}
    </ul>
  {/if}
  {if isset($accessories) AND $accessories}
    <!-- accessories -->
    <ul id="idTab4" class="bullet">
      <div class="block products_block accessories_block">
        <div class="block_content">
          <ul>
          {foreach from=$accessories item=accessory name=accessories_list}
            {assign var='accessoryLink' value=$link->getProductLink($accessory.id_product, $accessory.link_rewrite, $accessory.category)}
            <li class="ajax_block_product {if $smarty.foreach.accessories_list.first}first_item{elseif $smarty.foreach.accessories_list.last}last_item{else}item{/if} product_accessories_description">
              <h5 class="align_center"><a href="{$accessoryLink|escape:'htmlall':'UTF-8'}">{$accessory.name|truncate:22:'...'|escape:'htmlall':'UTF-8'}</a></h5>
              <p class="product_desc">
                <a href="{$accessoryLink|escape:'htmlall':'UTF-8'}" title="{$accessory.legend|escape:'htmlall':'UTF-8'}" class="product_image"><img src="{$link->getImageLink($accessory.link_rewrite, $accessory.id_image, 'medium')}" alt="{$accessory.legend|escape:'htmlall':'UTF-8'}" /></a>
                <a href="{$accessoryLink|escape:'htmlall':'UTF-8'}" title="{l s='More'}" class="product_description">{$accessory.description_short|strip_tags|truncate:100:'...'}</a>
              </p>
              <p class="product_accessories_price">
                <span class="price">{displayWtPrice p=$accessory.price}</span>
                <a class="button" href="{$accessoryLink|escape:'htmlall':'UTF-8'}" title="{l s='View'}">{l s='View'}</a>
                <a class="button ajax_add_to_cart_button" href="{$base_dir}cart.php?qty=1&id_product={$accessory.id_product|intval}&token={$static_token}&add" rel="ajax_id_product_{$accessory.id_product|intval}" title="{l s='Add to cart'}">{l s='Add to cart'}</a>
              </p>
            </li>
          {/foreach}
          </ul>
        </div>
      </div>
      <div class="clear"></div>
    </ul>
  {/if}
  {$HOOK_PRODUCT_TAB_CONTENT}
  </div>
</div>
{/if}

<!-- Customizable products -->
{if $product->customizable}
  <ul class="idTabs">
    <li><a style="cursor: pointer">{l s='Product customization'}</a></li>
  </ul>
  <div class="customization_block">
    <form method="post" action="{$customizationFormTarget}" enctype="multipart/form-data" id="customizationForm">
      <p>
        <img src="{$img_dir}icon/infos.gif" alt="Informations" />
        {l s='After saving your customized product, do not forget to add it to your cart.'}
        {if $product->uploadable_files}<br />{l s='Allowed file formats are: GIF, JPG, PNG'}{/if}
      </p>
      {if $product->uploadable_files|intval}
      <h2>{l s='Pictures'}</h2>
      <ul id="uploadable_files">
        {counter start=0 assign='customizationField'}
        {foreach from=$customizationFields item='field' name='customizationFields'}
          {if $field.type == 0}
            <li class="customizationUploadLine{if $field.required} required{/if}">{assign var='key' value='pictures_'|cat:$product->id|cat:'_'|cat:$field.id_customization_field}
              {if isset($pictures.$key)}<div class="customizationUploadBrowse"><img src="{$pic_dir}{$pictures.$key}_small" alt="" /><a href="{$link->getUrlWith('deletePicture', $field.id_customization_field)}"><img src="{$img_dir}icon/delete.gif" alt="{l s='delete'}" class="customization_delete_icon" /></a></div>{/if}
              <div class="customizationUploadBrowse"><input type="file" name="file{$field.id_customization_field}" id="img{$customizationField}" class="customization_block_input {if isset($pictures.$key)}filled{/if}" />{if $field.required}<sup>*</sup>{/if}
              <div class="customizationUploadBrowseDescription">{if !empty($field.name)}{$field.name}{else}{l s='Please select an image file from your hard drive'}{/if}</div></div>
            </li>
            {counter}
          {/if}
        {/foreach}
      </ul>
      {/if}
      <div class="clear"></div>
      {if $product->text_fields|intval}
      <h2>{l s='Texts'}</h2>
      <ul id="text_fields">
        {counter start=0 assign='customizationField'}
        {foreach from=$customizationFields item='field' name='customizationFields'}
          {if $field.type == 1}
            <li class="customizationUploadLine{if $field.required} required{/if}">{assign var='key' value='textFields_'|cat:$product->id|cat:'_'|cat:$field.id_customization_field}
              {if !empty($field.name)}{$field.name}{/if}<input type="text" name="textField{$field.id_customization_field}" id="textField{$customizationField}" value="{if isset($textFields.$key)}{$textFields.$key|stripslashes}{/if}" class="customization_block_input" />{if $field.required}<sup>*</sup>{/if}
            </li>
            {counter}
          {/if}
        {/foreach}
      </ul>
      {/if}
      <p style="clear: left;" id="customizedDatas">
        <input type="hidden" name="quantityBackup" id="quantityBackup" value="" />
        <input type="hidden" name="submitCustomizedDatas" value="1" />
        <input type="button" class="button" value="{l s='Save'}" onclick="javascript:saveCustomization()" />
      </p>
    </form>
    <p class="clear required"><sup>*</sup> {l s='required fields'}</p>
  </div>
{/if}

{if $packItems|@count > 0}
  <div>
    <h2>{l s='Pack content'}</h2>
    {include file=$tpl_dir./product-list.tpl products=$packItems}
  </div>
{/if}

{/if}

Product.php

<?php
include(dirname(__FILE__).'/config/config.inc.php');

include_once(dirname(__FILE__).'/init.php');

//will be initialized bellow...
if(intval(Configuration::get('PS_REWRITING_SETTINGS')) === 1)
  $rewrited_url = null;

function pictureUpload(Product $product, Cart $cart)
{
  global $errors;

  if (!$fieldIds = $product->getCustomizationFieldIds())
    return false;
  $authorizedFileFields = array();
  foreach ($fieldIds AS $fieldId)
    if ($fieldId['type'] == _CUSTOMIZE_FILE_)
      $authorizedFileFields[intval($fieldId['id_customization_field'])] = 'file'.intval($fieldId['id_customization_field']);
  $indexes = array_flip($authorizedFileFields);
  foreach ($_FILES AS $fieldName => $file)
    if (in_array($fieldName, $authorizedFileFields) AND isset($file['tmp_name']) AND !empty($file['tmp_name']))
    {
      $fileName = md5(uniqid(rand(), true));
      if ($error = checkImage($file, intval(Configuration::get('PS_PRODUCT_PICTURE_MAX_SIZE'))))
        $errors[] = $error;
      if (!$tmpName = tempnam(_PS_TMP_IMG_DIR_, 'PS') OR !move_uploaded_file($file['tmp_name'], $tmpName))
        return false;
      /* Original file */
      elseif (!imageResize($tmpName, _PS_PROD_PIC_DIR_.$fileName))
        $errors[] = Tools::displayError('An error occurred during the image upload.');
      /* A smaller one */
      elseif (!imageResize($tmpName, _PS_PROD_PIC_DIR_.$fileName.'_small', intval(Configuration::get('PS_PRODUCT_PICTURE_WIDTH')), intval(Configuration::get('PS_PRODUCT_PICTURE_HEIGHT'))))
        $errors[] = Tools::displayError('An error occurred during the image upload.');
      elseif (!chmod(_PS_PROD_PIC_DIR_.$fileName, 0777) OR !chmod(_PS_PROD_PIC_DIR_.$fileName.'_small', 0777))
        $errors[] = Tools::displayError('An error occurred during the image upload.');
      else
        $cart->addPictureToProduct(intval($product->id), $indexes[$fieldName], $fileName);
      unlink($tmpName);
    }
  return true;
}

function textRecord(Product $product, Cart $cart)
{
  global $errors;

  if (!$fieldIds = $product->getCustomizationFieldIds())
    return false;
  $authorizedTextFields = array();
  foreach ($fieldIds AS $fieldId)
    if ($fieldId['type'] == _CUSTOMIZE_TEXTFIELD_)
      $authorizedTextFields[intval($fieldId['id_customization_field'])] = 'textField'.intval($fieldId['id_customization_field']);
  $indexes = array_flip($authorizedTextFields);
  foreach ($_POST AS $fieldName => $value)
    if (in_array($fieldName, $authorizedTextFields) AND !empty($value))
    {
      if (!Validate::isMessage($value))
        $errors[] = Tools::displayError('Invalid message');
      else
        $cart->addTextFieldToProduct(intval($product->id), $indexes[$fieldName], $value);
    }
    elseif (in_array($fieldName, $authorizedTextFields) AND empty($value))
      $cart->deleteTextFieldFromProduct(intval($product->id), $indexes[$fieldName]);
}

function formTargetFormat()
{
  global $smarty;
  $customizationFormTarget = Tools::safeOutput(urldecode($_SERVER['REQUEST_URI']));
  foreach ($_GET AS $field => $value)
    if (strncmp($field, 'group_', 6) == 0)
      $customizationFormTarget = preg_replace('/&group_([[:digit:]]+)=([[:digit:]]+)/', '', $customizationFormTarget);
  if (isset($_POST['quantityBackup']))
    $smarty->assign('quantityBackup', intval($_POST['quantityBackup']));
  $smarty->assign('customizationFormTarget', $customizationFormTarget);
}

/* CSS ans JS files calls */
$css_files = array(
  __PS_BASE_URI__.'css/thickbox.css' => 'screen'
);

$js_files = array(
  __PS_BASE_URI__.'js/jquery/thickbox-modified.js',
  __PS_BASE_URI__.'js/jquery/jquery.idTabs.modified.js',
  __PS_BASE_URI__.'js/jquery/jquery.scrollto.js',
  __PS_BASE_URI__.'js/jquery/jquery.serialScroll.js',
  _THEME_JS_DIR_.'tools.js',
  _THEME_JS_DIR_.'product.js'
);

/* jqZoom */
$jqZoomEnabled = (Configuration::get('PS_DISPLAY_JQZOOM') == 1);
if ($jqZoomEnabled)
{
  $js_files[] = __PS_BASE_URI__.'js/jquery/jquery.jqzoom.js';
  $css_files[__PS_BASE_URI__.'css/jqzoom.css'] = 'screen';
}

include_once(dirname(__FILE__).'/header.php');

global $errors;
$errors = array();

if (!isset($_GET['id_product']) OR !Validate::isUnsignedId($_GET['id_product']))
  $errors[] = Tools::displayError('product not found');
else
{
  $product = new Product(intval($_GET['id_product']), true, intval($cookie->id_lang));
  if (!Validate::isLoadedObject($product) OR !$product->active)
    $errors[] = Tools::displayError('product is no longer available');
  elseif (!$product->checkAccess(intval($cookie->id_customer)))
    $errors[] = Tools::displayError('you do not have access to this product');
  else
  {
    $smarty->assign('virtual', ProductDownload::getIdFromIdProduct(intval($product->id)));
   
    /* rewrited url set */
    $rewrited_url = $link->getProductLink($product->id, $product->link_rewrite);
   
    /* Product pictures management */
    require_once('images.inc.php');
    $smarty->assign('customizationFormTarget', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));
    if (Tools::isSubmit('submitCustomizedDatas'))
    {
      pictureUpload($product, $cart);
      textRecord($product, $cart);
      formTargetFormat();
    }
    elseif (isset($_GET['deletePicture']) AND !$cart->deletePictureToProduct(intval($product->id), intval(Tools::getValue('deletePicture'))))
      $errors[] = Tools::displayError('An error occured while deleting the selected picture');

    $files = $cookie->getFamily('pictures_'.intval($product->id));
    $textFields = $cookie->getFamily('textFields_'.intval($product->id));
    $smarty->assign(array(
      'pictures' => $files,
      'textFields' => $textFields));

    $productPriceWithTax = floatval($product->getPrice(true, NULL, 2));
    $productPriceWithoutEcoTax = floatval($productPriceWithTax - $product->ecotax);
    $configs = Configuration::getMultiple(array('PS_ORDER_OUT_OF_STOCK', 'PS_LAST_QTIES'));

    /* Features / Values */
    $features = $product->getFrontFeatures(intval($cookie->id_lang));
    $attachments = $product->getAttachments(intval($cookie->id_lang));
   
    /* Category */
    $category = false;
    if (isset($_SERVER['HTTP_REFERER']) AND preg_match('!^(.*)\/([0-9]+)\-(.*[^\.])|(.*)id_category=([0-9]+)(.*)$!', $_SERVER['HTTP_REFERER'], $regs) AND !strstr($_SERVER['HTTP_REFERER'], '.html'))
    {
      if (isset($regs[2]) AND is_numeric($regs[2]))
      {
        if (Product::idIsOnCategoryId(intval($product->id), array('0' => array('id_category' => intval($regs[2])))))
          $category = new Category(intval($regs[2]), intval($cookie->id_lang));
      }
      elseif (isset($regs[5]) AND is_numeric($regs[5]))
      {
        if (Product::idIsOnCategoryId(intval($product->id), array('0' => array('id_category' => intval($regs[5])))))
          $category = new Category(intval($regs[5]), intval($cookie->id_lang));
      }
    }
    if (!$category)
      $category = new Category($product->id_category_default, intval($cookie->id_lang));

    if (isset($category) AND Validate::isLoadedObject($category))
    {
      $smarty->assign(array(
      'category' => $category,
      'subCategories' => $category->getSubCategories(intval($cookie->id_lang), true),
      'id_category_current' => intval($category->id),
      'id_category_parent' => intval($category->id_parent),
      'return_category_name' => Tools::safeOutput(Category::hideCategoryPosition($category->name))));
    }

    $smarty->assign(array(
      'return_link' => (isset($category->id) AND $category->id) ? Tools::safeOutput($link->getCategoryLink($category)) : 'javascript: history.back();',
      'path' => ((isset($category->id) AND $category->id) ? Tools::getFullPath(intval($category->id), $product->name) : Tools::getFullPath(intval($product->id_default_category), $product->name))
    ));

    /* /Quantity discount management */
    $smarty->assign(array(
      'quantity_discounts' => QuantityDiscount::getQuantityDiscounts(intval($product->id), $product->getPriceWithoutReduct()),
      'product' => $product,
      'jqZoomEnabled' => $jqZoomEnabled,
      'product_manufacturer' => new Manufacturer(intval($product->id_manufacturer)),
      'token' => Tools::getToken(false),
      'productPriceWithoutEcoTax' => floatval($productPriceWithoutEcoTax),
      'features' => $features,
      'attachments' => $attachments,
      'allow_oosp' => $product->isAvailableWhenOutOfStock(intval($product->out_of_stock)),
      'last_qties' =>  intval($configs['PS_LAST_QTIES']),
      'group_reduction' => (100 - Group::getReduction(intval($cookie->id_customer))) / 100,
      'col_img_dir' => _PS_COL_IMG_DIR_,
      'HOOK_EXTRA_LEFT' => Module::hookExec('extraLeft'),
      'HOOK_EXTRA_RIGHT' => Module::hookExec('extraRight'),
      'HOOK_PRODUCT_OOS' => Hook::productOutOfStock($product),
      'HOOK_PRODUCT_FOOTER' => Hook::productFooter($product, $category),
      'HOOK_PRODUCT_ACTIONS' => Module::hookExec('productActions'),
      'HOOK_PRODUCT_TAB' =>  Module::hookExec('productTab'),
      'HOOK_PRODUCT_TAB_CONTENT' =>  Module::hookExec('productTabContent')));
   
    $images = $product->getImages(intval($cookie->id_lang));
    $productImages = array();
    foreach ($images AS $k => $image)
    {
      if ($image['cover'])
      {
        $smarty->assign('mainImage', $images[0]);
        $cover = $image;
        $cover['id_image'] = intval($product->id).'-'.$cover['id_image'];
        $cover['id_image_only'] = intval($image['id_image']);
      }
      $productImages[intval($image['id_image'])] = $image;
    }
    if (!isset($cover))
      $cover = array('id_image' => Language::getIsoById($cookie->id_lang).'-default', 'legend' => 'No picture', 'title' => 'No picture');
    $size = Image::getSize('large');
    $smarty->assign(array(
      'cover' => $cover,
      'imgWidth' => intval($size['width']),
      'mediumSize' => Image::getSize('medium'),
      'accessories' => $product->getAccessories(intval($cookie->id_lang))));
    if (sizeof($productImages))
      $smarty->assign('images', $productImages);

    // Tax
    $tax_datas = Db::getInstance()->getRow('
    SELECT p.`id_tax`, t.`rate`
    FROM `'._DB_PREFIX_.'product` p
    LEFT JOIN `'._DB_PREFIX_.'tax` AS t ON t.`id_tax` = p.`id_tax`
    WHERE p.`id_product` = '.intval($product->id));
    $tax = floatval(Tax::getApplicableTax(intval($tax_datas['id_tax']), floatval($tax_datas['rate'])));
    /* Attributes / Groups & colors */
    $colors = array();
    $attributesGroups = $product->getAttributesGroups(intval($cookie->id_lang));

    if (Db::getInstance()->numRows())
    {
      $combinationImages = $product->getCombinationImages(intval($cookie->id_lang));
      foreach ($attributesGroups AS $k => $row)
      {
        /* Color management */
        if (isset($row['attribute_color']) AND $row['attribute_color'] AND $row['id_attribute_group'] == $product->id_color_default)
        {
          $colors[$row['id_attribute']]['value'] = $row['attribute_color'];
          $colors[$row['id_attribute']]['name'] = $row['attribute_name'];
        }

        $groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']] = $row['attribute_name'];
        $groups[$row['id_attribute_group']]['name'] = $row['public_group_name'];
        if ($row['default_on'])
          $groups[$row['id_attribute_group']]['default'] = intval($row['id_attribute']);
        if (!isset($groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']]))
          $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] = 0;
        $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] += intval($row['quantity']);

        $combinations[$row['id_product_attribute']]['attributes_values'][$row['id_attribute_group']] = $row['attribute_name'];
        $combinations[$row['id_product_attribute']]['attributes'][] = intval($row['id_attribute']);
        $combinations[$row['id_product_attribute']]['price'] = floatval($row['price']);
        $combinations[$row['id_product_attribute']]['ecotax'] = floatval($row['ecotax']);
        $combinations[$row['id_product_attribute']]['weight'] = floatval($row['weight']);
        $combinations[$row['id_product_attribute']]['quantity'] = intval($row['quantity']);
        $combinations[$row['id_product_attribute']]['reference'] = $row['reference'];
        $combinations[$row['id_product_attribute']]['id_image'] = isset($combinationImages[$row['id_product_attribute']][0]['id_image']) ? $combinationImages[$row['id_product_attribute']][0]['id_image'] : -1;
      }
      //wash attributes list (if some attributes are unavailables and if allowed to wash it)
      if (Configuration::get('PS_DISP_UNAVAILABLE_ATTR') == 0)
        foreach ($groups AS &$group)
          foreach ($group['attributes_quantity'] AS $key => &$quantity)
            if (!$quantity)
              unset($group['attributes'][$key]);
     
      foreach ($combinations AS $id_product_attribute => $comb)
      {
        $attributeList = '';
        foreach ($comb['attributes'] AS $id_attribute)
          $attributeList .= '\''.intval($id_attribute).'\',';
        $attributeList = rtrim($attributeList, ',');
        $combinations[$id_product_attribute]['list'] = $attributeList;
      }
      $smarty->assign(array(
        'groups' => $groups,
        'combinaisons' => $combinations, /* Kept for compatibility purpose only */
        'combinations' => $combinations,
        'colors' => (sizeof($colors) AND $product->id_color_default) ? $colors : false,
        'combinationImages' => $combinationImages));
    }
    $smarty->assign(array(
      'no_tax' => Tax::excludeTaxeOption() OR !Tax::getApplicableTax(intval($product->id_tax), 1),
      'customizationFields' => $product->getCustomizationFields(intval($cookie->id_lang))
    ));
   
    // Pack management
    $smarty->assign('packItems', Pack::getItemTable($product->id, intval($cookie->id_lang), true));
    $smarty->assign('packs', Pack::getPacksTable($product->id, intval($cookie->id_lang), true, 1));
  }
}

$smarty->assign(array(
  'ENT_NOQUOTES' => ENT_NOQUOTES,
  'outOfStockAllowed' => intval(Configuration::get('PS_ORDER_OUT_OF_STOCK')),
  'errors' => $errors,
  'categories' => Category::getHomeCategories(intval($cookie->id_lang)),
  'have_image' => Product::getCover(intval(Tools::getValue('id_product'))),
  'display_qties' => intval(Configuration::get('PS_DISPLAY_QTIES')),
  'display_ht' => !Tax::excludeTaxeOption()));

if (file_exists(_PS_THEME_DIR_.'thickbox.tpl'))
  $smarty->display(_PS_THEME_DIR_.'thickbox.tpl');
$smarty->assign(array(
  'currencySign' => $currency->sign,
  'currencyRate' => $currency->conversion_rate,
  'currencyFormat' => $currency->format,
  'currencyBlank' => $currency->blank)
  );
$smarty->display(_PS_THEME_DIR_.'product.tpl');

include(dirname(__FILE__).'/footer.php');

?>

#2 Forum Général PHP » Probleme variable smarty => php » 16-03-2016 11:14:32

regnierjoffrey
Réponses : 3

Bonjour,
je vous expose mon petit soucis,

j'ai du malheureusement trouver une solution pas très commode pour lire une fichier xml dans le template d'une boutique en ligne (prstashop). Au fur et à mesure du temps j'ai réussi a me débrouiller pour développper un p'tit bout de code qui fonctionne correctement si je tape l'adresse manuellement dans ce code mais cela ne m'arrange pas puisque chaque produit a son propre fichier xml. J'ai donc fait quelques modifications afin qu'il aille chercher le fichier lui-même. et c'est là que je dois donc passer une variable de smarty vers php. Mais, parce qu'il y a un mais, cela ne m'affiche rien. J'ai fait une vérif avec un echo là ca fonctionne, mais on dirait qu'il ne prend pas la variable pour direction.

si quelqu'un pouvais m'aider, je suis super dans la m...

{assign var='prodConvert' value=$product->description} // assignation de la variable pour le transfere a php

{php}

$myVar = $this->get_template_vars('prodConvert'); // recuperation de la variable


echo  "$myVar<br /><br />"; // controle de cette variable, la il m'affiche bien l'adresse (du type : http://www.bacata.net/RSS/CT%20White_FR.xml)

//ouverture du fichier xml

$reader = new XMLReader();

$reader->open("$this->get_template_vars('prodConvert')"); //ici si je tape l'adresse manuellement ca fonctionne mais avec la variable ca ne fonctionne pas ???

//on parcours le fichier xml

while($reader->read())
  {

  //rechercher de l'élément nommé 'item'

  if ($reader->nodeType == XMLREADER::ELEMENT && $reader->localName == "description")
    {
     
      //Lecture de son contenu

      if ($reader->read())   
     
        {
        $valeur = ($reader->value);
        //afficher la valeur de l'élément

        echo  "$valeur<br /><br />";
        }
    }
  }

{/php}

Pied de page des forums

Propulsé par FluxBB