I want to create my entity Settings, which will have basic editable information about my page. I've created my entity Settings.php with this source:
<?php
namespace Acme\SettingsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
* @ORM\Table(name="settings")
*/
class Settings
{
/**
* @ORM\Column(type="string", length=100)
*/
protected $page_name;
/**
* @ORM\Column(type="string", length=100)
*/
protected $page_description;
/**
* @ORM\Column(type="string", length=100)
*/
protected $page_email;
}
and I do not know, how to tell in my controller that will be only overwriting existing data, not creating new. This is my controller AdminController.php
public function indexAction(Request $request)
{
if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) {
throw new AccessDeniedException();
}
$settings = new Settings();
$form = $this->createForm('settings', $settings);
$form->handleRequest($request);
if($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($settings);
try {
$em->flush();
} catch (\PDOException $e) {
// sth
}
$this->get('session')->getFlashBag()->add(
'success',
'Settings was successfuly changed'
);
}
return $this->render('AcmeSettingsBundle:Admin:index.html.twig', array('form' => $form));
}
I didn't test it, but I believe, it creates a new Settings object with new data. Any help?
You should always set some field to act as an ID, even if it meant to be dummy.
Assign some default value that you will always use and then you should be able to update your settings with no problem.
Usually, DBMS wars you about absence of unique identifier so same applies to Doctrine.
$settings = new Settings();
$settings->setId(Settings::DUMMY_IDENTIFIER); // const within class
# rest of the logic
# ....
$em = $this->getDoctrine()->getManager();
$em->persist($settings);
try {
$em->flush();
} catch (\PDOException $e) {
}
You could take another approach: persist every property as a single row. However, you would need to build more complex form type and execute more queries.
EDIT:
You could use raw SQL but that is less flexible:
# raw query
$sql = "UPDATE settings SET page_name = ?, page_description = ?, page_email = ?";
# data
$params = array( $settings->getPageName(), $settings->getPageDesc(), $settings->getPageEmail());
# must specify type due to protection against sql injection
$types = array(\PDO::PARAM_STR,\PDO::PARAM_STR,\PDO::PARAM_STR);
# execute it
$stmt = $this->getEntityManager()->getConnection()->executeUpdate($sql, $params, $types);