FROM CACHE - es_header
RESUELTAS

Como actualizar el precio según variante y suscepción ?

GastonM
Visitante
3 0 0

Buenas que tal?

Me encuentro trabajando en una block app donde se listan las variante y los selling plan groups con sus selling plans. El problema es que no he logrado de ninguna manera actualizar los selling plan groups que se listan para cada variante, y por consiguiente tampoco el precio que ve el cliente final.

Segun la documentacion de shopify hay que actualizar el objeto producto segun la variante seleccionada, pero realmente no he logrado entender como funciona esto, ya que cada vez que intento actualizarlo, no sucede nada.

Sin contar con que la documentacion sobre el objeto producto habla de un monton de props que el objeto no tiene, como por ejemplo la selected_variant, que seria de vital ayuda para estas modificaciones!

A continuacion dejo la documentacion que estoy siguiendo, y un ejemplo de codigo del mismo.

https://shopify.dev/themes/product-merchandising/variants#shopify-option-selection

https://shopify.dev/themes/pricing-payments/subscriptions/selling-plans#update-selling-plan-informat...

HTML

 

{%- liquid
assign current_variant = product.selected_or_first_available_variant | default: product.variants.first
assign current_selling_plan_allocation = current_variant.selected_selling_plan_allocation

if current_selling_plan_allocation == nil and current_variant.requires_selling_plan
assign current_selling_plan_allocation = current_variant.selling_plan_allocations | first
endif

assign offer = current_selling_plan_allocation | default: current_variant
-%}

<h2>{{ product.title}}</h2>
{{ offer.price | money }}

<!-- <script>console.log({{ product | json }});</script> -->

{% if offer.compare_at_price > offer.price %}
<s>{{ offer.compare_at_price | money }}</s>
<span>{% if offer.selling_plan %}Subscription{% else %}Sale{% endif %}</span>
{% endif %}

{% form 'product', product, class:'shopify-product-form' %}
<input type="hidden" name="id" value="{{ current_variant.id }}">
<input type="hidden" name="selling_plan" value="{{ current_selling_plan_allocation.selling_plan.id | default: '' }}">

{% comment %}theme-check-disable ParserBlockingScriptTag{% endcomment %}
{{ 'option_selection.js' | shopify_asset_url | script_tag }}
{% comment %}theme-check-enable ParserBlockingScriptTag{% endcomment %}

<select id="product-select" name="id" class="select">
  {% for variant in product.variants %}
  <option value="{{ variant.id }}"
  {% if variant == product.selected_or_first_available_variant %}selected="selected"{% endif %}   
  >
  {{ variant.title }} - {{ variant.price | money }}
  </option>
  {% endfor %}
</select>

<fieldset class="selling-plan-fieldset" data-product='{{ product | json }}'>
    <legend>Purchase options</legend>
  <ul>
    <li>
      {% unless product.requires_selling_plan %}
        <input type="radio" name="purchase_option"> One-time purchase
        <hr>
      {% endunless %}
    </li>
    {% for group in product.selling_plan_groups %}
      {% unless product.selling_plan_groups.first == group %}
        <hr>
      {% endunless %}
   <li>
      <input type="radio" name="purchase_option" value="{{group.id}}" checked> {{ group.name}}
      {% for option in group.options %}
      <label>{{ option.name }}</label>
      <select data-position="{{ option.position }}" data-group="{{group.id}}">
        {% for value in option.values %}
          <option value="{{value}}" {% if product_option.selected_value == value %}selected{% endif %}>{{ value }}</option>
        {% endfor %}
      </select>
      {% endfor %}
    </li>
    {% endfor %}
  </ul>
</fieldset>

<p class="selling-plan">{{ line_item.selling_plan_allocation.selling_plan.name }}</p>

<button type="submit" name="add"
  class="product-form__submit button button--full-width {% if block.settings.show_dynamic_checkout and product.selling_plan_groups == empty %}button--secondary{% else %}button--primary{% endif %}"
  {% if product.selected_or_first_available_variant.available==false %}disabled{% endif %}>
  {%- if product.selected_or_first_available_variant.available -%}
  Add to cart
  {%- else -%}
  {{ 'products.product.sold_out' | t }}
  Sold out
  {%- endif -%}
</button>

{% endform %}

{% schema %}
{
  "name": "Subscription",
  "target": "section",
  "stylesheet": "subscription.css",
  "javascript": "subscription.js",
  "templates": ["product"],
  "settings": []
}
{% endschema %}

 

 

 

JS

 

var sellingPlanContainer = document.querySelector(".selling-plan-fieldset");
var product = JSON.parse(sellingPlanContainer.dataset.product);
var productForm = document.querySelector(".shopify-product-form");

var findSelectedVariant = function () {
  var selectedVariantId = parseInt(
    document.querySelector('.shopify-product-form [name="id"]').value
  );
  var selectedVariant;

  for (var i = 0; i < product.variants.length; i++) {
    if (product.variants[i].id === selectedVariantId) {
      selectedVariant = product.variants[i];
      break;
    }
  }

  return selectedVariant;
};

