Can you tell me how to use CakePHP's displayField directive? I can not figure out how to use it.
So, in a model file, I have following code:
<?php
class Task extends AppModel {
var $name = 'Task';
var $displayField = 'projectName';
//The Associations below have been created with all possible keys, those that are not needed can be removed
var $belongsTo = array(
'User' => array(
'className' => 'U开发者_开发问答ser',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
...
How can I use this, to display field projectName
in select form field?
So, you have Task belongsTo Project
(FK: project_id). You want to make a project select box in tasks/add and tasks/edit views.
The problem is that the projects table doesn't have a field called name
or title
so the select box is empty. You wouldn't have any problems if there was a name
or a title
field, right?
Well, here's the solution, in the Project model add this:
var $displayField = 'projectName';
http://book.cakephp.org/view/71/Model-Attributes
So you were going in the right direction, just messed up the models a bit. I hope you understand it now ;]
You can basically do this (in controller):
$this->set('tasks', $this->Task->find('list'));
And make an input with name task_id, and make sure to force it to be a select box, so (in views):
echo $form->input('task_id', array('label' => 'youLabelHere', 'type' => 'select'));
displayField gives you a chance to choose which field will be used as a displayed option (one of) in the select box, if it's not provided in model the script will look for 'name' or 'title'.
If you wan't to display projects in the users forms (add, edit option) then your associations aren't right. Always make sure that there is an association (with good, conventional tables and keys names) between two model when you want to make a select box, Cake makes it as easy as can it gets.
精彩评论