我在我的應用程序中有一個名爲Content
的模型。這有三個屬性與另一個名爲ContentBodyType
的模型鏈接。這是爲了允許「橫幅」,「摘要」和「主要」內容的三個部分。如何使用Silex和Symfony Forms在嵌入式窗體中顯示嵌入對象的數據?
我使用SymfonyForms爲Content
模型創建了一個FormType
。下面顯示了這是如何建立起來的:
public function buildForm(FormBuilderInterface $builder, array $options) {
$list = $this -> app['model.collection'] -> getList();
$builder -> add('id', HiddenType::Class)
-> add('displayname', TextType::Class, array("label" => "Friendly Name", "trim" => true))
-> add('description', TextareaType::Class)
-> add('collection', ChoiceType::Class, array(
'choices_as_values' => true,
"choices" => $list,
"label" => "Collection"
))
-> add('publish', ChoiceType::Class, array(
"choices" => array('Yes' => true, 'No' => false),
"choices_as_values" => true,
"expanded" => true,
"multiple" => false,
))
-> add('homepage', ChoiceType::Class, array(
"choices" => array('Yes' => true, 'No' => false),
"choices_as_values" => true,
"expanded" => true,
"multiple" => false,
))
-> add('startdate', DateTimeType::Class, array("widget" => "single_text", "format" => "dd-MM-yyyy"))
-> add('expirydate', DateTimeType::Class, array("widget" => "single_text", "format" => "dd-MM-yyyy"))
-> add('type', ChoiceType::Class, array(
"choices_as_values" => true,
"choices" => array(
'News' => "news",
'Page' => "page",
'Pinned' => "pinned",
'Blog' => "blog",
'Slider' => "slider"
),
"label" => "Type"
))
-> add('main', new \Turtle\Form\Type\ContentBodyType())
-> add('banner', new \Turtle\Form\Type\ContentBodyType())
-> add('summary', new \Turtle\Form\Type\ContentBodyType())
-> add('save', SubmitType::Class)
-> add('cancel', ButtonType::Class);
// only add the name field if this is a new template
if (!$this -> content || null == $this -> content -> getId()) {
$builder -> add('name', TextType::Class, array('label' => 'Name'));
}
}
當應用程序加載了它表明從Content
模型在正確的字段中的數據,不過是嵌套形式的部分不顯示的那些形式。
現在我知道這是因爲對於'banner','summary'和'main'中的每一個,我都會創建一個ContentBodyType
表單對象的新實例。但是我無法弄清楚如何將對象傳遞給它,以便它不必被創建。
的形式使用下面的代碼創建:
public function edit(Request $request, $id) {
// Get the entity from the datastore for the specified id
if ($id == "new") {
$item = new \Turtle\Model\Entity\Content();
} else {
$item = $this -> app['model.content'] -> getById($id) -> first();
}
if (!$item) {
return "notthere";
}
// Build the form
$type = new \Turtle\Form\Type\ContentType($this -> app, $item);
$form = $this -> app['form.factory']
-> createBuilder(
$type,
$item,
array(
'action' => $this -> app['url_generator'] -> generate(
'content_update',
array(
'id' => $item -> getId()
)
)
)
) -> getForm();
// process the form to see if it has been submitted or not
$form -> handleRequest($request);
snip ....
我相信,這是一個簡單的修復,但我看不出它是什麼。
謝謝,羅素