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.
* 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(
public function getInfo() {
$class = get_class($this);
return [
+ '#optional' => FALSE,
'#process' => [
[$class, 'processGroup'],
[$class, 'processContainer'],
],
'#pre_render' => [
[$class, 'preRenderGroup'],
+ [$class, 'preRenderContainer'],
],
'#theme_wrappers' => ['container'],
];
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;
+ }
+
}