【发布时间】:2018-04-04 22:21:38
【问题描述】:
我正在 Drupal 8 中设置一个控制器模块来创建一个 XML 提要,其中包含特定词汇表中的字段。我已经能够进行一些初始设置来循环遍历每个术语,但我不确定如何获取术语中的字段值。
我的控制器:
<?php
namespace Drupal\af_services_xml\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Entity\Term;
class FruitController extends ControllerBase {
/**
* Function (Public): Returns content to my route.
*/
public function fruits_xml() {
$response = new Response();
$response->headers->set('Content-Type', 'text/xml');
// Setup general nid query.
$query = \Drupal::entityQuery('taxonomy_term');
$query->condition('vid', 'fruits');
$result = array_values($query->execute());
for ($i = 0; $i < count($result); $i++) {
$result[$i] = self::xmlOutput($result[$i]);
}
// Prepend XML wrapper.
array_unshift($result, '<?xml version="1.0" encoding="utf-8"?><fruitbasket>');
// Append XML closure.
$result[] = '</fruitbasket>';
$response->setContent(implode('', $result));
return $response;
}
private function xmlOutput($tid) {
$tid = '<fruit whereValue="' . $tid . '">
<name>title</name>
<description>description</description>
<numberofseeds>field_seed_count</numberofseeds>
</fruit>';
return $tid;
}
}
您可以看到,我能够获取术语 id 本身。这是我的提要的当前输出(我的词汇表中有六个水果术语)
<fruitbasket>
<fruit whereValue="87">
<name>title</name>
<description>description</description>
<numberofseeds>field_seed_count</numberofseeds>
</fruit>
<fruit whereValue="90">
<name>title</name>
<description>description</description>
<numberofseeds>field_seed_count</numberofseeds>
</fruit>
<fruit whereValue="86">
<name>title</name>
<description>description</description>
<numberofseeds>field_seed_count</numberofseeds>
</fruit>
</fruitbasket>
当然,大部分输出都是硬编码的。我想使用 get 方法(可能是 get() 或 getFields() ?),将每个单独的字段定义为变量,并将该变量放入我的 XML 标记中。但是,我不确定该怎么做。
一些伪代码:
$seedCount = $tid->get(field_seed_count); 然后在$tid = 声明中使用$seedCount,在<numberofseeds> 标签之间。
有什么建议吗?
更新:已解决
这几乎效果很好!我不得不更新循环,因为 foreach 没有使用$i。我还在我的 xmlOutput 函数中加载了术语
$tids = array_values($query->execute());
foreach ($tids as $key=>$value) {
$result[$key] = self::xmlOutput($value);
}
private function xmlOutput($input) {
$term = Term::load($input);
$tid = '<tid>' . $term->id() . '</tid>';
return $tid;
}
【问题讨论】:
标签: xml drupal controller drupal-8