Change media when selecting a variant

Hello, I need help with the following code and I would like that when a color and or size is selected on the custom product page, the corresponding product images are displayed, which are stored in the respective variant.

The mainMedia of a product is selected correctly when the variation is selected, only the other media remain the same.

My Code snipped:

async function updateProductPageWithOptions() {
try {
console.log(‘Ausgewählte Optionen:’, selectOptions); // Struktur von selectOptions überprüfen

    const color = selectOptions['Farbe'];
    if (!color) {
        console.error("Keine Farboption ausgewählt.");
        // Optional: Medien-Elemente zurücksetzen oder eine Nachricht anzeigen
        return;
    }

    // Varianten basierend auf den Optionen abrufen
    const variants = await getProductVariants(thisProduct._id, {
        choices: selectOptions,
    });

    console.log("Gefundene Varianten:", variants);

    // Sicherstellen, dass mindestens eine Variante zurückgegeben wird
    if (!variants || variants.length === 0) {
        console.error("Keine Varianten für die ausgewählten Optionen gefunden.");
        return;
    }

    // Die erste gefundene Variante behandeln
    const variant = variants[0];

    // Überprüfen, ob die ausgewählte Variante Medien-Items hat, und diese aktualisieren
    if (variant && variant.mediaItems && variant.mediaItems.length > 0) {
        // Medien-Items filtern und im Repeater-Format abbilden
        const mediaData = variant.mediaItems.map((item, index) => ({ ...item, _id: index.toString() }));
        $w("#mediaRepeater").data = mediaData;
    } else {
        console.error("Keine Medien-Items für die ausgewählte Variante gefunden.");
        // Optional: Medien-Elemente zurücksetzen oder eine Nachricht anzeigen
    }

    // Hauptbild mit dem Haupt-Medien-Item der ausgewählten Farbvariante aktualisieren
    const colorOption = thisProduct.productOptions['Farbe'];
    const selectedChoice = colorOption.choices.find((choice) => choice.description === color);

    if (selectedChoice && selectedChoice.mainMedia) {
        $w("#mainMedia").src = selectedChoice.mainMedia;
    } else {
        console.error("Kein Haupt-Medien-Item für die ausgewählte Farbwahl gefunden.");
        // Optional: Standardbild anzeigen oder Medien-Elemente ausblenden
    }

    // Fortfahren mit der Aktualisierung der restlichen Produktdetails basierend auf der ausgewählten Variante
    if (variant) {
        if (variant.stock < 1) {
            console.error("Ausgewählte Variante ist nicht auf Lager.");
            $w("#inStock").text = "Diese Variante ist ausverkauft.";
            return;
        }

        const priceDifferencePercent = ((variant.price - variant.discountedPrice) / variant.price) * 100;
        const pricePerUnitData = thisProduct.pricePerUnitData || null;

        $w("#originalPrice").html = `<span style="text-decoration: line-through; color: red; font-size: 25px; font-family: 'Roboto', sans-serif; font-weight: normal;">${variant.formattedPrice}</span>`;
        $w("#prozent").html = `<span style="color: red; font-size: 20px; font-family: 'Roboto', sans-serif; font-weight: bold;">${priceDifferencePercent.toFixed(2)}%</span>`;
        $w("#price").text = variant.formattedDiscountedPrice.toString();
        $w("#weight").text = variant.weight.toString();
        $w("#sku").text = variant.sku.toString();

        if (pricePerUnitData) {
            const totalQuantity = pricePerUnitData.totalQuantity || 0;
            const totalMeasurementUnit = pricePerUnitData.totalMeasurementUnit || "";
            const baseQuantity = pricePerUnitData.baseQuantity || 0;
            const baseMeasurementUnit = pricePerUnitData.baseMeasurementUnit || "";
            const formattedPricePerUnit = variant.formattedPricePerUnit || "";

            $w("#perUnit").text = `Pro ${totalQuantity.toString()} ${totalMeasurementUnit} Inkl. MwSt.`;
            $w("#pricePerUnit").text = `Preis pro ${baseQuantity.toString()} ${baseMeasurementUnit}: ${formattedPricePerUnit} Inkl. MwSt.`;
            $w("#perUnit").show();
            $w("#pricePerUnit").show();
        } else {
            $w("#perUnit").hide();
            $w("#pricePerUnit").hide();
        }
    } else {
        console.error("Variante ist undefiniert oder nicht gefunden.");
        // Optional: Produktdetails zurücksetzen oder eine Fehlermeldung anzeigen
    }
} catch (error) {
    console.error("Fehler beim Aktualisieren der Produktseite:", error.message);
}

}
I have attached three more pictures to make it easier to understand:

This is what it looks like when you first load the product page if nothing is selected yet

Here you can see that when the color “Burgundy” is selected, the main media image changes but the image selection does not.

The images are correctly assigned to the variant.

screen 3

Does anyone have any ideas?

1 Like

I was able to solve the problem myself.
I used the following api to fix the problem:

1 Like