Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
namespace AppBundle\Form\DataMapper;
use Symfony\Component\Form\DataMapperInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Security\Core\User\UserInterface;
class UserSettingDataMapper implements DataMapperInterface
{
public function mapDataToForms($data, $forms)
{
if (!$data instanceof UserInterface) {
throw new UnexpectedTypeException($data, 'must be instance of Symfony\Component\Security\Core\User\UserInterface');
}
foreach ($forms as $form) {
/** @var string */
$key = $form->getName();
/** @var \Symfony\Component\Form\FormConfigInterface */
$config = $form->getConfig();
/** @var boolean */
$hasSetting = $data->hasSetting($key);
/** @var \AppBundle\Entity\UserSetting */
$setting = $data->getSetting($key);
if ($hasSetting && $config->getMapped()) {
$form->setData($setting->getValue());
} else {
$form->setData($config->setData());
}
}
}
public function mapFormsToData($forms, $data)
{
if (null === $data) {
return;
}
if (!$data instanceof UserInterface) {
throw new UnexpectedTypeException($data, 'must be instance of Symfony\Component\Security\Core\User\UserInterface');
}
foreach ($forms as $form) {
/** @var string */
$key = $form->getName();
/** @var \Symfony\Component\Form\FormConfigInterface */
$config = $form->getConfig();
/** @var boolean */
$hasSetting = $data->hasSetting($key);
/** @var \AppBundle\Entity\UserSetting */
$setting = $data->getSetting($key);
if ($config->getMapped() && $form->isSubmitted() && $form->isSynchronized() && !$form->isDisabled()) {
if (null === $form->getData()) {
$data->removeSetting($setting);
} else {
$setting->setValue($form->getData());
$data->addSetting($setting);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.