【问题标题】:Symfony/Silex populate form with data from databaseSymfony/Silex 使用数据库中的数据填充表单
【发布时间】:2015-03-06 13:48:20
【问题描述】:

我是 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 类的属性,但不知道该怎么做。

简短的例子会很有用。

【问题讨论】:

  • 您使用的是 Symfony 2 还是 Silex?您的标题暗示 Symfony,但您的(非工作)示例是 Silex。使用 Symfony,使用 Doctrine ORM 很容易。 Silex 没有为 Doctrine ORM 提供服务。您要么需要添加这样的服务,要么使用 dbal 服务查询您的数据库,然后将数据传输到您的 $page 对象。
  • 在我的例子中我的意思是 silex
  • 文档通常是一个很好的起点:silex.sensiolabs.org/doc/providers/doctrine.html
  • 你的意思是 $paget->setTitle('Title'); 而不是 $paget->setTitle = 'Title'; 不是吗?

标签: php symfony doctrine entity silex


【解决方案1】:

首先您需要将实体管理器注册为服务:

$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;
});

然后在您的控制器中,您可以使用实体管理器的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多