Reputation: 793
I'm new to silex. Learning forms. I want to populate a form with data from database. I have this entity class
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......
Then in my controller
$page = new Page();
$form = $app['form.factory']->create(new UserForm(), $page);
etc ........
When the form is rendered it's fields are empty (which is normal)
If I do
$paget->setTitle = 'Title';
before rendering the form then the field title in the form is populated with the word Title.
So my question is how to populate the form fields with data from database? I guess somehow the properties of Page class should be populated with the data from the database but have no idea how to do that.
Short example will be useful.
Upvotes: 1
Views: 351
Reputation: 770
First you need to register the Entity Manager as a service:
$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;
});
Then in your controller you can use the Entity Manger's find method to load an entity. In this example I will load an id field from the $_GET parameters.
$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 reference: http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html#entities-and-the-identity-map
Upvotes: 0