I want to SET gift message programmatically in current order(one message for whole order) during Checkout. Currently, I trying using sales_order_save_after event to edit order but didn't get succeed.
any another approach to do the same?
Finally, I got the easiest way.
public function __construct(
\Magento\Checkout\Model\Session $session,
\Magento\Quote\Model\QuoteRepository $quoteRepository,
\Magento\GiftMessage\Model\MessageFactory $messageFactory
) {
$this->session = $session;
$this->quoteRepository = $quoteRepository;
$this->messageFactory = $messageFactory;
}
public function test(){
$quoteId = $this->session->getQuote()->getId();
$giftMessage = $this->messageFactory->create();
$giftMessage->setMessage('your text');
$giftObj = $giftMessage->save();
$quote->setGiftMessageId($giftObj->getId());
$quote->save();
}
if you want to add information after placing order then you may use "checkout_onepage_controller_success_action" this event to add your custom data
You can get Gift message for order item using this code.
public function __construct(
\Magento\GiftMessage\Api\OrderItemRepositoryInterface $orderItemGiftRepo
) {
$this->orderItemGiftRepo = $orderItemGiftRepo;
}
public function getGiftMessage($orderId, $orderItemId)
{
$giftMessage = $this->orderItemGiftRepo->get($orderId, $orderItemId);
$giftMessage->getMessage(); // This will give you message
}
public function setGiftMessage($orderId)
{
$giftMessage = $this->orderItemGiftRepo->get($orderId);
$giftMessage->setMessage('custommessage');
}
Hope this will help you !!