Making custom product values available in the cart

Question by @dimmy in Slack:

When I have custom fields that I like to show in my twig template (for instand in the cart) and those fields are in my database, how do I get them in the template?

If you have a custom product, it probably has some custom data besides the sku, name, price, etc. That information is not automatically copied into the order items or made available in the various templates for the cart/checkout.

To accomplish that, you’ll need to override the comProduct->toArray() method to add your own information. For example like this:

public function toArray($keyPrefix = '', $rawValues = false, $excludeLazy = false, $includeRelated = false)
    // First we let comProduct.toArray get all the base values.
    $array = parent::toArray($keyPrefix, $rawValues, $excludeLazy, $includeRelated);
    if (!$rawValues) {
        $array[$keyPrefix . 'color'] = $this->getColor();
    return $array;

After that, you can use {{ item.product.color }} in your cart/checkout templates as well as most other places where the product record is made available.