在CakePHP中显示用户名而不是user_id

时间:2018-04-16 11:04:32

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

嘿,我是cakePHP上的新手,我正在关注Bookmark教程,但我没有使用书签表,而是使用了产品表, 这里我想要的是在添加新产品时,我想在输入字段user_id中显示用户名而不是 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->find('list') 但我真的不明白如何编写此查询。 我需要运行什么查询?,

3 个答案:

答案 0 :(得分:2)

你也可以这样做

<强> UsersTable.php

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

然后是代码

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

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

答案 1 :(得分:1)

select输入采用key =&gt;的数组。价值形式。因此,要以该格式获取$users数组,请在控制器中执行以下操作:

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

这将为您提供此数组:

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

答案 2 :(得分:1)

首先,这取决于你的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() ?>

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

希望这会对你有所帮助

由于