dongxiangchan0743 2013-01-09 18:43
浏览 10
已采纳

使用表单帮助程序显示标记名称而不是ID

In one of my forms I have a text input for a posts tags. At the moment, Cake is returning the tag id into this field rather than the name of the tag. I want to change it to show the name of the tag.

The posts controller is getting a result like this:

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'
        )
    )
)

and the form is laid out like this:

<?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'); ?>

Is there a way I can tell CakePHP to output the name field of the tags instead of id? Thanks.

  • 写回答

2条回答 默认 最新

  • dtziv24262 2013-01-09 19:31
    关注

    OK, so from what I've gathered from our comment discussion, this would be what you're looking for. In your controller, just loop over all the set tags for the post. Assuming your find result is set in the $post variable, you can use the below code and save them all in a "plain" non-recursive array:

    $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'));
    

    Then in your view you can just implode the array with a space and set it as value for your text field:

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

    The find example in your OP would then return a value of tag1 tag2 tag3.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?