简体   繁体   English

我可以在Sonata Admin控制器中使用prePersist / preUpdate来保留多个对象吗?

[英]Can I use prePersist/preUpdate in Sonata Admin controller to persist more than one object?

I have this Alias entity: 我有这个Alias实体:

use Gedmo\Timestampable\Traits\TimestampableEntity;

class Alias
{
    use IdentifierAutogeneratedTrait;
    use TimestampableEntity;
    use ActiveTrait;

    /**
     * @var string
     * @ORM\Column(type="string", length=150)
     */
    private $name;

    /**
     * Command associated to the alias.
     *
     * @var Command[]
     * @ORM\ManyToMany(targetEntity="Command", mappedBy="aliases", cascade={"persist"})
     */
    private $commands;

    ...
}

And I have this Admin controller: 我有这个管理员控制器:

class AliasAdmin extends Admin
{
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            ->add('name', null, array('required' => true))
            ->add('active', null, array('required' => false));
    }

    ...

    public function prePersist($alias)
    {
        // remove extra white spaces
        $noWhiteSpaces = str_replace(' ', '', $alias->getName());
        // split into several names
        $aliasArr = explode(',', $noWhiteSpaces);
    }

    public function preUpdate($alias)
    {
        ...
    }
}

When I am adding a new Alias on the view - meaning the form itself - I can write one value on the name input field as for example: value1 or I can write multiple values comma separated: value1, value2, value3, value4 . 当我在视图上添加一个新的Alias - 意味着表单本身 - 我可以在name输入字段上写一个值,例如: value1或者我可以用逗号分隔多个值: value1, value2, value3, value4 If I have only one value on the name field when I submit the form then will be no problems but if I have more than one comma separated as the second example then I should check for them on prePersist/preUpdate method in order to split them and create one Alias per name , how I can do this? 如果我在提交表单时在name字段上只有一个值,那么将没有问题,但如果我将多个逗号分隔为第二个示例,那么我应该在prePersist/preUpdate方法上检查它们以便拆分它们每个name创建一个Alias ,我该怎么做? If you take a look to the prePersist method you will see what I am talking about more clear about how to create a new Alias per name in the new $aliasArr , any help? 如果你看一下prePersist方法,你会看到我正在谈论的更清楚如何在新的$aliasArr中为每个名字创建一个新的Alias,任何帮助?

Update: TimestampableEntity is not processed, why? 更新: TimestampableEntity未处理,为什么?

After tried the solution by @m-khalid-junaid I end with the error below due to NOT NULL constraint but I don't know why. 在尝试了@m-khalid-junaid的解决方案后,由于NOT NULL约束,我以下面的错误结束,但我不知道为什么。 Take a look to the code: 看看代码:

class AliasAdminController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function createAction(Request $request = null)
    {
        // the key used to lookup the template
        $templateKey = 'edit';

        if (false === $this->admin->isGranted('CREATE')) {
            throw new AccessDeniedException();
        }

        $object = $this->admin->getNewInstance();
        $this->admin->setSubject($object);

        /** @var $form \Symfony\Component\Form\Form */
        $form = $this->admin->getForm();
        $form->setData($object);

        if ($this->getRestMethod() == 'POST') {
            $form->submit($this->get('request'));
            $isFormValid = $form->isValid();

            // persist if the form was valid and if in preview mode the preview was approved
            if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
                if (false === $this->admin->isGranted('CREATE', $object)) {
                    throw new AccessDeniedException();
                }

                try {
                    $aliasArr = $this->toStrings($object->getName());

                    if (count($aliasArr) > 1) {
                        $object->setName($aliasArr[0]);
                        $object = $this->admin->create($object);
                        unset($aliasArr[0]);
                        $entityManager = $this->getDoctrine()->getManager();

                        foreach ($aliasArr as $alias) {
                            $newAlias = new Alias();
                            $newAlias->setName($alias);
                            $entityManager->persist($newAlias);
                        }

                        $entityManager->flush();
                    } else {
                        $object = $this->admin->create($object);
                    }

                    if ($this->isXmlHttpRequest()) {
                        return $this->renderJson(array(
                            'result' => 'ok',
                            'objectId' => $this->admin->getNormalizedIdentifier($object),
                        ));
                    }

                    $this->addFlash(
                        'sonata_flash_success',
                        $this->admin->trans(
                            'flash_create_success',
                            array('%name%' => $this->escapeHtml($this->admin->toString($object))),
                            'SonataAdminBundle'
                        )
                    );

                    // redirect to edit mode
                    return $this->redirectTo($object);
                } catch (ModelManagerException $e) {
                    $this->logModelManagerException($e);
                    $isFormValid = false;
                }
            }

            // show an error message if the form failed validation
            if (!$isFormValid) {
                if (!$this->isXmlHttpRequest()) {
                    $this->addFlash(
                        'sonata_flash_error',
                        $this->admin->trans(
                            'flash_create_error',
                            array('%name%' => $this->escapeHtml($this->admin->toString($object))),
                            'SonataAdminBundle'
                        )
                    );
                }
            } elseif ($this->isPreviewRequested()) {
                // pick the preview template if the form was valid and preview was requested
                $templateKey = 'preview';
                $this->admin->getShow();
            }
        }

        $view = $form->createView();

        // set the theme for the current Admin Form
        $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());

        return $this->render($this->admin->getTemplate($templateKey), array(
            'action' => 'create',
            'form' => $view,
            'object' => $object,
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function editAction($id = null)
    {
        // the key used to lookup the template
        $templateKey = 'edit';

        $id = $this->get('request')->get($this->admin->getIdParameter());
        $object = $this->admin->getObject($id);

        if (!$object) {
            throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
        }

        if (false === $this->admin->isGranted('EDIT', $object)) {
            throw new AccessDeniedException();
        }

        $this->admin->setSubject($object);

        /** @var $form \Symfony\Component\Form\Form */
        $form = $this->admin->getForm();
        $form->setData($object);

        if ($this->getRestMethod() == 'POST') {
            $form->submit($this->get('request'));

            $isFormValid = $form->isValid();

            // persist if the form was valid and if in preview mode the preview was approved
            if ($isFormValid && (!$this->isInPreviewMode() || $this->isPreviewApproved())) {
                try {
                    $aliasArr = $this->toStrings($object->getName());

                    if (count($aliasArr) > 1) {
                        $object->setName($aliasArr[0]);
                        $object = $this->admin->update($object);
                        unset($aliasArr[0]);
                        $entityManager = $this->getDoctrine()->getManager();

                        foreach ($aliasArr as $alias) {
                            $newAlias = new Alias();
                            $newAlias->setName($alias);
                            $entityManager->persist($newAlias);
                        }

                        $entityManager->flush();
                    } else {
                        $object = $this->admin->update($object);
                    }

                    if ($this->isXmlHttpRequest()) {
                        return $this->renderJson(array(
                            'result' => 'ok',
                            'objectId' => $this->admin->getNormalizedIdentifier($object),
                        ));
                    }

                    $this->addFlash(
                        'sonata_flash_success',
                        $this->admin->trans(
                            'flash_edit_success',
                            array('%name%' => $this->escapeHtml($this->admin->toString($object))),
                            'SonataAdminBundle'
                        )
                    );

                    // redirect to edit mode
                    return $this->redirectTo($object);
                } catch (ModelManagerException $e) {
                    $this->logModelManagerException($e);

                    $isFormValid = false;
                }
            }

            // show an error message if the form failed validation
            if (!$isFormValid) {
                if (!$this->isXmlHttpRequest()) {
                    $this->addFlash(
                        'sonata_flash_error',
                        $this->admin->trans(
                            'flash_edit_error',
                            array('%name%' => $this->escapeHtml($this->admin->toString($object))),
                            'SonataAdminBundle'
                        )
                    );
                }
            } elseif ($this->isPreviewRequested()) {
                // enable the preview template if the form was valid and preview was requested
                $templateKey = 'preview';
                $this->admin->getShow();
            }
        }

        $view = $form->createView();

        // set the theme for the current Admin Form
        $this->get('twig')->getExtension('form')->renderer->setTheme($view, $this->admin->getFormTheme());

        return $this->render($this->admin->getTemplate($templateKey), array(
            'action' => 'edit',
            'form' => $view,
            'object' => $object,
        ));
    }

    private function logModelManagerException($e)
    {
        $context = array('exception' => $e);
        if ($e->getPrevious()) {
            $context['previous_exception_message'] = $e->getPrevious()->getMessage();
        }
        $this->getLogger()->error($e->getMessage(), $context);
    }

    private function toStrings($string)
    {
        $noWhiteSpaces = str_replace(' ', '', $string);
        return explode(',', $noWhiteSpaces);
    }
}

And this is the error: 这是错误:

[2016-02-28 11:10:36] doctrine.DEBUG: "START TRANSACTION" [] []
[2016-02-28 11:10:36] doctrine.DEBUG: INSERT INTO cm_alias (name, created_at, updated_at, active) VALUES (?, ?, ?, ?) {"1":"alias1","2":null,"3":null,"4":true} []
[2016-02-28 11:10:36] doctrine.DEBUG: "ROLLBACK" [] []
[2016-02-28 11:10:36] app.ERROR: Failed to create object: PlatformAdminBundle\Entity\Alias {"exception":"[object] (Sonata\\AdminBundle\\Exception\\ModelManagerException(code: 0): Failed to create object: PlatformAdminBundle\\Entity\\Alias at /var/www/html/platform.sonata/vendor/sonata-project/doctrine-orm-admin-bundle/Model/ModelManager.php:142, Doctrine\\DBAL\\Exception\\NotNullConstraintViolationException(code: 0): An exception occurred while executing 'INSERT INTO cm_alias (name, created_at, updated_at, active) VALUES (?, ?, ?, ?)' with params [\"alias1\", null, null, 1]:\n\nSQLSTATE[23000]: Integrity constraint violation: 1048 Column 'created_at' cannot be null at /var/www/html/platform.sonata/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:112, Doctrine\\DBAL\\Driver\\PDOException(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'created_at' cannot be null at /var/www/html/platform.sonata/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:93, PDOException(code: 23000): SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'created_at' cannot be null at /var/www/html/platform.sonata/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:91)","previous_exception_message":"An exception occurred while executing 'INSERT INTO cm_alias (name, created_at, updated_at, active) VALUES (?, ?, ?, ?)' with params [\"alias1\", null, null, 1]:\n\nSQLSTATE[23000]: Integrity constraint violation: 1048 Column 'created_at' cannot be null"} []

Why TimestampableEntity trait is not processed by the new Admin controller? 为什么新的管理控制器不处理TimestampableEntity特征? What I am missing here? 我在这里缺少什么?

Maybe something like this: 也许是这样的:

public function prePersist($alias)
{
    // remove extra white spaces
    $noWhiteSpaces = str_replace(' ', '', $alias->getName());
    // split into several names
    $aliasArr = explode(',', $noWhiteSpaces);

    $currentAliasName = $aliasArr[0]; // Use the first name for the Alias created by your admin class.
    $alias->setName($currentAliasName);
    unset($aliasArr[0]);

    $em = $this->getConfigurationPool()->getContainer()->getDoctrine()->getManager();

    foreach ($aliasArr as $aliasName) {
        $newAlias = new Alias();
        $newAlias->setName($aliasName);
        $newAlias->setActive(?);

        $em->persist($newAlias);
        $em->flush($newAlias);
    }
}

If you want to add same object with different aliases its better to create a CRUDController controller for your admin class, Once you have your CRUDController you can override createAction & editAction of base class and implement your logic here prePresist/preUpdate events for your current object to play with to create copies for your object with different information use a controller. 如果你想用不同的别名添加相同的对象,最好为你的管理类创建一个CRUDController控制器,一旦你有了CRUDController,你可以覆盖基类的createActioneditAction ,并在这里实现你的逻辑,为你当前的对象提供prePresist / preUpdate事件使用控制器来玩具有不同信息的对象的副本。 I have mentioned only necessary code below you can copy from sonata's CRUDController and implement the same logic in editAction 我已经提到下面只有必要的代码,你可以从sonata的CRUDController复制并在editAction实现相同的逻辑

public function createAction(Request $request = null)
{
    // .. some code here copy from base class
    try {
        $noWhiteSpaces = str_replace(' ', '', $object->getName());
        // split into several names
        $aliases = explode(',', $noWhiteSpaces);
        if (count($aliases) > 1) {
            $object->setName($aliases[0]);
            $object = $this->admin->create($object);
            unset($aliases[0]);
            $DM = $this->getDoctrine()->getManager();
            foreach ($aliases as $alias) {
                $newAlias = new Alias();
                $newAlias->setName($alias);
                $DM->persist($newAlias);
            }
            $DM->flush();
        } else {
            $object = $this->admin->create($object);
        }
    } catch (ModelManagerException $e) {
        $this->handleModelManagerException($e);

        $isFormValid = false;
    }
    // .. some code here copy from base class
}

Edit for created_at not null error 编辑created_at not null错误

You need to define a constructor function in your alias entity and there initialize your createdAt property with DateTime object 您需要在别名实体中定义构造函数,并使用DateTime对象初始化createdAt属性

/**
 * Constructor
 */
public function __construct()
{
    $this->createdAt = new \DateTime('now');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM