Unable to generate a URL for the named route "admin_app_sonatauseruser_create" after renaming SonataUserUser entity - symfony

My application worked fine until I decided to rename SonataUserUser to User and SonataUserUserGroup to group.
This is how my user entity looks like
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Sonata\UserBundle\Entity\BaseUser;
/**
* #ORM\Entity
* #ORM\Table(name="users")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
protected $id;
.....
public function __construct()
{
parent::__construct();
}
public function __toString()
{
return $this->getFirstName() === null ? 'New' : $this->getFullname();
}
}
App\Admin\UserAdmin
declare(strict_types=1);
namespace App\Admin;
use FOS\UserBundle\Model\UserManagerInterface;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Form\Type\ModelType;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\Form\Type\DatePickerType;
use Sonata\UserBundle\Form\Type\SecurityRolesType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\LocaleType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\TimezoneType;
use Symfony\Component\Form\Extension\Core\Type\UrlType;
use Sonata\UserBundle\Admin\Model\UserAdmin as BaseUserAdmin;
class UserAdmin extends BaseUserAdmin
{
protected $translationDomain = 'SonataBundle';
/**
* {#inheritdoc}
*/
protected function configureShowFields(ShowMapper $showMapper): void
{
$showMapper
->with('General')
->add('username')
->add('email')
->end()
->with('Groups')
->add('groups')
->end()
->with('Profile')
->add('dateOfBirth')
->add('firstname')
->add('lastname')
->add('website')
->add('biography')
->add('gender')
->add('locale')
->add('timezone')
->add('phone')
->end()
;
}
/**
* {#inheritdoc}
*/
protected function configureFormFields(FormMapper $formMapper): void
{
// define group zoning
$formMapper
->tab('Details')
->with('Profile', ['class' => 'col-md-6'])->end()
->with('General', ['class' => 'col-md-6'])->end()
->with('Social', ['class' => 'col-md-6'])->end()
->end();
$now = new \DateTime();
$genderOptions = [
'choices' => \call_user_func([$this->getUserManager()->getClass(), 'getGenderList']),
'required' => true,
'translation_domain' => $this->getTranslationDomain(),
];
$formMapper
->tab('Details')
->with('General')
->add('username')
->add('email')
->add('plainPassword', PasswordType::class, [
'required' => (!$this->getSubject() || null === $this->getSubject()->getId()),
'label' => 'Password',
'help' => 'Updating this field will change your password.'
])
->end()
->with('Profile')
->add('firstname', null, ['required' => false])
->add('lastname', null, ['required' => false])
->add('dateOfBirth', DatePickerType::class, [
'required' => false,
])
->add('gender', ChoiceType::class, $genderOptions)
->add('locale', LocaleType::class, ['required' => false])
->add('timezone', TimezoneType::class, ['required' => false])
->add('phone', null, ['required' => false])
->end()
->end();
}
}
config/routes/sonata_admin.yaml
admin_area:
resource: "#SonataAdminBundle/Resources/config/routing/sonata_admin.xml"
prefix: /admin
_sonata_admin:
resource: .
type: sonata_admin
prefix: /admin
config/packages/sonata_user
sonata_user:
security_acl: false
manager_type: orm
class:
user: App\Entity\User
group: App\Entity\Group
mailer: sonata.user.mailer.default
impersonating:
route: sonata_admin_dashboard
table:
user_group: "users_groups"
The error I get is An exception has been thrown during the rendering of a template ("Unable to generate a URL for the named route "admin_app_sonatausergroup_create" as such route does not exist."). in in vendor/sonata-project/admin-bundle/src/Resources/views/Block/block_admin_list.html.twig (line 28).
I'd appreciate any form of help

What does php bin/console debug:router return? You could find the route name that is being used I would expect. Example output from one that I have in development:
dashboard ANY ANY ANY /account/dashboard
home ANY ANY ANY /
app_register ANY ANY ANY /register
app_login ANY ANY ANY /login
app_logout ANY ANY ANY /logout

