No Entity Manager in Custom Class and ContextErrorException - symfony

I'm trying to create custom Form in Sonata-Admin and I want to get data from database to choices box.
When I'm trying to get data via getEntityManager() I got error
No entity manager defined for class \Admin\AdminBundle\Entity\Category
I tried to add entity manager to first argument in service.yml [code below]
services:
sonata.admin.category:
class: Admin\AdminBundle\Admin\Category
tags:
- {name: sonata.admin, manager_type: orm, group: "Content", label: "Kategoria"}
arguments:
- #doctrine.orm.default_entity_manager
- Admin\AdminBundle\Entity\Category
- ~
calls:
- [ setTranslationDomain, [AdminAdminBundle]]
After i Add default entity manager I'm having error:
ContextErrorException in RoutesCache.php line 47:
Warning: md5() expects parameter 1 to be string, object given
I'm also adding my ConfigureFormFields() function:
protected function configureFormFields(FormMapper $formMapper){
$em = $this->modelManager->getEntityManager('\Admin\AdminBundle\Entity\Category');
$query = $em->createQueryBuilder('c')
->select('c')
->from('AdminBundle:Category', 'c')
->where('c.parent IS NOT NULL')
->orderBy('c.root, c.lft', 'ASC');
$formMapper
->add ('name', 'text', array('label' => 'Nazwa Kategorii'))
->add ('alias', 'text', array('label' => 'Alias'))
->add('parent_id', 'sonata_type_model', array(
'required' => true,
'query' => $query
));
Can somebody help me fix that error ?
Thanks for answers,
best regards !

You get error because add manager in wrong place.
First argument of admin service should be set as
the admin service’s code (defaults to the service’s name).
Admin class pharse this string and build some logic based on. You put there manager so you get error.
If you want to add something to your admin class you can simply add as fourth argument (or fifth, sixth ....) like:
services:
sonata.admin.category:
class: Admin\AdminBundle\Admin\Category
tags:
- {name: sonata.admin, manager_type: orm, group: "Content", label: "Kategoria"}
arguments:
- ~
- Admin\AdminBundle\Entity\Category
- ~
- #doctrine.orm.default_entity_manager
calls:
- [ setTranslationDomain, [AdminAdminBundle]]
And then in your admin class you have to update override constructor, like :
public function __construct($code, $class, $baseControllerName, $yourManager)
{
parent::_construct($code, $class, $baseControllerName);
$this->yourManager = $yourManager
}

Related

How to add item_permission on delete action in easyadmin?

I use EasyadminBundle for the Backend of a Symfony application.
Two type of users have access to the back-end and I'd like to keep the right to delete to a small number of persons granted with ROLE_ADMIN.
I'd like to use item_permission parameter as for the other actions (such as show or list) :
Lieu:
class: App\Entity\Lieu
list:
item_permission: ROLE_ENCADRANT
delete:
item_permission: ROLE_ADMIN
But it's not working and I can still delete user when I'm logged with ROLE_ENCADRANT. Is there another solution ?
I currently accomplish it with:
Lieu:
class: App\Entity\Lieu
list:
item_permission: ROLE_ENCADRANT
action: ['-delete']
help: "the delete button is accessible in <b>Edit</b> view"
form:
item_permission: ROLE_ADMIN
I'm just looking for a 100% configuration solution, more elegant than mine.
Take a look at adding an action in the docs. The action can be tied to a route, which allows specifying what role may perform the action. The downside is that the list view button is present regardless of role. You can add a flash message to advise the user whether they have permission.
Here's an example from a project. Not quite what you're looking for but may get you started:
easyadmin.yaml:
Admin:
class: App\Entity\Admin
disabled_actions: ['new', 'edit']
list:
actions:
-
name: 'admin_enabler'
type: 'route'
label: 'Enable/Disable'
controller:
/**
* #Route("/enabler", name = "admin_enabler")
*/
public function enabler(Request $request)
{
$em = $this->getDoctrine()->getManager();
$id = $request->query->get('id');
$admin = $em->getRepository(Admin::class)->find($id);
$enabled = $admin->isEnabled();
if (!$admin->isActivator() && !$admin->hasRole('ROLE_SUPER_ADMIN')) {
$admin->setEnabled(!$enabled);
$em->persist($admin);
$em->flush();
} else {
$this->addFlash('danger', $admin->getFullName() . ' cannot be disabled');
}
return $this->redirectToRoute('easyadmin', array(
'action' => 'list',
'entity' => $request->query->get('entity'),
));
}

Symfony3 EasyAdmin Custom non-auto ID column

I have setup a database table in which the ID values will be created by my application and NOT the database.
/**
* #ORM\Column(type="bigint", precision=14, options={"unsigned":true})
* #ORM\Id()
* #ORM\GeneratedValue("NONE")
*/
private $id;
This works fine in symfony, but I am trying to edit the table using EasyAdmin and EasyAdmin simply omits the 'id' column.
I found out that I can manipulate edit/new views configuration from EasyAdmin documentation.
Now I have the following configuration (the mentioned id is for Product):
easy_admin:
entities:
- AppBundle\Entity\Category
- AppBundle\Entity\Product
Question:
1- How do I setup the YAML configuration so id field will also appear? I found out that this partially works:
easy_admin:
entities:
Product:
class: AppBundle\Entity\Product
form:
fields:
- 'id'
But this shows only 'id', is there a way to tell that I want 'id' in addition to all the other fields so I don't have to list them manually?
2- My original config is using a list of entities with dash (-) in the YAML file. I am a YAML noob, when I make a Product: key I am not able to use the dash anymore, is there a way to keep using dash list and just make an exception for 'Product? For example the code below does NOT work, it says it is not valid YAML.
easy_admin:
entities:
- AppBundle\Entity\Category
Product:
class: AppBundle\Entity\Product
form:
fields:
- 'id'
Well, for now I solved the problem like this and abandoned the dash notation altogether:
easy_admin:
entities:
Category:
class: AppBundle\Entity\Category
Store:
class: AppBundle\Entity\Store
Product:
class: AppBundle\Entity\Product
edit:
fields:
- { property: 'stores', label: 'Stores', type_options: { by_reference: false } }
form:
fields:
- 'id'
- 'name'
- 'category'
- 'stores'
Q1: you can use customization based on entity controllers. See doc here: https://symfony.com/doc/master/bundles/EasyAdminBundle/book/complex-dynamic-backends.html#customization-based-on-entity-controllers
app/config/config.yml
User:
class: AppBundle\Entity\User
controller: UserBundle\Controller\Admin\UserController
And then in your UserController you can have something like this. Pay attention you must use the exact entity name in method signature: createUserEntityFormBuilder in your case
protected function createUserEntityFormBuilder($entity, $view)
{
$form = parent::createEntityFormBuilder($entity, $view);
$form->add('Anyfield', TextType::class, [
'label' => 'id' // feel free to add other options
]); // add fieldlike you would do in FormType
$form->remove('anyField');
return $form;
}
Q2: I can't answer to this question for sure. I do not use "Dashed" notation.
Maybe take a look at doc here: https://symfony.com/doc/current/components/yaml/yaml_format.html#collections

Symfony 2.7: The 127.0.0.1 page isn’t working 127.0.0.1 is currently unable to handle this request

The form is displayed with different roles and permissions except that the server can not Symfony 2.7 processed the request (I do not know why !!).
The 127.0.0.1 page isn’t working
127.0.0.1 is currently unable to handle this request. HTTP ERROR 500
even though I used the command:
php app/console cache:clear --env=prod
here are my formType:
Class RoleType{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('groups', 'entity',array(
'class' => 'GroupsBundle:Roles',
'property' => 'name_role',
'required' => false,
'placeholder' => 'Choisir le role du votre groupe'
)
)
->add('permissions_role','entity',array(
'class' => 'GroupsBundle:Permissions',
'property' => 'name_permissions',
'multiple' => true,
'expanded' => true,
'required' => true
)
)
;
}
}
Class GroupType{
class GroupsType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('image', new ImagesType())
->add('name_groups','text',array('required' => true, 'attr' => array('placeholder' => 'Nom du groupe')))
->add('role', new RolesType())
;
}
}
Here the code of controller:
public function createAction(Request $request)
{
$entity = new Groups();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
//$em->getReference('MemberShipManagement\GroupsBundle\Entity\Groups',$entity.getId());
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('groups_show', array('id' => $entity->getId())));
}
return $this->render('GroupsBundle:Groups:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
thank you to solve the problem
*Dev.log
[2016-07-12 00:23:49] doctrine.DEBUG: SELECT p0_.id_per AS id_per0, p0_.nom_permisions AS nom_permisions1 FROM permissions p0_ [] []
[2016-07-12 00:23:49] doctrine.DEBUG: SELECT r0_.id AS id0, r0_.nom_roles AS nom_roles1 FROM roles r0_ WHERE r0_.id IN (?) [["0"]] []
[2016-07-12 01:51:58] php.DEBUG: fsockopen(): unable to connect to 127.0.0.1:8000 (Connection refused) {"type":2,"file":"/home/syrine01/Desktop/Project_Console/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Command/ServerCommand.php","line":59,"l
evel":28928} []
WARNING - Translation not found.
Context: {"id":"Image","domain":"messages","locale":"fr"}
WARNING - Translation not found.
Context: {"id":"File","domain":"messages","locale":"fr"}
WARNING - Translation not found.
Context: {"id":"Name groups","domain":"messages","locale":"fr"}
WARNING - Translation not found.
Context: {"id":"Nom du groupe","domain":"messages","locale":"fr"}
WARNING - Translation not found.
Context: {"id":"Role","domain":"messages","locale":"fr"}
WARNING - Translation not found.
Context: {"id":"Groups","domain":"messages","locale":"fr"}
WARNING - Translation not found.
Context: {"id":"Choisir le role du votre groupe","domain":"messages","locale":"fr"}
WARNING - Translation not found.
Context: {"id":"Permissions role","domain":"messages","locale":"fr"}
WARNING - Translation not found.
INFO - Matched route "groups_new".
Context: {"route_parameters":{"_controller":"MemberShipManagement\\GroupsBundle\\Controller\\GroupsController::newAction","_route":"groups_new"},"request_uri":"http://127.0.0.1:8000/groups/new"}
DEPRECATED - The Symfony\Component\Form\Extension\Csrf\CsrfProvider\CsrfProviderAdapter class is deprecated since version 2.4 and will be removed in version 3.0. Use the Symfony\Component\Security\Csrf\CsrfTokenManager class instead. +
INFO - Populated the TokenStorage with an anonymous Token.
DEPRECATED - MemberShipManagement\GroupsBundle\Form\GroupsType: The FormTypeInterface::setDefaultOptions() method is deprecated since version 2.7 and will be removed in 3.0. Use configureOptions() instead. This method will be added to the FormTypeInterface with Symfony 3.0. +
DEPRECATED - MemberShipManagement\GroupsBundle\Form\ImagesType: The FormTypeInterface::setDefaultOptions() method is deprecated since version 2.7 and will be removed in 3.0. Use configureOptions() instead. This method will be added to the FormTypeInterface with Symfony 3.0. +
DEPRECATED - MemberShipManagement\GroupsBundle\Form\RolesType: The FormTypeInterface::setDefaultOptions() method is deprecated since version 2.7 and will be removed in 3.0. Use configureOptions() instead. This method will be added to the FormTypeInterface with Symfony 3.0. +
DEPRECATED - The "property" option is deprecated since version 2.7 and will be removed in 3.0. Use "choice_label" instead.
I have not done the translation of my website
the Config databse is:
doctrine:
dbal:
driver: pdo_mysql
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
unix_socket: /tmp/mysql.sock
//parameters
parameters:
database_host: 127.0.0.1
database_port: null
database_name: symfony
database_user: root
database_password: root
mailer_transport: smtp
mailer_host: 127.0.0.1
mailer_user: null
mailer_password: null
with this command I find my server encountered a problem
sudo php app/console server:start -vvv
[2016-07-12 06:02:10] php.DEBUG: fsockopen(): unable to connect to
127.0.0.1:8000 (Connection refused) {"type":2,"file":"/home/Cros/Desktop/Project_Console/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Command/ServerCommand.php","line":59,"level":28928}
It is shown in the dev.log at the 3rd line:
[2016-07-12 01:51:58] php.DEBUG: fsockopen(): unable to connect to 127.0.0.1:8000 (Connection refused) ...
Try to check your database informations and have a look to your parameters or config file in app/config directory to see if all database parameters are set correctly.
Currently, your database_port is set to 8000, maybe your must leave the value to null.
Anyway try to check your database informations (database_host, database_port, database_user, database_password...). It may be the problem

there is no default value + symfony2 + crud

sf 2.8.4 with sylius 0.17
i had generated a controller and routes with generate:doctrine:crud
i can list all datas, but on show and edit, always got this error:
Controller "St\AppBundle\Controller\TranslationDomainController::showAction()" requires that you provide a value for the "$translationdomain" argument (because there is no default value or because there is a non optional argument after this one).
here the show action
public function showAction(TranslationDomain $translationdomain)
{
$deleteForm = $this->createDeleteForm($translationdomain->getId(), 'administration_translations_domain_delete');
return $this->render('StAppBundle:TranslationDomain:show.html.twig', array(
'translationdomain' => $translationdomain,
'delete_form' => $deleteForm->createView(), ));
}
and the route
administration_translations_domain_show:
pattern: /{id}/show
defaults: { _controller: "StAppBundle:TranslationDomain:show", id : 1 }
requirements:
id : \d+
_method : get
You are using a param converter
http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html
You have to disable the auto-conversion of type-hinted method arguments feature by setting the auto_convert flag to false.
Look at:
# app/config/config.yml
sensio_framework_extra:
request:
converters: true
auto_convert: false
Change to:
sensio_framework_extra:
request:
converters: true
auto_convert: true
At the end you should always request for an object identifier. It's safe and semantic correct. You want to 'show/edit/update/delete' concrete entity.
If you really wants to have a default show for your set of entities create route like a '/show/default' and use this route with 'show/choose default' link.

how to include an entity join in sonata bundle admin list view

related code:
in services.yml
sonata.admin.domain:
class: MyBundle\AdminBundle\Admin\MyAdmin
tags:
- { name: sonata.admin, manager_type: orm, group: "Domains", label: "Domains" }
arguments:
- ~
- MyBundle\ServiceBundle\Entity\MyEntity
- ~
calls:
- [ setTranslationDomain, [MyOtherBundle]]
in my admin controller:
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('domain')
->add('user.email')
->add('_action', 'actions', array(
'actions' => array(
'show' => array())));
}
which errors in:
Notice: Undefined index: user
to describe the problem further, i have a table that has a user_id column, and i want to be able to include the users email address (using fos user bundle) in that same list with that table. i've tried custom query with no luck also. thanks ahead of time
here is official documentation about list view definition :
http://sonata-project.org/bundles/admin/master/doc/reference/action_list.html
and
http://sonata-project.org/bundles/doctrine-orm-admin/master/doc/reference/list_field_definition.html
if you have a user_id within you entity, i guess your entity is an override of fosUserBundle, right ?
so normally you directly access from the list field definition like this :
->add('user.email') // user is you entity object
otherwise if it s a standalone entity with a user_id, you might have a relationship between this entity and the entity which owns your fosuserbundle object, and like in the above list field definition , you should normally access the object email.

Resources