I am spinning my wheel to render an object in a twig template. I have 3 entities user >> customer >> account each one mapped to the next with a bi-directionnal one-to-many relationship. I want to fetch all accounts for a specific customer using this controller
//...
public function showAction($customerref)
{
$customer=$this->getDoctrine()->getRepository('AcmeCustomerBundle:Customer')
->find($customerref);
$accounts = $customer->getAccounts();
return $this->render('mytemplate.html.twig', array('accounts'=>$accounts));
}
I try to retrieve the information related to the "accounts" object in twig using
{% for account in accounts %}
{{ account.id }}
{{ account.number}}
{% endfor %}
I get the error "Notice: undefined index:customer". I cannot make sense of this error. When does the "customer" index need to be defined? This is what I have when I dump the "accounts" object.
PersistentCollection {#1061 ▼
-snapshot: []
-owner: Customer {#1060 ▼
-id: 11
-name: "nameofthecustomer"
+user: User {#947 ▼
-id: 1
-username: "tom"
#customers: PersistentCollection {#968 ▶}
}
#accounts: PersistentCollection {#1061}
}
-association: array:15 [ …15]
-em: EntityManager {#151 …10}
-backRefFieldName: "customer"
-typeClass: ClassMetadata {#948 …}
-isDirty: false
-initialized: false
-coll: ArrayCollection {#1062 ▼
-_elements: []
}
}
Could anyone give me some guidance on why I get this error? I have used a similar code many times (e.g. to display all customer for one specific user and it worked perfectly well)? Thanks.
I left some typos indeed (i just corrected them). I happen to have found the solution. I had issues with the way my entities were mapped. This is where I found some useful tips http://obtao.com/blog/symfony2-issues-you-do-not-understand/
Related
This question already has answers here:
What is the difference between fetch="EAGER" and fetch="LAZY" in doctrine
(2 answers)
Closed 1 year ago.
I recently started using Symfony and I don't understand why statuses(ManyToMany) don't give any output on a findAll query.
I need there the last/current value that was entered in the database.
App\Entity\Service {#752 ▼
-id: 5
-name: "Helpdesk"
-description: null
-url: null
-serviceGroup: App\Entity\ServiceGroup {#728 ▼
-id: 2
-name: "Webserver 2"
-description: null
-services: Doctrine\ORM\PersistentCollection {#729 ▶}
-order_id: 2
}
-order_id: 3
-statuses: Doctrine\ORM\PersistentCollection {#753 ▼
-snapshot: []
-owner: App\Entity\Service {#752}
-association: array:16 [ …16]
-em: Doctrine\ORM\EntityManager {#383 …11}
-backRefFieldName: "services"
-typeClass: Doctrine\ORM\Mapping\ClassMetadata {#675 …}
-isDirty: false
#collection: Doctrine\Common\Collections\ArrayCollection {#754 ▶}
#initialized: false
}
}
//Edit
for easyadmin I have already added a function in the Entity/Service.php, can't I just use this for the twig tempalte?
public function getLastStatus()
{
return $this->getStatuses()->last();
}
You should try to modify your class Service in your property "statuses" inside #ORM\ManyToMany() by adding : fetch="EAGER" (it should give the all object and not just the proxy).
Or you can also create a function findStatuses(Service $service) in your ServiceRepository that get all the statuses using the query builder. You will find exemples of it in your ServiceRepository.
I have ManyToOne relationship between Posts and User:
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User\User")
*/
private $author;
After I obtain response form my endpoint which looks like this:
array:2 [
"message" => "OK"
"data" => array:1 [
0 => Post {#6077
-id: 1
-title: "sda"
-teaser: "asdj"
-content: "asd"
-createdDateTime: DateTime #1517078058 {#6075
date: 2018-01-27 18:34:18.0 UTC (+00:00)
}
-deletedDateTime: null
-author: User {#6294
+__isInitialized__: false
-id: 1
-firstName: null
-lastName: null
-email: null
-activationCode: null
-isActive: null
-createdDateTime: null
-deletedDateTime: null
…2
}
-statusId: false
}
]
]
I'm trying to serialize it to JSON. Perviously(Symfony 3) there was a problem with Circular References which I managed to solve but this is little bit different.
I keep getting 500 response with exception:
NotNormalizableValueException
An unexpected value could not be normalized: NULL
If I remove relationship between entities it's fine so it's clearly the problem.
It's treating related object as something that cannot be normalized. For some reason. Not sure why it's happening. Didn't find anything in the docs on that.
Anything I missed here?
I think I have solved my problem. I went to:
/vendor/symfony/serializer/Serializer.php
After little investigation I was able to find out that normalizer is falling over PHP RESOURCE.
It turned out that I had one field of VARBINARY type in my User table. According to doctrine documentation that type is translated to PHP resource.
Conclusion: Symfony serialization does not have any problems with serializing entity and related child entities. It is simply not capable of normalizing resource type of data.
I think that's something worth remembering.
I would need some more info to help you. What serializer are you using, the Symfony one? How are you loading the serializer? Whatever it may be, the error is clear: the normalizer of the serializer you are using does not know what to do when finds a null field. My guess is that you are loading just one normalizer (of the around 5 available) to your serializer as it is shown in the official Symfony Serializer docs.
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
For the simplicity of the problem I am not using role_hierarchy on my security.yml.
I have a logged user. If I do this on my controller:
dump($this->get('security.token_storage')->getToken()->getUser()->getRoles());
This is what I get:
array:3 [▼
0 => "ROLE_SUPER_ADMIN"
1 => "ROLE_ADMIN"
2 => "ROLE_USER"
]
But then if I ask for isGranted, I just get true on 'ROLE_USER', and false with all the rest:
dump($this->get('security.authorization_checker')->isGranted('ROLE_USER'));
dump($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN'));
dump($this->get('security.authorization_checker')->isGranted('ROLE_SUPER_ADMIN'));
gives me:
true
false
false
I am using FOSUserBundle and my user extends their BaseUser (which on turn implements UserInterface) and I am not touching any method of it on my User entity.
Can you spot the problem? Is that I can not use the security.checker with FOSUSerBundle?
UPDATE:
If I dump($this->getUser()) this is what I get:
Usuario {#2290 ▼
#id: 3
#username: "u1"
#usernameCanonical: "u1"
#email: "u1"
#emailCanonical: "u1"
#enabled: true
#salt: "8wqvgv5t24g0ssck44gw4008c04g8sg"
#password: "zfDmozi78wrglXx3SUaCiz7490o4ZzKYEukcbdlCQ5FAWpA4jgLFQT6BXNbo3tzTyhdPDOCC/h4ZDs32SKlGEw=="
#plainPassword: null
#lastLogin: DateTime {#2288 ▶}
#confirmationToken: null
#passwordRequestedAt: null
#groups: null
#locked: false
#expired: false
#expiresAt: null
#roles: array:2 [▼
0 => "ROLE_SUPER_ADMIN"
1 => "ROLE_ADMIN"
]
#credentialsExpired: false
#credentialsExpireAt: null
}
As you can see, FSOS just add the 'ROLE_USER' in getRoles() method since it is not present in the actual array of Roles.
Logging out and back in again will resolve the issue.
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.