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



嘿,我是 cakePHP 的新手,我正在遵循书签教程,但我使用的是产品表,而不是书签表,在这里,我想要的是添加新产品时,我想在输入字段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() ?>

用户表有

id, username, email, password

我跟着$username = $this-Users->find('list')但我真的不明白如何编写此查询。我需要运行什么查询?,

你也可以这样做

用户表.php

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

然后代码

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

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

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

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

例如,这会给你这个数组:

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

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

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

希望这对你有帮助

谢谢

最新更新