Загрузка нескольких файлов в теме Shopify Debut - PullRequest
1 голос
/ 14 февраля 2020

Я настраиваю свою страницу для загрузки нескольких файлов (фотографий). Это код, который у меня есть, и по этой ссылке он должен работать: https://shopify.dev/tutorials/customize-theme-get-customization-information-for-products в ссылке go на «Разрешить загрузку файлов», если вы хотите проверить.

{% form 'product', product, class:form_classes, data-product-form: '', enctype:"multipart/form-data" %}
            {% unless product.has_only_default_variant %}
              <div class="product-form__controls-group">
                {% for option in product.options_with_values %}
                  <div class="selector-wrapper js product-form__item">

                    <select class="single-option-selector single-option-selector-{{ section.id }} product-form__input"
                      id="SingleOptionSelector-{{ forloop.index0 }}"
                      data-index="option{{ forloop.index }}"
                    >
                      {% for value in option.values %}
                        <option value="{{ value | escape }}"{% if option.selected_value == value %} selected="selected"{% endif %}>{{ value }}</option>
                      {% endfor %}
                    </select>
                  </div>
                {% endfor %}
              </div>
            {% endunless %}

            <select name="id" id="ProductSelect-{{ section.id }}" class="product-form__variants no-js">
              {% for variant in product.variants %}
                <option value="{{ variant.id }}"
                  {%- if variant == current_variant %} selected="selected" {%- endif -%}
                >
                  {{ variant.title }}  {%- if variant.available == false %} - {{ 'products.product.sold_out' | t }}{% endif %}
                </option>
              {% endfor %}
            </select>

            {% if section.settings.show_quantity_selector %}
            {% comment %}
              <div class="product-form__controls-group">
                <div class="product-form__item">
                  <input type="number" id="Quantity-{{ section.id }}"
                    name="quantity" value="1" min="1" pattern="[0-9]*"
                    class="product-form__input product-form__input--quantity" data-quantity-input
                  >
                </div>
              </div>

                <div class="qtydiv">
                {% comment %}<label for="Quantity" class="quantity-selector">Quantity</label>{% endcomment %}
                <div class="qtybox">
                  <span class="btnqty qtyminus icon icon-minus">-</span>
                  <input type="text" id="quantity" name="quantity" value="1" min="1" class="quantity-selector quantity-input" readonly="">
                  <span class="btnqty qtyplus icon icon-plus">+</span>
                </div>
              </div>
        {% endcomment %}
            {% endif %}

            <div class="product-form__error-message-wrapper product-form__error-message-wrapper--hidden{% if section.settings.enable_payment_button %} product-form__error-message-wrapper--has-payment-button{% endif %}"
              data-error-message-wrapper
              role="alert"
            >
              <span class="visually-hidden">{{ 'general.accessibility.error' | t }} </span>
              {% include 'icon-error' %}
              <span class="product-form__error-message" data-error-message>{{ 'products.product.quantity_minimum_message' | t }}</span>
            </div>

            <div class="product-form__controls-group product-form__controls-group--submit">
              <div class="qtydiv">
                {% comment %}<label for="Quantity" class="quantity-selector">Quantity</label>{% endcomment %}
                <div class="qtybox">
                  <span class="btnqty qtyminus icon icon-minus">-</span>
                  <input type="text" id="quantity" name="quantity" value="1" min="1" class="quantity-selector quantity-input" readonly="">
                  <span class="btnqty qtyplus icon icon-plus">+</span>
                </div>
              </div>
              <div class="product-form__item product-form__item--submit
                {%- if section.settings.enable_payment_button %} product-form__item--payment-button {%- endif -%}
                {%- if product.has_only_default_variant %} product-form__item--no-variants {%- endif -%}"
              >
                <button type="submit" name="add"
                  {% unless current_variant.available %} aria-disabled="true"{% endunless %}
                  aria-label="{% unless current_variant.available %}{{ 'products.product.sold_out' | t }}{% else %}{{ 'products.product.add_to_cart' | t }}{% endunless %}"
                  class="btn product-form__cart-submit{% if section.settings.enable_payment_button %} btn--secondary-accent{% endif %}"
                  data-add-to-cart>
                  <span data-add-to-cart-text>
                    {% unless current_variant.available %}
                      {{ 'products.product.sold_out' | t }}
                    {% else %}
                      {{ 'products.product.add_to_cart' | t }}
                    {% endunless %}
                  </span>
                  <span class="hide" data-loader>
                    {% include 'icon-spinner' %}
                  </span>
                </button>
                {% if section.settings.enable_payment_button %}
                  {{ form | payment_button }}
                {% endif %}
              </div>
                    <input required class="required product-form__input" id="photo" type="file" name="properties[Photo]" multiple>
              </div>
            </div>
          {% endform %}

