我希望能够将实体定义的常量转换为其相关的文本值。为了更好地概述,我删除了大部分与问题无关的代码
Todo实体
/**
* Todo
*
* @ORM'Table(name="todo")
* @ORM'Entity(repositoryClass="TodoBundle'Repository'TodoRepository")
* @ORM'HasLifecycleCallbacks
*/
class Todo
{
const PRIORITY_HIGH = 2;
const PRIORITY_NORMAL = 1;
const PRIORITY_LOW = 0;
/**
* @var int
*
* @Assert'NotBlank(groups={"new", "edit"})
* @Assert'Choice(callback="getPriorities")
*
* @ORM'Column(name="priority", type="integer")
*/
private $priority;
/**
* Set priority
*
* @param integer $priority
*
* @return Todo
*/
public function setPriority($priority)
{
$this->priority = $priority;
return $this;
}
/**
* Get priority
*
* @return int
*/
public function getPriority()
{
return $this->priority;
}
/**
* Get all priorities
*
* @return int
*/
public static function getPriorities()
{
return array(
'High' => self::PRIORITY_HIGH,
'Normal' => self::PRIORITY_NORMAL,
'Low' => self::PRIORITY_LOW
);
}
}
Twig概述
{% for todo in todos %}
<tr>
<td>{{ todo.title }}</td>
<td>{{ todo.content }}</td>
<td>{{ todo.priority }}</td> *Change this to output High, Normal or Low according to its set priority*
<td>{{ todo.duedate|date('d/m/Y') }}</td>
<td>
<div class="btn-group" role="group">
<a href="{{ path('todo.show', {'id': todo.id }) }}" class="btn btn-success">View</a>
<a href="{{ path('todo.edit', {'id': todo.id }) }}" class="btn btn-warning">Edit</a>
<a href="{{ path('todo.delete', {'id': todo.id }) }}" class="btn btn-danger">Delete</a>
</div>
</td>
</tr>
{% endfor %}
当使用FormBuilder创建表单时,我可以将这段代码称为
->add('priority', ChoiceType::class, array(
'choices' => Todo::getPriorities()
))
创建带有像一样填充的文本和值的dorpdown字段
<select id="new_priority" name="new[priority]" class="form-control">
<option value="2">High</option>
<option value="1" selected="selected">Normal</option>
<option value="0">Low</option>
</select>
我希望这是可能的,或者以另一种方式实现,在稍后的体育场中实现翻译将是有用的。
尝试使用另一种以相反方式返回关联数组的方法,例如:
public static function getPrioritiesForSelect()
{
return array(
self::PRIORITY_HIGH => 'High',
self::PRIORITY_NORMAL => 'Normal',
self::PRIORITY_LOW => 'Low'
);
}
然后,你将能够翻译字符串,如"高","正常"等
如果你不喜欢这个解决方案,如果你使用的是基于翻译id字符串的翻译结构,那么,你可以再次创建另一个方法,返回由前缀和常量值组成的串联字符串,然后对其进行翻译
public static function getPrioritiesForSelect()
{
return array(
'High' => 'string.priority.' . self::PRIORITY_HIGH,
'Normal' => 'string.priority.' . self::PRIORITY_NORMAL,
'Low' => 'string.priority.' . self::PRIORITY_LOW
);
}
在你的翻译文件中,你会有这样的东西:
string:
priority:
2: 'High'
1: 'Normal'
0: 'Low'