【问题标题】:Display username instead of user_id in CakePHP在 CakePHP 中显示用户名而不是 user_id
【发布时间】:2018-04-16 11:04:31
【问题描述】:

嘿,我是 cakePHP 新手,我正在学习书签教程,但我使用的是产品表而不是书签表, 这里我想要的是在添加新产品时,我想在输入字段 user_id 中显示 username 而不是 user_id

 <?= $this->Form->create($product) ?>
<fieldset>
    <legend><?= __('Add Product') ?></legend>
    <?php
        echo $this->Form->input('user_id', ['options' => $users]);
        echo $this->Form->input('title');
        echo $this->Form->input('description');
    ?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>

UsersTable 有

id, username, email, password

我关注了$username = $this-Users-&gt;find('list') 但我真的不明白如何编写这个查询。 我需要运行什么查询?,

【问题讨论】:

  • 确保您使用list 方法获得$users。另外,确保用户表的displayFieldusername
  • 谢谢@yBrodsky,当然表的diplayField是用户名,我遵循命名约定,现在帮我弄清楚,我需要做什么?
  • 向我们展示您的查询以获得$users
  • 先生,我还没有写任何查询,我只是烘焙了表格。
  • 签入您的控制器。 $users 来自某个地方。看看@FrankSunnyman 的回答

标签: cakephp cakephp-3.0 cakephp-3.x


【解决方案1】:

你也可以这样做

UsersTable.php

 public function initialize(array $config)
    {       
         $this->displayField('username'); 
    }

然后是代码

echo $this->Form->input('user_id', ['options' => $users]);  

现在将拉出用户表中的所有用户

【讨论】:

  • 很好,这个想法来自我的朋友@greg smith,他去年帮助了我
【解决方案2】:

选择输入采用键 => 值格式的数组。因此,要以该格式获取您的 $users 数组,您可以在控制器中执行以下操作:

$query = $this->Users->find('list', [
    'keyField' => 'id',
    'valueField' => 'username'
]);
$users = $query->toArray();

这会给你这个数组:

[
    1 => 'Javed',
    2 => 'Test user'
]

【讨论】:

    【解决方案3】:

    首先这取决于你的 cakephp 版本, 这是cakephp 2.X 版本

    的解决方案

    要在您的情况下显示用户名而不是 id,您必须分配用户数据列表

    查询如下:

    //In your controller action code
    $users = $this->Users->find('list', array(
            'fields' => array('id', 'username')
            'recursive' => 0
    ));
    $this->set(compact('users'));
    

    这将在 html 中获得输出

    //In your html view side jsut have to field name not required to write options parameter cakephp auto detect that and filled up the data
    
    <?= $this->Form->create($product) ?>
    <fieldset>
        <legend><?= __('Add Product') ?></legend>
        <?php
            echo $this->Form->input('user_id', ['empty' => __('Select username')]);
            echo $this->Form->input('title');
            echo $this->Form->input('description');
        ?>
    </fieldset>
    <?= $this->Form->button(__('Submit')) ?>
    <?= $this->Form->end() ?>
    

    如果您使用的是其他版本,请添加评论,您的版本也将帮助您解决您的版本

    希望对你有帮助

    谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多