Это моя форма, которая по ссылке должна иметь атрибут

enctype = "multipart / form-data".

Внизу формы она находится в типе ввода = "file".

<input required class="required product-form__input" id="photo" type="file" name="properties[Photo]" multiple>

И это код в cart-template.liquid.

<div class="list-view-item__title">
                      <a href="{{ item.url }}" class="cart__product-title" data-cart-item-title>
                        {{ item.product.title }}<br>
                        {% assign property_size = item.properties | size %}
                          {% if property_size > 0 %}
                            {% for p in item.properties %}
                                {{ item.properties.count }}
                              {% assign first_character_in_key = p.first | truncate: 1, '' %}
                              {% unless p.last == blank or first_character_in_key == '_' %}
                                {{ p.first }}:
                                {% if p.last contains '/uploads/' %}
                                  <a class="lightbox" href="{{ p.last }}">{{ property_size }}</a>
                                {% else %}
                                  {{ p.last }}
                                {% endif %}
                                <br>
                              {% endunless %}
                            {% endfor %}
                          {% endif %}
                      </a>
                    </div>

Проблема в том, что переменная property_size получает значение один, даже если я загружаю два или более изображений, хотя на самом деле я должен вернуть сумму свойства, которыми обладает элемент. Кто-нибудь может мне помочь? Что я делаю не так?

1 Ответ

0 голосов
/ 14 февраля 2020

Тема Debut, вероятно, изменилась с момента загрузки этого учебника, и поскольку она не поддерживается, вероятно, не будет обновлена.

Если вы добавите вход type="text" вместо type="file", свойство добавляется как ожидалось. Это происходит потому, что функция _initAddToCart (assets/theme.js строка 6447) получает элемент формы HTML и передает его другой функции.

var $data = $(this.selectors.productForm, this.$container);
this._addItemToCart($data);

Затем в функции _addItemToCart (assets/theme.js строка 6513), форма сериализована в строку:

var params = {
  url: '/cart/add.js',
  data: $(data).serialize(),
  dataType: 'json',
};
$.post(params).done(...

Эта функция будет игнорировать входные данные файла, как описано в документации jQuery:

Data from file select elements is not serialized.

Для отправки файла можно использовать API браузера FormData . Но чтобы использовать его с вызовом jQuery AJAX, необходимо установить некоторые свойства :

var params = {
  url: '/cart/add.js',
  // data: $(data).serialize(),
  dataType: 'json',
  // Disable the jQuery data processing, and send the FormData object
  contentType: false,
  processData: false,
  data: new FormData($(data).get()[0])
};
$.post(params).done(...

Однако, поскольку файл HTML <input> имеет name="properties[Photo]", только последний из загруженных файлов будет добавлен в свойство Photo элемента корзины. Я пробовал с name="properties[Photo][]", но вызов cart/add.js возвращает только ошибку 500 с сообщением «Внутренняя ошибка сервера».

Таким образом, чтобы загрузить несколько файлов, вы можете добавить собственный код в функцию _addItemToCart , чтобы получить каждый файл из <input> и , добавить к FormData с различным ключом для каждого файла.

...