【问题标题】:Displaying tag names rather than IDs using the form helper使用表单助手显示标签名称而不是 ID
【发布时间】:2013-01-12 22:08:32
【问题描述】:

在我的一个表单中,我有一个用于帖子标签的文本输入。目前,Cake 正在将标签 id 返回到该字段中,而不是标签的名称。我想更改它以显示标签的名称。

posts 控制器得到如下结果:

array(
    'Post' => array(
        'id' => '7',
        'title' => 'Testing again',
        'body' => 'wooooooo',
        'created' => '2013-01-09 19:20:53',
        'slug' => 'testing-again'
    ),
    'Tag' => array(
        (int) 0 => array(
            'id' => '4',
            'name' => 'tag1'
        ),
        (int) 1 => array(
            'id' => '3',
            'name' => 'tag2'
        ),
        (int) 2 => array(
            'id' => '5',
            'name' => 'tag3'
        )
    )
)

表格的布局如下:

<?php echo $this->Form->create('Post'); ?>
<?php echo $this->Form->input('Post.title'); ?>
<?php echo $this->Form->input('Post.body'); ?>
<?php echo $this->Form->input('Tag.Tag', array('type' => 'text', 'label' => 'Tags (seperated by space)')); ?>
<?php echo $this->Form->input('Post.slug'); ?>
<?php echo $this->Form->end('Save Changes'); ?>

有没有办法让 CakePHP 输出标签的 name 字段而不是 id?谢谢。

【问题讨论】:

  • 输入的标签不就是Tag.x.name下的tag1tag2tag3吗?
  • 抱歉,我不确定你的意思?
  • 嗯,在返回给控制器的数据中,我看到一组标签(数字索引)列出名称tag1tag2tag3。那些不是你在表单中输入的标签吗?
  • 对不起,我应该在我的 OP 中更具体一些。这是在帖子编辑页面上。假设我提交了带有标签phpmysqloracle 的博客文章,稍后我想编辑该帖子标签,编辑页面显示这些标签的ID 而不是名称。我希望它显示名称,以便我知道标签是什么,如果这有意义的话。 :)
  • 基本上,您在上面看到的输出是来自数据库的find 操作。

标签: php cakephp tags posts has-and-belongs-to-many


【解决方案1】:

好的,根据我从我们的评论讨论中收集到的信息,这就是您要查找的内容。在您的控制器中,只需遍历帖子的所有设置标签。假设您的查找结果设置在 $post 变量中,您可以使用以下代码并将它们全部保存在“普通”非递归数组中:

$tags = array(); // This will hold all the tags
foreach($post['Tag'] as $tag) {
    $tags[] = $tag['name'];
}

// Set the tags as view variable
$this->set(compact('tags'));

然后在您的视图中,您只需 implode 带有空格的数组并将其设置为您的文本字段的值:

echo $this->Form->input('Tag.Tag', array('type' => 'text', 'label' => 'Tags (seperated by space)', 'value' => implode(' ', $tags)));

然后,您的 OP 中的 find 示例将返回值 tag1 tag2 tag3

【讨论】:

  • 我以为有办法告诉Cake 这样做,嗯。这无论如何都有效,谢谢! :)
  • 当您保存它时,这实际上不会编辑它们,因为id 丢失了。你需要一些额外的处理
【解决方案2】:

你在标签模型中设置了 $displayField 吗?

例如。

public $displayField = "name";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多