Related

symfony easyadmin form field type entity with filter list

I use symfony 3.4 and easycorp/easyadmin-bundle 1.17
This is my class "Quotation", the "artisan" field is an "under registration" of the "Person" entity (person.type = 1) :
class Quotation
{
/** others fields... */
/**
* 1 => 'artisan', 2 => 'customer'
*/
private $type;
/**
* #ORM\ManyToOne(targetEntity="Person", inversedBy="artisanQuotations", cascade= { "persist" })
* #ORM\JoinColumn(name="artisan_id", referencedColumnName="id")
*/
private $artisan;
/** getters and setters ... */
I have a problem with a form field using a custom field type
form:
fields:
...
- { property: 'artisan', label: '', type: 'AppBundle\Form\Field\ArtisanType' }
I created this form field type to be able to filter the list thanks to the query_builder :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('artisan', EntityType::class, array(
'class' => 'AppBundle:Person',
'label' => false,
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('person')
->where('person.type = 1');
},
'attr' => array('data-widget' => 'select2'),
'multiple' => false,
'expanded'=> false
));
}
my form is displayed perfectly well but when i submit this form i have an error :
Expected argument of type "AppBundle\Entity\Person", "array" given
Thank you in advance for your help
Instead of using the buildForm method you should use configureOptions here. That way your form is not extended by another subform which results in the array.
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ArtisanType extends AbstractType
{
/**
* #param \Symfony\Component\OptionsResolver\OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'class' => 'AppBundle:Person',
'label' => false,
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('person')
->where('person.type = 1');
},
'attr' => array('data-widget' => 'select2'),
'multiple' => false,
'expanded'=> false,
]);
}
/**
* #return string|null
*/
public function getParent()
{
return EntityType::class;
}
}

Persisting entity with relation and form data

I have the AppBundle\Entity\Comments entity which I want to persist to the database when the user fill the form I can't find information exactly how to save the form data to the database:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="Comments")
*/
class Comments
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="Employer")
* #ORM\JoinColumn(name="employer_id", referencedColumnName="id")
*/
private $employer;
/**
* #ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
* #ORM\JoinColumn(name="company_id", referencedColumnName="id")
*/
private $company;
/**
* #ORM\ManyToOne(targetEntity="Commenttypes")
* #ORM\JoinColumn(name="comment_id", referencedColumnName="id")
*/
private $comment;
/**
* #ORM\Column(type="date")
*/
private $from_date;
/**
* #ORM\Column(type="date")
*/
private $to_date;
?>
Here is the Form Type:
<?
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\OptionsResolver\OptionsResolver;
class WorkerType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('comment', 'entity', array(
'class' => 'AppBundle\Entity\CommentTypes',
'label' => 'Comment:'
))
->add('from_date', 'Symfony\Component\Form\Extension\Core\Type\DateType', array(
'label' => 'From date:',
'input' => 'datetime',
'widget' => 'single_text',
'format' => 'dd-MM-yyyy',
'attr' => [ 'class' => 'datepicker' ]
))
->add('to_date', 'Symfony\Component\Form\Extension\Core\Type\DateType', array(
'label' => 'To date:',
'input' => 'datetime',
'widget' => 'single_text',
'format' => 'dd-MM-yyyy',
'attr' => [ 'class' => 'datepicker' ]
))
->add('submit', 'Symfony\Component\Form\Extension\Core\Type\SubmitType', array(
'label' => 'Submit',
'attr' => [ 'class' => 'buttonColor' ]
));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Comments',
));
}
}
?>
So by now, I'm receiving the data for the fields $from_date and $to_date and $comment (the ID of the comment from the dropdown) from the Form, what I need to to in my controller in order to persist the comment object to the database. Here is my controller:
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\Comments;
use AppBundle\Form\Type\WorkerType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class Worker extends Controller
{
/**
* #Route("/worker/{id}", name="worker")
*/
public function indexAction($id, Request $request)
{
$comment = new Comments();
$form = $this->createForm('AppBundle\Form\Type\WorkerType', $comment);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
{{{{ CODE HERE }}}}
}
return $this->render('default/worker.html.twig',array(
'form' => $form->createView()
));
}
}
I exactly want to know what I need to do to persist the comment object if the form is valid, I'm trying with this:
if ($form->isSubmitted() && $form->isValid()) {
$comment->setEmployer($id);
$comment->setCompany($this->getUser());
$comment->setComment($form->get('comment')->getData());
$comment->setfrom_date($form->get('from_date')->getData());
$comment->setto_date($form->get('to_date')->getData());
}
But I get this error:
Catchable Fatal Error: Argument 1 passed to AppBundle\Entity\Comments::setEmployer() must be an instance of AppBundle\Entity\Employer, string given, called in /home1/rabotnici/src/AppBundle/Controller/Worker.php on line 42 and defined

