ArrayBackend.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Eav\Model\Entity\Attribute\Backend;
  7. /**
  8. * Backend model for attribute with multiple values
  9. *
  10. * @api
  11. * @since 100.0.2
  12. */
  13. class ArrayBackend extends \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend
  14. {
  15. /**
  16. * Prepare data for save
  17. *
  18. * @param \Magento\Framework\DataObject $object
  19. * @return \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend
  20. */
  21. public function beforeSave($object)
  22. {
  23. $attributeCode = $this->getAttribute()->getAttributeCode();
  24. $data = $object->getData($attributeCode);
  25. if (is_array($data)) {
  26. $data = array_filter($data, function ($value) {
  27. return $value === '0' || !empty($value);
  28. });
  29. $object->setData($attributeCode, implode(',', $data));
  30. }
  31. return parent::beforeSave($object);
  32. }
  33. /**
  34. * Implode data for validation
  35. *
  36. * @param \Magento\Catalog\Model\Product $object
  37. * @return bool
  38. */
  39. public function validate($object)
  40. {
  41. $attributeCode = $this->getAttribute()->getAttributeCode();
  42. $data = $object->getData($attributeCode);
  43. if (is_array($data)) {
  44. $object->setData($attributeCode, implode(',', array_filter($data)));
  45. } elseif (empty($data)) {
  46. $object->setData($attributeCode, null);
  47. }
  48. return parent::validate($object);
  49. }
  50. }