View source
<?php
namespace Drupal\faq;
use Drupal\node\NodeInterface;
use Drupal\Core\Link;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Url;
class FaqViewer {
public static function viewQuestion(&$data, NodeInterface $node, $path = NULL, $anchor = NULL) {
$faq_settings = \Drupal::config('faq.settings');
$disable_node_links = $faq_settings
->get('disable_node_links');
$question = '';
if ($disable_node_links) {
if (empty($path) && empty($anchor)) {
$question = $node
->getTitle();
}
elseif (empty($path)) {
$question = '<a id="' . $anchor . '"></a>' . $node
->getTitle();
}
else {
$options = array();
if ($anchor) {
$options['attributes'] = array(
'id' => $anchor,
);
}
$question = Link::fromTextAndUrl($node
->getTitle(), $path, $options)
->toString();
}
}
else {
$node_id = $node
->id();
if (empty($anchor)) {
$question = Link::fromTextAndUrl($node
->getTitle(), "node/{$node_id})")
->toString();
}
else {
$url = $node
->toUrl()
->setOptions(array(
"attributes" => array(
"id" => "{$anchor}",
),
));
$question = Link::fromTextAndUrl($node
->getTitle(), $url)
->toString();
}
}
$question = '<span datatype="" property="dc:title">' . $question . '</span>';
$detailed_question = $node
->get('field_detailed_question')->value;
if ($faq_settings
->get('display') != 'hide_answer' && !empty($detailed_question) && $faq_settings
->get('question_length') == 'both') {
$question .= '<div class="faq-detailed-question">' . $detailed_question . '</div>';
}
$data['question'] = new FormattableMarkup($question, []);
}
public static function viewAnswer(&$data, NodeInterface $node, $teaser) {
$faq_settings = \Drupal::config('faq.settings');
$view_mode = $teaser ? 'teaser' : 'full';
$node_build = \Drupal::entityTypeManager()
->getViewBuilder('node')
->view($node, $view_mode);
hide($node_build['title']);
if (!$faq_settings
->get('question_long_form')) {
hide($node_build['field_detailed_question']);
}
$content = \Drupal::service('renderer')
->render($node_build);
$content .= FaqViewer::initBackToTop();
$data['body'] = new FormattableMarkup($content, []);
}
public static function initBackToTop() {
$faq_settings = \Drupal::config('faq.settings');
$back_to_top = '';
$back_to_top_text = trim($faq_settings
->get('back_to_top'));
if (!empty($back_to_top_text)) {
$options = array(
'attributes' => array(
'title' => t('Go back to the top of the page.'),
),
'html' => TRUE,
'fragment' => 'top',
);
$back_to_top = Link::fromTextAndUrl($back_to_top_text, Url::fromUserInput('#', $options))
->toString();
}
return $back_to_top;
}
}