// Watch for variant selection to update selling plan option selectors
productForm.addEventListener("change", function (e) {
  var selectedVariant = findSelectedVariant();
  var availableSellingPlanAllocations =
    selectedVariant.selling_plan_allocations;

  console.log("change", e.target.attributes);

  var radioValue = e.target?.attributes[2]?.value || null;
  console.log("radio", radioValue);

  if (availableSellingPlanAllocations) {
    var sellingId = document.querySelector('[name="selling_plan"]').value;
    for (const e of availableSellingPlanAllocations) {
      if (e.selling_plan_id == sellingId) {
        product.selected_or_first_available_variant == e;
      }
    }
  }

  console.log("selected?", availableSellingPlanAllocations || null);

  // Update the selling plan option selectors based on the available selling plan allocations
  // for the selected variant
});

// Watch for selling plan option change to update the selected selling plan
sellingPlanContainer
  .querySelectorAll("select")
  .forEach(function (optionSelector) {
    optionSelector.addEventListener("change", function (e) {
      var selectedVariant = findSelectedVariant();
      var availableSellingPlanAllocations =
        selectedVariant.selling_plan_allocations;
      var selectedSellingPlanId;

      console.log("En el segundo", availableSellingPlanAllocations);
      console.log("En el segundo e", e);

      let groupIdSelected = e.target.dataset.group;
      let itemSelected = e.target.value;
      let sellingPlanSelected = getSubscriptionPlanId(
        groupIdSelected,
        itemSelected
      );

      if (sellingPlanSelected) {
        selectedSellingPlanId = sellingPlanSelected;
      }

      selectedSellingPlanId =
        typeof selectedSellingPlanId === "undefined"
          ? ""
          : selectedSellingPlanId;
      document.querySelector('[name="selling_plan"]').value =
        selectedSellingPlanId;
    });
  });

const getSubscriptionPlanId = (selectedSellingGroupId, optionValue) => {
  let sellingPlanGroup = product.selling_plan_groups.find(
    (x) => x.id === selectedSellingGroupId
  );
  let sellingPlanSelected = sellingPlanGroup.selling_plans.find(
    (x) => x.options[0].value === optionValue
  ).id;
  return sellingPlanSelected;
};

var selectCallback = function (variant, selector) {
  console.log(product || null);
  console.log("variante", variant ? variant : "sin variante");
  this.variant = variant;
  console.log("selector", selector ? selector : "sin selector");

  selector.product.selected_variant = variant;

  document.querySelector('[name="id"]').value = variant.id;
};

new Shopify.OptionSelectors("product-select", {
  product: product,
  onVariantSelected: selectCallback,
});

 

 

 

1 SOLUCIÓN ACEPTADA

Javier
Shopify Staff
1696 471 225

Éxito.

Hola @GastonM,

 

Gracias por tu mensaje y por compartir el código conmigo. Por curiosidad, ¿ese código es para una aplicación que estás creando?

 

Solo para darte un poco de contexto, aconsejamos que si tiene cualquier duda en relación con algo que involucra la API de Shopify, debe subir tu pregunta en el subforo Shopify APIs & SDKs. Tu pregunta se queda fuera del alcance del soporte de Shopify, sin embargo, hay desarrolladores que conocen la plataforma y participan activamente en esa comunidad. Es posible que podrás ya encontrar un hilo que trata del mismo asunto de tu duda.

 

Una otra cosa que puedes hacer es juntarte a nuestra comunidad de charla en Discord para desarrolladores.

 

Saludos

Javier | Shopify 
 - ¿Te resultó útil mi respuesta? Dale Me gusta para hacérmelo saber 
 - ¿Resolvimos tu pregunta? Dale a Aceptar como solución
 - Para saber más visita el Centro de ayuda de Shopify o nuestro Blog de Shopify

Ver la solución en mensaje original publicado

1 RESPUESTA 1

Javier
Shopify Staff
1696 471 225

Éxito.

Hola @GastonM,

 

Gracias por tu mensaje y por compartir el código conmigo. Por curiosidad, ¿ese código es para una aplicación que estás creando?

 

Solo para darte un poco de contexto, aconsejamos que si tiene cualquier duda en relación con algo que involucra la API de Shopify, debe subir tu pregunta en el subforo Shopify APIs & SDKs. Tu pregunta se queda fuera del alcance del soporte de Shopify, sin embargo, hay desarrolladores que conocen la plataforma y participan activamente en esa comunidad. Es posible que podrás ya encontrar un hilo que trata del mismo asunto de tu duda.

 

Una otra cosa que puedes hacer es juntarte a nuestra comunidad de charla en Discord para desarrolladores.

 

Saludos

Javier | Shopify 
 - ¿Te resultó útil mi respuesta? Dale Me gusta para hacérmelo saber 
 - ¿Resolvimos tu pregunta? Dale a Aceptar como solución
 - Para saber más visita el Centro de ayuda de Shopify o nuestro Blog de Shopify