Assigning Attributes Directly to Orders

How to set an attribute to an order?

In order to set an attribute to an order, the following steps are required.

      1. The first step is to obtain the order object based on the order ID. This is done using Magento's OrderRepository:
1
2
3
use Magento\Sales\Model\OrderRepository;

$order = $objectManager->create(OrderRepository::class)->get($orderId);

Here, $orderId is the ID of the order for which you want to set the custom attribute.


      2.  Once you have the order object, you need to get the related entity using Amasty's EntityResolver. There are two ways to resolve the entity:
  1. By Order Object:

    1
    2
    3
    4
    use Amasty\Orderattr\Model\Entity\EntityResolver;
    
    $entityResolver = $objectManager->create(EntityResolver::class);
    $entity = $entityResolver->getEntityByOrder($order);
    
  2. By Order ID:

    $entity = $entityResolver->getEntityByOrderId($orderId);

Choose the method that best fits your scenario.


      3. With the entity in hand, you can now set the custom attribute using the setCustomAttribute method. This method updates the attribute with the specified value using the following code:
1
2
3
4
$attributeCode = 'your_custom_attribute_code'; // Replace with your actual attribute code
$attributeValue = 'your_desired_value'; // Replace with the value you want to set

$entity->setCustomAttribute($attributeCode, $attributeValue);