Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sort order and default attribute option #8

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,10 +214,14 @@ We can also specify product options for select type attributes as so:
- Yellow
- Blue
- Purple
- Pink
- Pink|default
- Orange
```

Use the marker `|default` to specify the default option.

Note that the order of the options in the config file determines the sort order of the options.

Please note, certain attribute configurations follow certain rules so do ensure you're familiar with how Magento product attributes work in order to make best use of this component. An attribute's configuration elements are simply fields in the `catalog_eav_attribute` table with a few exceptions.

### Attribute Sets
Expand Down
2 changes: 1 addition & 1 deletion samples/components/attributes.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
- Yellow
- Blue
- Purple
- Pink
- Pink|default
- Orange
- Brown
- rrp:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
<?php
class Cti_Configurator_Helper_Components_Attributes extends Cti_Configurator_Helper_Components_Abstract {

const DEFAULT_MARKER = 'default';
const NUMBER_MARKER = '###';

public function __construct() {
$this->_componentName = 'attributes';
$this->_filePath1 = Mage::getBaseDir().DS.'app'.DS.'etc'.DS.'components'.DS.'attributes.yaml';
Expand Down Expand Up @@ -73,10 +76,12 @@ private function _createOrUpdateAttribute($code,$data) {
};
unset($key);
unset($value);

if (!$attribute->getEntityTypeId()) {
$attribute->setEntityTypeId(Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId());
$attribute->setIsUserDefined(1);
}

try {
if ($canSave) {
$attribute->save();
Expand All @@ -90,7 +95,6 @@ private function _createOrUpdateAttribute($code,$data) {
}
}


/**
* Gets a particular attribute otherwise
* returns false if it doesn't exist
Expand Down Expand Up @@ -125,64 +129,69 @@ private function _getAttribute($code) {
* @param $attribute
* @param $options
*/
private function _maintainAttributeOptions($attribute,$options) {

$currentOptions = $attribute->getSource()->getAllOptions();
private function _maintainAttributeOptions($attribute, $options)
{
$currentOptions = array_filter($attribute->getSource()->getAllOptions(), function ($option) { return $option["label"] !== ""; });

// Make label => id map of currentOptions
$currentOptions = array_combine(
array_map(function ($keys) { return $keys['label']; }, $currentOptions),
array_map(function ($keys) { return $keys['value']; }, $currentOptions)
);

$currentOptionFormat = array();
foreach ($currentOptions as $option) {
if ($option['label'] != '') {
$currentOptionFormat[] = $option['label'];
// Look for default marker
$default = null;
$options = array_map(function ($option) use (&$default, $currentOptions) {
if ($this->isDefault($option)) {
$default = $this->getOptionId($option, $currentOptions);
}
return $this->trimDefault($option);
}, $options);

// Ordered by position in YAML
$optionsPosition = array_flip($options);

$toCreate = array_values(array_diff($options, array_keys($currentOptions)));
$toDelete = array_values(array_diff(array_keys($currentOptions), $options));

// Placeholders
$value = [];
$order = [];
$delete = [];

// All properties (value, order, delete) are set no matter the operation
$allOptions = array_unique(array_merge($options, array_keys($currentOptions)));
foreach ($allOptions as $option) {
$option_id = null;
if (in_array($option, $toCreate)) {
$option_id = is_numeric($option) ? self::NUMBER_MARKER . $option : $option;
} else {
$option_id = $currentOptions[$option];
}
}

$attributeId = $attribute->getId();
$optionsToAdd = array_diff($options,$currentOptionFormat);
$optionsToRemove = array_diff($currentOptionFormat,$options);
$eav_entity_setup = new Mage_Eav_Model_Entity_Setup('core_setup');

// Create new attributes
foreach ($optionsToAdd as $option) {

unset($new_option);
$value[$option_id] = [ 0 => $option ];
$order[$option_id] = "" . isset($optionsPosition[$option]) ? $optionsPosition[$option] : "0";
$delete[$option_id] = "";

// Check if the option already exists
if ($attribute->getSource()->getOptionId($option)) {
$this->log($this->__("Exsting attribute option %s for %s",$option,$attribute->getAttributeCode()));
if (in_array($option, $toDelete, true)) {
$delete[$option_id] = "1"; // value of "1" means delete
}
$new_option['attribute_id'] = $attributeId;
$new_option['value']['_custom_'.$option][0] = $option;
$eav_entity_setup->addAttributeOption($new_option);

/*
$attribute->setData(
'option',
array(
'value'=>array(
'option'=>array(
$option
)
)
)
);
$attribute->save();
*/

$this->log($this->__("Created attribute option %s for %s",$option,$attribute->getAttributeCode()));
}

// Remove old attributes
foreach ($optionsToRemove as $option) {
$optionId = $attribute->getSource()->getOptionId($option);
$toDelete['delete'][$optionId] = true;
$toDelete['value'][$optionId] = true;
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($toDelete);
$this->log($this->__("Deleted attribute option %s for %s",$option,$attribute->getAttributeCode()));
}
// Data-structure derrived from saveAction in Mage_Adminhtml_Catalog_Product_AttributeController
$data = [
"option" => [
"value" => $value,
"order" => $order,
"delete" => $delete
],
"default" => [ (in_array($default, $toCreate) && is_numeric($default) ? self::NUMBER_MARKER . $default : $default) ]
];

$attribute->addData($data);
$attribute->save();
}


/**
* @return array
*/
Expand Down Expand Up @@ -216,4 +225,18 @@ private function _getAttributeDefaultSettings() {
'search_weight' => 1 // EE only
);
}
}

private function isDefault($option)
{
return strpos($option, "|" . self::DEFAULT_MARKER) !== false;
}
private function trimDefault($option)
{
return $this->isDefault($option) ? substr($option, 0, strpos($option, "|" . self::DEFAULT_MARKER)) : $option;
}
private function getOptionId($option, $currentOptions = [])
{
$option = $this->trimDefault($option);
return isset($currentOptions[$option]) ? $currentOptions[$option] : $option;
}
}