How to create a new Selection Rule(Condition) for Panels

At the moment of writing this article, the latest Panels release is on 8.x-4.2.

If you were using the Panels module in Drupal 7, you might now that while creating a new Variant, you could add "Selection Rules" rules comparing the field values of the context's Entity.

Currently, there is no possibility to do it in Drupal 8. There is some ongoing work in CTools module but it's still in beta.

As for example, I'm going to create a Condition which is going to check for a boolean value of a Node's field.


So, to create your own rule here is the minimal implementation you need. 


Create a file in "mymodule/src/Plugin/Condition/ExtraArticleIsMain.php" containing:

namespace Drupal\mymodule\Plugin\Condition;

use Drupal\Core\Condition\ConditionPluginBase;
use Drupal\node\Entity\Node;

/**
 * Provides a 'Extra Article is Main' condition.
 *
 * @Condition(
 *   id = "extra_article_is_main",
 *   label = @Translation("Extra Article Is Main"),
 *   category = @Translation("Node"),
 *   context = {
 *     "node" = @ContextDefinition("entity:node",
 *     label = @Translation("Node")
 *     )
 *   }
 * )
 *
 */
class ExtraArticleIsMain extends ConditionPluginBase {

  /**
   * {@inheritdoc}
   */
  public function evaluate() {
    $pass = FALSE;

    /** @var Node $node */
    $node = $this->getContextValue('node');
    if (!$node instanceof Node) {
      return $pass;
    }

    if (!$node->hasField('field_main_article')) {
      return $pass;
    }

    if ($node->get('field_main_article')->getString()) {
      $pass = TRUE;
    }

    return $pass;
  }

  /**
   * {@inheritdoc}
   */
  public function summary() {
    return $this->t('The value of field_main_article is TRUE.');
  }

}

Rebuild the cache and you should see your rule available.

********************************** ************************* ************************ **************** ****************** *********** ************** ************* ************ *************