I have a code below (simplified) to add a comment to current order in customer’s account -> orders -> view (order detail).
The code is working fine. The only thing is, that after processing the comment sent by form and calling getVisibleStatusHistory(), all comments are sorted by date/time (descending) correctly except the comment recently added by customer. That comment is added as the last one in the result – which doesn’t correspond to the descending sorting of the getVisibleStatusHistory() result. After reloading the page it’s correctly sorted.
All code is in customized view.phtml
I have a form sending comment:
<form action="" method="post">
<textarea name="ordercomment" maxlength="1000"></textarea>
<input type="submit" value="Send" />
</form>
it is processed by the view.phtml as well:
$ordcomment = $_POST['ordercomment'];
$_order->addStatusHistoryComment($ordcomment)->setIsVisibleOnFront(1);
$_order->save();
and after that script to print all visible comments:
<?php $_history = $this->getOrder()->getVisibleStatusHistory() ?>
<?php if (count($_history)): ?>
<div class="order-additional order-comments">
<h2 class="sub-title"><?php echo $this->__('About Your Order') ?></h2>
<dl class="order-about">
<?php foreach ($_history as $_historyItem): ?>
<dt><?php echo $this->formatDate($_historyItem->getCreatedAtStoreDate(), 'medium', true) ?></dt>
<dd><?php echo $this->escapeHtml($_historyItem->getComment()) ?></dd>
<?php endforeach; ?>
</dl>
</div>
<?php endif; ?>
Does anyone know what is the reason, why last added comment is not sorted properly among the others?
The reason of this strange sorting is that when you add a new history item to the order’s status history collection, the order loads the existing collection (sorted) and adds the new item to its end.
To output the collection correctly, you can reload the order object and with that the history collection will be fetched in a proper order: