How to programmatically set the field formatter for a field given certain conditions
Is there a more convenient way of setting a field formatter for a particular field on an entity?


Yes, choose the formatter in the view mode settings (configure in the user interface) rather than using template preprocess.

(I found this old question looking for how to make a field formatter, and ended up copying Drupal\user\Plugin\Field\FieldFormatter and simplifying it by dropping the configuration parts, and then simply selecting that formatter on the view modes and Views tables i wanted to use it on.)

For ensuring this formatter doesn't show up in places it shouldn't, the key part is "isApplicable"; here's what mine looked like for a custom entity 'give_donation' and a field named 'recurring':

  /**
   * {@inheritdoc}
   */
  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    return $field_definition-&gt;getTargetEntityTypeId() === 'give_donation' &amp;&amp; $field_definition-&gt;getName() === 'recurring';
  }