Issue to override Subscription Form FOSUser Bundle

I'm trying to override the Subscription Form of FOSUser bundle in a Symfony2 Project but I get this error :
Warning: Missing argument 1 for Utilisateurs\UtilisateursBundle\Form\Type\RegistrationFormType::__construct(), called in C:\wamp\www\biblishare\app\cache\dev\appDevDebugProjectContainer.php on line 3730 and defined
I search for the same issue but can't resolve it...
Here are my codes :
-app/config/config.yml
fos_user:
db_driver: orm
firewall_name: main
user_class: Utilisateurs\UtilisateursBundle\Entity\Utilisateurs
from_email:
address: contact#biblishare.com
sender_name: contact#biblishare.com
registration:
form:
type: utilisateurs_utilisateurs_registration
-.../UtilisateursBundle/Resources/config/services.yml
services:
utilisateurs_utilisateurs.listener.authentication_success_handler:
class: %utilisateurs_utilisateurs.listener.authentication_success_handler.class%
public: false
arguments: ['#router', '#doctrine.orm.entity_manager', '#security.context']
utilisateurs_utilisateurs.registration.form.type:
class: Utilisateurs\UtilisateursBundle\Form\Type\RegistrationFormType
tags:
- { name: form.type, alias: utilisateurs_utilisateurs_registration }
and my form:
<?php
namespace Utilisateurs\UtilisateursBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class RegistrationFormType extends AbstractType
{
private $class;
/**
* #param string $class The User class name
*/
public function __construct($class)
{
$this->class = $class;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
// add your custom field
$builder
->add('first_name', null, array('label' => 'Prénom :', 'translation_domain' => 'FOSUserBundle'))
->add('family_name', null, array('label' => 'Nom :', 'translation_domain' => 'FOSUserBundle'))
->add('email', 'email', array('label' => 'form.email', 'translation_domain' => 'FOSUserBundle'))
->add('plainPassword', 'repeated', array(
'type' => 'password',
'options' => array('translation_domain' => 'FOSUserBundle'),
'first_options' => array('label' => 'form.password'),
'second_options' => array('label' => 'form.password_confirmation'),
'invalid_message' => 'fos_user.password.mismatch',
))
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => $this->class,
'intention' => 'registration',
));
}
public function getName()
{
return 'utilisateurs_utilisateurs_registration';
}
}
Thank you for your help, I tried to erase the cache but it doesn't work...
You need to add the user class as an argument to your service definition so that it will be called in the __construct method.
utilisateurs_utilisateurs.registration.form.type:
class: Utilisateurs\UtilisateursBundle\Form\Type\RegistrationFormType
arguments:
- %fos_user.model.user.class%
tags:
- { name: form.type, alias: utilisateurs_utilisateurs_registration }

Add roles field to FOSUserBundle group form

