從Symfony開始是一個相當的學習曲線。即使在閱讀了幾個小時之後,我也無法理解這個大概簡單的問題。我想從一個實體中加載一個選擇形式的值。symfony:訪問控制器變量形式
控制器:
namespace AppBundle\Controller
class ItemController extends Controller
{
public function itemAction (Request $request)
{
$myItems = new Itemlist();
//some statements to fill $myItems
$form = $this->createForm (AllitemsType::class, $myItems);
// some more stuff
return $this->render (...);
}
}
實體:
namespace AppBundle\Entity;
class Itemlist
{
protected $choices;
protected $defaultvalue;
public function __construct()
{
$choices = array();
}
// all the get and set-methods to fill/read the $choices array and $defaultvalue
}
形式:
namespace AppBundle\Form
class AllitemsType extends AbstractType
{
public function buildForm (FormBuilderInterface $builder, array $options)
{
// and here is my problem: how can I fill next two lines with values from the Itemlist-Entity?
// The Itemlist instance has been build in the controller and is unknown here
$items = ??? // should be 'AppBundle\Entity\Itemlist->$choices
$defaultitem = ??? // should be 'AppBundle\Entity\Itemlist->$defaultvalue
$choices_of_items = array (
'choices' => $items,
'expanded' => true,
'multiple' => false,
'data' => $defaultitem,
);
$builder->add ('radio1', ChoiceType::class, $choices_of_items);
}
}
任何幫助表示讚賞, 鎢
您的「最佳實踐」答案確實解決了填充選項,但並不尊重填充「數據」屬性,對嗎? 對不起,我不抓住其他兩個可選答案。 無論如何感謝您的貢獻。 – Wolfram
@wolfram對不起,我忘記了數據選項,但是我用於選擇的方法相同 – DonCallisto