Summary of Issue:

I am looking to sort the color attribute options programmatically with input type 'Visual Swatch'. I have made customization in below files to sort the attribute options:

File 1: vendor/magento/module-swatches/view/adminhtml/templates/catalog/product/attribute/Visual.phtml

in the above file, I have added code before last script tag. (after line 109)

    $values = [];
    $color = [];

    foreach($block->getOptionValues() as $value) {
        $value = $value->getData();
        $values[] = is_array($value) ? array_map(function($str) {
            return htmlspecialchars_decode($str, ENT_QUOTES);
        }, $value) : $value;
    foreach($values as $key => $val) {
      $color[ucwords($key)]  = ucwords($val['store0']);
    array_multisort($color, SORT_ASC, $values);

also added the code in below file in getJsonConfig() after line 71


public function getJsonConfig()
        $values = [];
        foreach ($this->getOptionValues() as $value) {
            $values[] = $value->getData();
        //custom code
        foreach($values as $key => $val) {
          $mid[ucwords($key)]  = ucwords($val['store0']);
        array_multisort($mid, SORT_ASC, $values);
        //custom code end
        $data = [
            'attributesData' => $values,
            'uploadActionUrl' => $this->getUrl('swatches/iframe/show'),
            'isSortable' => (int)(!$this->getReadOnly() && !$this->canManageOptionDefaultOnly()),
            'isReadOnly' => (int)$this->getReadOnly()

        return json_encode($data);

after adding the above code, I am able to sort the attribute options. But the visual swatches don't sort with respective options.

Please check the below images:

A) Below image is before adding the swatch option.

enter image description here

B) Below image is after adding the option. Here option is sorted correctly alphabet-wise but the image is not assigning to that option. See below image

enter image description here

  Steps to replicate:  (Before replicating the above issue, please add
  above custom code)
  - Go to Store >> Attribute >> Product 
  - Search for the color attribute 
  - Add swatch option with image.
  - Check that option get sorted
  - But image assigned to last option.

Expected result: The image should assign to newly added option after sorting.

Actual result: The image does not assign against newly added option after sorting.

Is anything wrong happens after sorting the array?

  • any suggestions on this ? or is it possible to do?
    – 1990rk4
    Jun 6, 2019 at 4:41
  • Hi, did you manage to solve it?
    – gabtzi
    May 27, 2022 at 13:02


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.