When activating group( base on its documentation) in FOSUserBundle, the group roles are not embedded on edit and update form!I already override GroupFormType and GroupController but I can't pass roles from controller to form class.
my question is how can I add roles to form to let administrator change or assign role to groups?
Solving my problem by adding the role field to override GroupController
public function editAction(Request $request, $groupName)
{
...
/** #var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$formFactory = $this->get('fos_user.group.form.factory');
$form = $formFactory->createForm();
$form->add('roles', 'choice', array(
'choices' => $this->getExistingRoles(),
'data' => $group->getRoles(),
'label' => 'Roles',
'expanded' => true,
'multiple' => true,
'mapped' => true,
));
...
}
public function getExistingRoles()
{
$roleHierarchy = $this->container->getParameter('security.role_hierarchy.roles');
$roles = array_keys($roleHierarchy);
foreach ($roles as $role) {
$theRoles[$role] = $role;
}
return $theRoles;
}
For my part I decided to inerite the GroupFormType class. Here is inherited class :
namespace UserBundle\Form;
use FOS\UserBundle\Form\Type\GroupFormType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
class GroupType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$permissions = array(
'Utilisateur' => 'ROLE_USER',
'Administrateur' => 'ROLE_ADMIN'
);
$builder
->add('name', null, array('label' => 'form.group_name', 'translation_domain' => 'FOSUserBundle'))
->add('role', ChoiceType::class, array(
'label' => 'Rôle',
'choices' => $permissions,
'multiple' => true,
'expanded' => true
))
;
}
public function getParent()
{
return GroupFormType::class;
}
}
Don't forget to precise your new class in the config.yml
fos_user:
group:
form:
type: UserBundle\Form\GroupType

Symfony2 + SonataAdminBundle: Error on updating User's roles (many-to-many)

Entities:
User:
class User implements AdvancedUserInterface, \Serializable
{
...
/**
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
* #ORM\JoinTable(name="users_roles")
*
*/
private $roles;
...
}
Role:
class Role implements RoleInterface
{
...
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
public function __toString()
{
return $this->getName();
}
...
}
Admin classes:
UsersAdmin:
<?php
namespace Lan\ConsoleBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Knp\Menu\ItemInterface as MenuItemInterface;
class UsersAdmin extends Admin
{
protected function configureShowField(ShowMapper $showMapper)
{
$showMapper
->add('id', null, array('label' => 'ID'))
->add('username', null, array('label' => 'Name'))
->add('password', null, array('label' => 'Password'))
->add('email', null, array('label' => 'Mail'))
->add('is_active', null, array('label' => 'Active', 'required' => false))
->add('roles');
}
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->with('General')
->add('username', null, array('label' => 'Name'))
->add('password', null, array('label' => 'Password'))
->add('email', null, array('label' => 'Mail'))
->add('is_active', 'checkbox', array('label' => 'Active', 'required' => false))
->end()
->with('Roles')
->add('roles', 'sonata_type_model',array('expanded' => true, 'compound' => true, 'multiple' => true))
->end();
}
}
RolesAdmin:
<?php
namespace Lan\ConsoleBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Knp\Menu\ItemInterface as MenuItemInterface;
class RolesAdmin extends Admin
{
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('name', null, array('label' => 'Заголовок'))
->add('role', null, array('label' => 'Роль'));
}
}
Screenshot:
http://img577.imageshack.us/img577/3565/jyte.png
After updating User i get this error message:
FatalErrorException: Error: Call to a member function add() on a
non-object in
\vendor\sonata-project\doctrine-orm-admin-bundle\Sonata\DoctrineORMAdminBundle\Model\ModelManager.php line 560
I think this error occurs because the object instead of 'Role' value is passed to the function Role-> __toString (). How can I solve this problem?
Try something arround this code:
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('name', null, array('label' => 'Заголовок'))
->add('Product' , 'entity' , array(
'class' => 'LanConsoleBundle:Role' ,
'property' => 'name' ,
'expanded' => true ,
'multiple' => true , ))
}

Resources