:::: MENU ::::

Magento Tutorial | Magento Blog | Learn Magento 2

Cookies Consent Popup

In Magento 2, associated products are widely used in configurable products and bundled products. However, some store owners face an issue where associated products do not appear when custom options are added. This can be confusing and may look like a bug in Magento.

Understanding the Issue

  • When you add a required custom option to a product, Magento may fail to display associated products correctly.
  • This is due to a limitation in earlier Magento versions where required custom options conflicted with product association logic.
  • As a result, customers could not see or select associated products if a required custom option was present.

Magento Bug and Fix

This was a known bug in Magento 2 before version 2.2.4. The Magento team fixed the issue in Magento 2.2.4, so upgrading your store is the most reliable solution.

Workarounds for Older Versions

  1. Use Non‑Required Custom Options: If possible, set your custom option to non‑required so associated products can display.
  2. Upgrade Magento: Update to Magento 2.2.4 or later where the bug is fixed.
  3. Custom Module Override: Developers can override product option validation logic to allow associated products with required options.

Practical Example

Suppose you have a configurable product “T‑Shirt” with associated products for different sizes. If you add a required custom option like “Gift Wrap” or “Custom Text,” the associated size options may not appear. By making the custom option non‑required or upgrading Magento, the associated products will show correctly.

Best Practices

  • Always test associated products after adding custom options.
  • Keep Magento updated to avoid known bugs.
  • Use staging environments to test changes before applying them to live.
  • Document any custom overrides for future maintenance.

SEO & UX Benefits

  • Ensures customers can select product variations without confusion.
  • Improves conversion rates by reducing checkout errors.
  • Maintains a professional and reliable shopping experience.

Troubleshooting Checklist

  • Check if your Magento version is older than 2.2.4.
  • Verify if the custom option is marked as required.
  • Test with a non‑required option to confirm the issue.
  • Review logs in var/log for related errors.

Conclusion

The “Associated Product with Custom Option Not Showing” issue in Magento 2 is a known bug in earlier versions. The simplest fix is to upgrade to Magento 2.2.4 or later. For older versions, using non‑required custom options or applying a developer override can help. By resolving this issue, you ensure customers can view and select associated products smoothly, improving both user experience and sales.

Magento 2 store owners often face issues when trying to upload product images, category images, or placeholder images directly from the Admin Panel. This can be frustrating, especially when you need to quickly update your catalog visuals. In this guide, we’ll cover the common causes and step‑by‑step solutions to fix image upload problems in Magento 2.

Common Causes

  • File permissions: The pub/media or var directories don’t have proper write access.
  • PHP settings: Low upload_max_filesize or post_max_size values in php.ini.
  • Cache issues: Old cache entries prevent new images from being recognized.
  • Browser problems: Outdated cache or JavaScript conflicts in the admin panel.
  • Theme overrides: Custom themes may override image upload logic.

Step-by-Step Solutions

  1. Check Permissions: Ensure pub/media and var directories are writable.
    
        chmod -R 775 pub/media
        chmod -R 775 var
        
  2. Update PHP Settings: Increase limits in php.ini.
    
        upload_max_filesize = 20M
        post_max_size = 20M
        
  3. Clear Cache: Run:
    
        php bin/magento cache:flush
        
  4. Deploy Static Content: If using production mode:
    
        php bin/magento setup:static-content:deploy -f
        
  5. Check Browser: Clear browser cache or try another browser to rule out frontend conflicts.

Alternative Fix (Direct Upload)

If the admin panel upload fails, you can manually place your image in:


pub/media/catalog/product/yourimage.jpg

Magento will automatically use this file when you assign it to a product.

Best Practices

  • Use optimized images (compressed, proper dimensions) to improve performance.
  • Keep a consistent style across product and category images.
  • Always clear cache after uploading new images.
  • Test uploads in staging before applying changes to live.

SEO & UX Benefits

  • Improves user experience by ensuring products always display correctly.
  • Maintains a professional look for your store.
  • Helps search engines index products with proper visuals.

Troubleshooting

  • If the image doesn’t appear, check pub/media/catalog/product for the file.
  • Ensure your theme’s view.xml doesn’t override image dimensions.
  • Run php bin/magento cache:clean after changes.
  • Check server error logs for PHP or permission errors.

Conclusion

The “Unable to Upload Images from Magento 2 Admin Panel” issue is usually caused by permissions, PHP limits, or cache problems. By following the steps above, you can quickly fix the issue and ensure your store always displays product images correctly. This not only improves the customer experience but also boosts SEO and conversions.

Magento 2 uses Knockout.js heavily on checkout and other dynamic pages. This can cause timing issues when you try to run jQuery code: your script executes before the element is fully bound or rendered, resulting in errors or missing functionality.

To solve this, you can use a utility function that waits until the element is available in the DOM before executing your code.

Problem Scenario

  • Custom jQuery runs too early on checkout or cart pages.
  • Knockout.js binds elements asynchronously, so selectors return empty.
  • Scripts fail silently or cause console errors.

Solution: Wait for Element


function waitForElement(query, callback) {
    var checkExist = setInterval(function() {
        if (document.querySelector(query)) {
            clearInterval(checkExist);
            callback();
        }
    }, 100);
}

// Usage Example
waitForElement(".class", function() {
    alert("Element is loaded.. do stuff");
});

Explanation

  • query: CSS selector of the element you want to wait for.
  • setInterval: Checks every 100ms if the element exists.
  • clearInterval: Stops checking once the element is found.
  • callback(): Executes your custom code after the element is loaded.

Best Practices

  • Use specific selectors (e.g., #checkout-step-shipping) to avoid unnecessary checks.
  • Keep the callback lightweight to avoid performance issues.
  • Always test on multiple browsers and devices to confirm behavior.

Alternative: Using MutationObserver


function observeElement(query, callback) {
    var target = document.querySelector("body");
    var observer = new MutationObserver(function(mutations) {
        if (document.querySelector(query)) {
            callback();
            observer.disconnect();
        }
    });
    observer.observe(target, { childList: true, subtree: true });
}

// Usage Example
observeElement(".class", function() {
    console.log("Element loaded via MutationObserver");
});

Real Magento Example


// Wait for shipping method buttons on checkout
waitForElement("#shipping-method-buttons-container", function() {
    console.log("Shipping method buttons are ready");
    // Add your custom logic here
});

Troubleshooting

  • If your code never runs, double‑check the selector with browser DevTools.
  • Increase the interval time if the element takes longer to load.
  • Use MutationObserver for complex cases where elements are dynamically replaced.

Conclusion

Magento 2’s dynamic frontend can cause timing issues with jQuery. By using waitForElement or MutationObserver, you can ensure your script runs only after the element is available. This makes your customizations more reliable and prevents errors on checkout or other Knockout‑driven pages.

Logging is a critical part of Magento 2 development. It helps developers track issues, debug functionality, and monitor custom processes. While Magento provides system and exception logs by default, sometimes you need your own custom log file for module‑specific or business‑specific events.

Why Custom Logs?

  • Keep your module’s logs separate from Magento’s core logs
  • Quickly identify issues related to your custom functionality
  • Track specific events (e.g., product sync, API calls, payment gateway responses)
  • Provide an audit trail for business processes

Magento Version Specific Code

For Magento 2.4.2 and Before:


$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/custom.log');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);

$logger->info('Custom message');
$logger->info(print_r($object->getData(), true));

For Magento 2.4.2 and After:


$writer = new \Laminas\Log\Writer\Stream(BP . '/var/log/custom.log');
$logger = new \Laminas\Log\Logger();
$logger->addWriter($writer);

$logger->info('text message');
$logger->info(print_r($object->getData(), true));

For Magento 2.4.3:


$writer = new \Zend_Log_Writer_Stream(BP . '/var/log/custom.log');
$logger = new \Zend_Log();
$logger->addWriter($writer);

$logger->info('text message');
$logger->info(print_r($object->getData(), true));

Best Practices

  • Use meaningful log filenames (e.g., custom.log, sync.log, payment.log)
  • Apply log levels properly: info, debug, error
  • Rotate or clear logs regularly to avoid large files
  • Never log sensitive data like passwords or tokens

Step-by-Step Tutorial

  1. Create Logger: Instantiate the correct logger class based on your Magento version.
  2. Define Log File: Point to /var/log/custom.log or another meaningful filename.
  3. Write Messages: Use info(), debug(), or error() depending on the context.
  4. Test: Trigger your code and check the log file in var/log to confirm entries.

When to Use Custom Logs

  • Tracking API integrations (ERP, payment gateways, etc.)
  • Debugging custom module functionality
  • Monitoring cron jobs or scheduled tasks
  • Capturing business‑specific events for auditing

Troubleshooting

  • If your log file doesn’t appear, check file permissions for the var/log directory.
  • Ensure your code is actually executed (e.g., place a test $logger->info('Hello World');).
  • Clear cache after adding new code to make sure Magento picks up changes.

Conclusion

Depending on your Magento version, the logging classes differ slightly. By using the correct snippet above, you can generate custom logs safely and effectively. This ensures better visibility into your module’s behavior and makes debugging much easier. Custom logs are a simple but powerful tool to keep your Magento store stable and transparent.