PUGXMultiUserBundle: custom profile template

家住魔仙堡 提交于 2019-12-11 23:33:47

问题


A method to enable custom user profile templates involves modifying the vendor's Configuration.php. Is there a method that does not? Or is this a viable solution? Current method appears below:

Update: I'm thinking my bundle needs to take responsibility for the configuration so I'm in the throes of deciphering and applying the CompilerPassInterface.

[Edit: another way to ask the question - can this be done by prepending the template option with PrependExtensionInterface? If so, how might that work?]

config.yml

pugx_multi_user:
  users:
    staff:
        entity: 
          class: Acme\MyBundle\Entity\Staff
#          factory: 
        registration:
          form: 
            type: Acme\UserBundle\Form\RegistrationStaffFormType
            name: fos_user_registration_form
            validation_groups:  [Registration, Default]
          template: AcmeUserBundle:Registration:staff.form.html.twig
        profile:
          form:
            type: Acme\UserBundle\Form\ProfileStaffFormType
            name: fos_user_profile_form
            validation_groups:  [Profile, Default]
# template line added
          template: AcmeUserBundle:Profile:staff.form.html.twig 
         ...

excerpt from PUGX\MultiUserBundle\DependencyInjection\Configuration.php

[Note addition of ->scalarNode('template')->defaultValue(null)->end()]

...
                        ->children()
                            ->arrayNode('profile')
                                ->addDefaultsIfNotSet()
                                ->children()
                                    ->arrayNode('form')
                                    ->addDefaultsIfNotSet()
                                        ->children()
                                            ->scalarNode('type')->defaultValue(null)->end()
                                            ->scalarNode('name')->defaultValue('fos_user_profile_form')->end()
                                            ->arrayNode('validation_groups')
                                                ->prototype('scalar')->end()
                                                ->defaultValue(array('Profile', 'Default'))
                                            ->end()
                                        ->end()
                                    ->end()
                                    ->scalarNode('template')->defaultValue(null)->end()
                                 ->end()
                            ->end()
                        ->end()
...

ProfileController (in extended User Bundle)

class ProfileController extends BaseController
{

    /**
     * Edit the user
     */
    public function editAction(Request $request)
    {
        $user = $this->container->get('security.context')->getToken()->getUser();
        if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        $discriminator = $this->container->get('pugx_user.manager.user_discriminator');
        $users = $this->container->getParameter('pugx_user_discriminator_users');
        $class = $discriminator->getClass($user);

        foreach ($users as $userType) {
            if ($userType['entity']['class'] == $class) {
                $templateString = $userType['profile']['template'];
                if (false === strpos($templateString, $this->container->getParameter('fos_user.template.engine'))) {
                    $template = 'FOSUserBundle:Profile:edit.html.';
                } else {
                    $l = strrpos($templateString, ".");
                    $template = substr($templateString, 0, $l + 1);
                }
            }
        }

        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->container->get('event_dispatcher');

        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event);

        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }

        /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
        $formFactory = $this->container->get('fos_user.profile.form.factory');

        $form = $formFactory->createForm();
        $form->setData($user);

        if ('POST' === $request->getMethod()) {
            $form->bind($request);

            if ($form->isValid()) {
                /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
                $userManager = $this->container->get('fos_user.user_manager');

                $event = new FormEvent($form, $request);
                $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);

                $userManager->updateUser($user);

                if (null === $response = $event->getResponse()) {
                    $url = $this->container->get('router')->generate('fos_user_profile_show');
                    $response = new RedirectResponse($url);
                }

                $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

                return $response;
            }
        }

        return $this->container->get('templating')->renderResponse(
                        $template . $this->container->getParameter('fos_user.template.engine'), array('form' => $form->createView())
        );
    }

回答1:


I have create a pull request here that handles custom profile templates.




回答2:


Progress of a sort. It took a while but it became clear I would not be able to add a template parameter to the PUGXMultiUserBundle configuration. So I decided to create my own configuration. Had to be sure to make a couple of other hack-like fixes to my own code, but this at least seems to work. (I won't accept my answer; I'd rather Patt's solution gets implemented.) But here's what I did:

config.yml addition:

vol_user:
    staff: VolUserBundle:Profile:staff.form.html.twig
    volunteer: VolUserBundle:Profile:volunteer.form.html.twig
    admin: VolUserBundle:Profile:admin.form.html.twig

routing.yml change to fos_user_profile (added _edit to parameter name):

fos_user_profile_edit:
    resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
    prefix: /profile

Revised controller:

    public function editAction(Request $request)
    {
        $user = $this->container->get('security.context')->getToken()->getUser();
        if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        $discriminator = $this->container->get('pugx_user.manager.user_discriminator');
        $users = $this->container->getParameter('pugx_user_discriminator_users');
        $class = $discriminator->getClass($user);
        $templates = $this->container->getParameter('vol_user');

        foreach ($users as $userType) {
            if ($userType['entity']['class'] == $class) {
                $l = strrpos($class, DIRECTORY_SEPARATOR ) + 1;
                $type = strtolower(substr($class, $l));
                $templateString = $templates[$type];
                if (false === strpos($templateString, $this->container->getParameter('fos_user.template.engine'))) {
                    $template = 'FOSUserBundle:Profile:edit.html.';
                } else {
                    $l = strrpos($templateString, ".");
                    $template = substr($templateString, 0, $l + 1);
                }
            }
        }
...
}

Configuration.php

namespace Vol\UserBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('vol_user');

        $rootNode->
                children()
                    ->scalarNode('staff')->defaultValue(null)->end()
                    ->scalarNode('volunteer')->defaultValue(null)->end()
                    ->scalarNode('admin')->defaultValue(null)->end()
                ->end()
                ->end();

        return $treeBuilder;
    }
}

VolUserExtension

class VolUserExtension extends Extension
{

    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $container->setParameter('vol_user', $config);
    }

}


来源:https://stackoverflow.com/questions/22203590/pugxmultiuserbundle-custom-profile-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!