Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / web / core / lib / Drupal / Core / Render / Element / Container.php
index 212000d7be5629bcc6e3c0e7cf8ee182897a75a9..357e6a5484968625232a37ab10e5c5d9dbf44cab 100644 (file)
@@ -4,6 +4,7 @@ namespace Drupal\Core\Render\Element;
 
 use Drupal\Component\Utility\Html as HtmlUtility;
 use Drupal\Core\Form\FormStateInterface;
+use Drupal\Core\Render\Element;
 
 /**
  * Provides a render element that wraps child elements in a container.
@@ -11,6 +12,10 @@ use Drupal\Core\Form\FormStateInterface;
  * Surrounds child elements with a <div> and adds attributes such as classes or
  * an HTML ID.
  *
+ * Properties:
+ * - #optional: Indicates whether the container should render when it has no
+ *   visible children. Defaults to FALSE.
+ *
  * Usage example:
  * @code
  * $form['needs_accommodation'] = array(
@@ -46,12 +51,14 @@ class Container extends RenderElement {
   public function getInfo() {
     $class = get_class($this);
     return [
+      '#optional' => FALSE,
       '#process' => [
         [$class, 'processGroup'],
         [$class, 'processContainer'],
       ],
       '#pre_render' => [
         [$class, 'preRenderGroup'],
+        [$class, 'preRenderContainer'],
       ],
       '#theme_wrappers' => ['container'],
     ];
@@ -79,4 +86,22 @@ class Container extends RenderElement {
     return $element;
   }
 
+  /**
+   * Prevents optional containers from rendering if they have no children.
+   *
+   * @param array $element
+   *   An associative array containing the properties and children of the
+   *   container.
+   *
+   * @return array
+   *   The modified element.
+   */
+  public static function preRenderContainer($element) {
+    // Do not render optional container elements if there are no children.
+    if (empty($element['#printed']) && !empty($element['#optional']) && !Element::getVisibleChildren($element)) {
+      $element['#printed'] = TRUE;
+    }
+    return $element;
+  }
+
 }