我是silex的新手。学习形式。我想用数据库中的数据填充表单。我有这个实体类
namespace NS\Entity\Admin;
class Page
{
protected $id;
protected $title;
protected $keywords;
protected $description;
protected $content;
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
public function getTitle()
{
return $this->title;
}
public function setTitle($title)
{
$this->title = $title;
}
etc......
然后在我的控制器中
$page = new Page();
$form = $app['form.factory']->create(new UserForm(), $page);
etc ........
表单呈现时,它的字段为空(这是正常的)
如果我这样做
$paget->setTitle = 'Title';
在呈现表单之前,表单中的字段标题将填充单词Title。
所以我的问题是如何使用数据库中的数据填充表单字段? 我猜想Page类的属性应该用数据库中的数据填充,但不知道如何做到这一点。
简短的例子很有用。
答案 0 :(得分:0)
首先,您需要将实体管理器注册为服务:
$app['em'] = $app->share(function (Application $app) {
$connection = [
'user' => 'root',
'password' => 'password',
'host' => '127.0.0.1',
'port' => '3306',
'dbname' => 'database',
'driver' => 'pdo_mysql',
];
// If using annotations... e.g. /../Entity/Page.php
// $config = Setup::createAnnotationMetadataConfiguration(
// [__DIR__.'/../Entity'],
// $app['debug'],
// null,
// null,
// false // Use Simple Annotations
// );
// If using Yaml... e.g. /../config/orm/Page.orm.yml
$config = Setup::createYAMLMetadataConfiguration([__DIR__.'/../config/orm'], $app['debug']);
$em = EntityManager::create($connection, $config);
return $em;
});
然后在您的控制器中,您可以使用Entity Manger的find方法加载实体。在这个例子中,我将从$ _GET参数中加载一个id字段。
$app->get('/example', function (Request $request, Application $app) {
$page = $app['em']->find('Page', $request->query->getInt('id'));
if (!$page) {
throw new NotFoundHttpException("Page not found");
}
// ... pass page to form builder
$form = $app['form.factory']->create(new UserForm(), $page);
});
Doctrine Entity Manager参考:http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html#entities-and-the-identity-map