Drupal 8 get image filename or URI - drupal-8

While I would like to find the best way to accomplish this, I'm presently desperate to find any way to accomplish this. I'm trying to get an image filename or URI value inside of a preprocess view function in my theme file but keep hitting roadblocks. The closest I've manage to get is with $node->field_photo->entity; and when I dump it I can see the "filename" or "uri" value that I want to get, see screenshot below.
Here is what I've tried thus far:
#1) I tried using $node->field_photo->entity->getFileUri();
Problem: Returns Error: Call to a member function getFileUri() on null
#2) I tried the following:
$referenceItem = $node->get('field_photo')->referencedEntities();
$referenceItem[0]->values['filename']
Problem: returns null
#3) I tried the following:
$referencedEntity = $node
->get('field_photo')
->first()
->get('entity')
->getTarget()
->getValue();
Problem: Returns Error: Call to a member function get() on null for " ->get('entity')"
#4) I tried getting the image from "target_id" but neither one of the two classes are found:
use Drupal\media\Entity\Media;
use Drupal\media_entity\Entity\Media;
Problem: Neither class is found
#5) I tried the following:
// $id = some node ID
// $field = field name for entity reference field
$node = Node::load($id);
/** #var \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $referenceItem */
$referenceItem = $node->get($field)->first();
/** #var \Drupal\Core\Entity\Plugin\DataType\EntityReference $entityReference */
$entityReference = $referenceItem->get('entity');
/** #var \Drupal\Core\Entity\Plugin\DataType\EntityAdapter $entityAdapter */
$entityAdapter = $entityReference->getTarget();
/** #var \Drupal\Core\Entity\EntityInterface $referencedEntity */
$referencedEntity = $entityAdapter->getValue();
Problem: Error: Call to a member function get() on null for " ->get('entity')"
#6) I also tried the following:
$node->field_photo->entity->field_media_image->entity->getFileUri();
Problem: Returns error Call to a member function getFileUri() on null

Related

Doctrine prevent error on OneToOne association where record doesn't exist in database

Problem
I'm trying to create a OneToOne association in a Laravel app using Doctrine. When trying to access the association I'm getting this error.
Entity of type 'Status' for IDs clientId(1) was not found
Versions:
Doctrine: 2.7.5
Laravel: 7.30.4
Code:
Client Class
<?php
namespace App\Client;
use App\Person\Person;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Client
* #package App\Client
*
* #ORM\Entity(repositoryClass="ClientRepository")
* #ORM\Table(name="client")
*/
class Client extends Person
{
/**
* #var Status
*
* #ORM\OneToOne(targetEntity="Status", mappedBy="client")
* #ORM\JoinColumn(name="id", referencedColumnName="client_id", nullable=true)
*/
protected $status;
/**
* #return Status
*/
public function getStatus()
{
return $this->status;
}
}
Status Class:
<?php
namespace App\Client\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Status
* #package App\Client\Entity
*
* #ORM\Entity(readOnly=true)
* #ORM\Table(name="status_view")
*/
class Status
{
/**
* #var int
*
* #ORM\Id()
* #ORM\Column(name="client_id", type="integer")
*/
protected $clientId;
/**
* #var \App\Client\Client
*
* #ORM\OneToOne(targetEntity="App\Client\Client", inversedBy="staus")
* #ORM\JoinColumn(name="client_id", referencedColumnName="id", nullable=true)
*/
protected $client;
/**
* #var string
*
* #ORM\Column(name="status", type="string")
*/
protected $status;
/**
* #return string
*/
public function getStatus()
{
return $this->status;
}
}
Calling Code
$client->getStatus()->getStatus()
What I've tried/Answers I've looked at
Entity of type 'AppBundle\Entity\User' for IDs id(155) was not found - I'm not using a Doctrine filter, nor DQL.
https://stackoverflow.com/a/49416542/9530790 - This works, with a few tweaks, by swallowing up the exception, but it feels more like a hack when the docs say nullable should work.
https://stackoverflow.com/a/21887344/9530790 - This states nullable should work but it doesn't.
https://stackoverflow.com/a/15744449/9530790 - Same question different ans. States that Doctrine doesn't support zero-to-one associations, but nullable I believe should be what solves that, but for my problem it's not working. Also there's no link to the docs stating where Zero to one is not supported.
I believe that adding fetch="EAGER" should fix the null issue as elsewhere in our app that works, but when I add that I get an different Doctrine error spl_object_hash() expects parameter 1 to be object, null given, which again has to do with the association not existing.
"Well why aren't you experiencing the above error with your other associations". Great question! After a deep underwater excursion into the Doctrine code, I believe the reason is because those associations are nested and for some reason (I'm not sure why), when nested, the spl_object_hash function, in class UnitOfWork is not called.
Additional Notes:
This is what the object looks like when calling $client->getStatus(), before it errors on the next ->getStatus() call.
DoctrineProxies\__CG__\App\Client\Entity\Status {#2011
+__isInitialized__: false
#clientId: 4
#client: null
#status: null
…2
}
You can see it's a Client Proxy object that's created not a 'true' object, this is why it errors (with Entity of type 'Status' for IDs clientId(1) was not found) when not using fetch="EAGER", since eager loads a true object. See here
This code below in the Proxy object is the what causes the above error. Which is why I can't do a try catch in the parent ('true' Client class), since it errors before calling the parent.
/**
* {#inheritDoc}
*/
public function getStatus()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getStatus', []);
return parent::getStatus();
}
Question:
Why is nullable=true not working as expected, and what should/can I do to make it work?

Embed a Collection of Forms Error: Could not determine access type for property

I am trying to embed collection of Tag forms to Service form, according to this tutorial. Tag and Service entities have many-to-many relationship.
Form is rendering correctly. But when I submit form, I get
Could not determine access type for property "tagList"
error. I don't understand why new Tag object is not added to the Service class by calling the addTag() method.
ServiceType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', TextType::class, array(
'label' => 'Title'
))
;
$builder->add('tagList', CollectionType::class, array(
'entry_type' => TagType::class,
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false
)));
}
Service class
{
....
/**
* #ORM\ManyToMany(targetEntity="Tag", mappedBy="serviceList",cascade={"persist"})
*/
private $tagList;
/**
* #return ArrayCollection
*/
public function getTagList()
{
return $this->tagList;
}
/**
* #param Tag $tag
* #return Service
*/
public function addTag(Tag $tag)
{
if ($this->tagList->contains($tag) == false) {
$this->tagList->add($tag);
$tag->addService($this);
}
}
/**
* #param Tag $tag
* #return Service
*/
public function removeTag(Tag $tag)
{
if ($this->tagList->contains($tag)) {
$this->tagList->removeElement($tag);
$tag->removeService($this);
}
return $this;
}
}
Tag class
{
/**
* #ORM\ManyToMany(targetEntity="Service", inversedBy="tagList")
* #ORM\JoinTable(name="tags_services")
*/
private $serviceList;
/**
* #param Service $service
* #return Tag
*/
public function addService(Service $service)
{
if ($this->serviceList->contains($service) == false) {
$this->serviceList->add($service);
$service->addTag($this);
}
return $this;
}
/**
* #param Service $service
* #return Tag
*/
public function removeService(Service $service)
{
if ($this->serviceList->contains($service)) {
$this->serviceList->removeElement($service);
$service->removeTag($this);
}
return $this;
}
}
ServiceController
public function newAction(Request $request)
{
$service = new Service();
$form = $this->createForm('AppBundle\Form\ServiceType', $service);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($service);
$em->flush();
return $this->redirectToRoute('service_show', array('id' => $service->getId()));
}
return $this->render('AppBundle:Service:new.html.twig', array(
'service' => $service,
'form' => $form->createView(),
));
}
Could you please try to implement code from this URL?
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#owning-and-inverse-side-on-a-manytomany-association
First, please try to change mapped/inverse sides, and remove $service->addTag($this); from Tag::addService method.
Short version:
I just ran into this problem and solved it by adding a setter for the affected property:
Could not determine access type for property "tagList"
public function setTagList(Array $tagList)
{
$this->tagList = $tagList;
}
Long version:
The error message is signaling that Symfony is trying to modify the object's state, but cannot figure out how to actually make the change due to the way its class is set up.
Taking a look at Symfony's internals, we can see that Symfony gives you 5 chances to give it access and picks the best one in this order from top to bottom:
A setter method named setProperty() with one argument:
This is the first thing Symfony checks for and is the most explicit way to achieve this. As far as I'm aware this is the best practice:
class Entity {
protected $tagList;
//...
public function getTagList()
{
return $this->tagList;
}
//...
}
A combined getter and setter in one method with one argument:
It's important to realize that this method will also be accessed by Symfony in order to get the object's state. Since those method calls don't include an argument, the argument in this method must be optional.
class Entity {
protected $tagList;
//...
public function tagList($tags = null)
{
if($reps){
$this->tagList = $tags;
} else {
return $this->tagList;
}
}
//...
}
The affected property being declared as public:
class Entity {
public $tagList;
//... other properties here
}
A __set magic method:
This will affect all properties rather than just the one you intended.
class Entity {
public $tagList;
//...
public function __set($name, $value){
$this->$name = $value;
}
//...
}
A __call magic method (in some cases):
I wasn't able to confirm this, but the internal code suggests this is possible when magic is enabled on PropertyAccessor's construction.
Only using one of the above strategies is required.
Maybe the problem is that Symfony can't access that property?
If you look at where that exception is thrown (writeProperty method in the PropertyAccessor class) it says it can be thrown:
If the property does not exist or is not public.
In the tutorial you mentioned it has property $tags, and method addTag. I'm just guessing here, but maybe there's a convention where it tries to call a method names add($singularForm) and this is failing for you because the property is tagList and the method is addTag.
I'm not 100% sure, but you could try debugging by setting a stop point in that Symfony method to see why it's being thrown.
Maybe you forgot in the __construct() of Service class and Tag class to initialize $tagList and $serviceList like this ?
$this->tagList = new ArrayCollection();
$this->serviceList = new ArrayCollection();
This seems like an error with your constructor. Try this :
public function __construct()
{
$this-> tagList = new \Doctrine\Common\Collections\ArrayCollection();
}
It's a long shot, but looking at your annotations I think the problem might be related to your manyToMany relationship. Try to change the owning side and inverse side (Swap the relationship) unless you specifically need to update from both ends (In that case I think the only solution is to add the objects manually or use oneToMany relationships).
Changes made only to the inverse side of an association are ignored.
Make sure to update both sides of a bidirectional association (or at
least the owning side, from Doctrine’s point of view)
This is a problem related to Doctrine I have suffered before, see:
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/unitofwork-associations.html
Based on Symfony 3.3.10
I actually faced this problem many and many times, finally once i discovered where this problem was coming from, depending on the name you give to your entity property it can happen that the adder and the remover for your collection property aren't exactly what you are expecting.
Example: Your entity properity name is "foo" and you would expect the adder to be called "addFoo" and remover "removeFoo", but then all of a sudden the "Could not determine access type for property" appear.
So you start going into fear searching for w/e problems in your code, instead you just have to look this file inside Symfony core files:
vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php
Inside this file there's a method called findAdderAndRemover.
Go there with your debugger and you will eventually find out that symfony searches for weird name for your adder/remover, they may actually end with "um" or "on" or "us" depending on the language (human language) you used to name them. Since i'm Italian this happen quite often.
Watch out for that, since the fix may be as simple as changing the name used for your add/remove method inside your entity to make them match with what Symfony core is looking for.
This happens to me when i use bin/console doctrine:generate:entities to create the methods automatically for me
If you are using symfony, and use EntityRepository instead of CollectionType, make sure you use the 'multiple' => true, on your form build, otherwise the input will be for one entity and not for many, therefore it will call the setTagList instead of using the methods addTagList and removeTagList.

Doctrine2: How to use array of objects in array type?

Doctrine2 has a built-in type 'array' that I find useful for my project. It perfectly works with arrays of scalar types. But now I want to use an array of objects. Something like this:
/**
* #ORM\Entity
*/
class MyEntity {
/**
* #var MyEntityParameter[] array of MyEntityParameter instances
*
* #ORM\Column(name="parameters", type="array", nullable=true)
*
*/
private $parameters;
}
Where MyEntityParameter is a class that can be serialized. I also use it in the Symfony's Form Builder.
My plan works perfectly, except that when the field in the MyEntityParameter instance gets changed, Doctrine doesn't detect it and thus doesn't update the record. If I delete or add array elements, Doctrine detects that. I realize that this happens because class instance object id doesn't change when I change its field, but then how can I make it so that Doctrine detects this change?
I found a working solution for me. I don't think it's that elegant, but in case if there are no good ways to solve this problem it can work for me and for others.
First of all, I decided not to keep objects in the array, but instead keep arrays. I, however, still want to use MyEntityParameter class in the Symfony's form builder. In this case, the idea is to disable mapping for our field:
In the form builder we do the following:
// Acme/Bundle/DemoBundle/Form/Type/MyEntityType.php
// ...
class MyEntityType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('parameters', 'collection', array(
'mapped' => false, // do not map this field
'type' => new MyEntityParameterType(),
// ... other options ...
));
}
}
In the child type (MyEntityParameterType) we set 'data_class' to MyEntityParameter (I don't show the code, as it's not related to the problem).
Now all we need is to manually fill and process the data for this not-mapped field.
In the controller:
public function editAction($id, Request $request)
{
// ...
// $object is an instance of MyEntity
$form = $this->createForm(new MyEntityType(), $object);
$parameters = $object->getParameters();
if ($parameters) {
foreach ($parameters as $key => $parameter)
{
$form->get('parameters')->add($key, new MyEntityParameterType(),
array(
// here I assume that the constructor of MyEntityParameter
// accepts the field data in an array format
'data' => new MyEntityParameter($parameter),
)
);
}
}
if ($request->isMethod('POST')) {
$form->submit($request);
$parameters = array();
foreach ($form->get('parameters')->all() as $parameter) {
// here first getData() gives MyEntityParameter instance
// and the second getData() is just a method of MyEntityParameter
// that returns all the fields in an array format
$parameters[] = $parameter->getData()->getData();
}
$object->setParameters($parameters);
// if the parameters were changed in the form,
// this change will be detected by UnitOfWork
}
// ...
}
I remember coming across this issue before, and a workaround that worked for me was to set a new object so Doctrine would recognise the entity property has been modified, then set the object that has the changes you want persisted.
$parameters = $entity->getParameters();
$parameters->foo = "bar";
$entity->setParameters(new MyEntityParameter());
$entity->setParameters($parameters);
$em->persist($entity);
If it's an array of MyEntityParameter instances then the following code might work.
$parameters = $entity->getParameters();
$parameters[3]->foo = "bar"; // Just an example
$entity->setParameters(array(new MyEntityParameter()));
$entity->setParameters($parameters);
$em->persist($entity);

Doctrine2 __constructor not called when using $em->find(); ? How to load entity properly?

I'm learning doctrine2, and having a problem how to call constructor automatically.
For example, in my entity I have
/**
* #Entity
*/
class User{
....
public function __construct() {
exit('in');
}
}
and when I get the object this way:
$userObj = $em->find('User', 1);
I do get that object from database, but constructor is never called.
I want to put some common things in constructor, like validation rules, or even to put sample code from the doctrine documentation like
$this->comments = new ArrayCollection();
This ofcourse works when I create new object in code for creating a user like
$user = new User(); //now constructor works just fine
Now, what is the "proper" way of getting the entity? I doubt I have to call constructor manually each time I user $em->find() with $user0bj->__construct(); ? This would kinda sucks then... Or I should use something other then ->find() to get single entity properly?
I know I can user #PrePersist, and I am using it to actually do validation checks etc.
I guess that I'm probably missing something here, or I'm trying to use constructor in a poor way. Thanks for any explanations and guides!
I'm pretty certain that find or similar isn't expected to call the constructor...
You need to hook into the #PostLoad event.
Why would you want to call the constuctor of already persisted entity? When you need to validate it you should have done the validation or initializations before you have persisted it. So When you call a already persisted entity there is no point to validate it.
The right place to put validation and other initializations is the constructor method of entity.
Eg.
/**
* #Entity
*/
class User{
protected $name;
public function __construct($name) {
if (isset($name)) {
//** validate the name here */
$this->name=$name;
} else {
throw new Exception("no user name set!");
}
}
}
According to the doctrine2 documentation Doctrine2 never calls __construct() method of entities.
http://www.doctrine-project.org/docs/orm/2.0/en/reference/architecture.html?highlight=construct
doctrine uses reflection to instantiate your object without invoking your constructor.
Since PHP 5.4 , you can use reflection to instanciate a class without
calling the constructor using
ReflectionClass::newInstanceWithoutConstructor
the instantiator of doctrine use it like :
private function buildFactory(string $className) : callable
{
$reflectionClass = $this->getReflectionClass($className);
if ($this->isInstantiableViaReflection($reflectionClass)) {
return [$reflectionClass, 'newInstanceWithoutConstructor'];
}
$serializedString = sprintf(
'%s:%d:"%s":0:{}',
is_subclass_of($className, Serializable::class) ? self::SERIALIZATION_FORMAT_USE_UNSERIALIZER : self::SERIALIZATION_FORMAT_AVOID_UNSERIALIZER,
strlen($className),
$className
);
$this->checkIfUnSerializationIsSupported($reflectionClass, $serializedString);
return static function () use ($serializedString) {
return unserialize($serializedString);
};
}
Doctrine ORM will "rewrite" your class, it generate a new class that implement \Doctrine\ORM\Proxy\Proxy
And it rewrite the construct method:
/**
* #param \Closure $initializer
* #param \Closure $cloner
*/
public function __construct($initializer = null, $cloner = null)
{
$this->__initializer__ = $initializer;
$this->__cloner__ = $cloner;
}
You can see it inside the cache folder ${CACHE}/doctrine/orm/Proxies.
You will need both #ORM\HasLifecycleCallbacks on the class + #ORM\PostLoad on a specific function of your choice.
Beware! If you put it on the constructor it will override loaded database data!
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table(name="dossier")
* #ORM\Entity()
* #ORM\HasLifecycleCallbacks
*/
class Dossier
{
// ...
/**
* The normal constructor stays as usual
*/
public function __construct()
{
$this->takenActions = new ArrayCollection();
$this->classifications = new ArrayCollection();
$this->dossierProblems = new ArrayCollection();
$this->internalNotes = new ArrayCollection();
}
/**
* Triggers after the entity has been loaded in the EntityManager (e.g. Doctrine's ->find() etc...)
* The constructor does not get called. Some variables still need a default value
* Must be in combination with "ORM\HasLifecycleCallbacks" on the class
*
* #ORM\PostLoad
*/
public function postLoadCallback(): void
{
// Only put a default value when it has none yet
if (!$this->dossierProblems)
$this->dossierProblems = new ArrayCollection();
if (!$this->internalNotes)
$this->internalNotes = new ArrayCollection();
}
// ...
}

Doctrine 2 Can't Seem to Remove Many to Many Relationships

I have the following setup "Many Users can have Many Projects (Collaborators)"
/**
* #Entity #HasLifeCycleCallbacks
* #Table(name="projects")
*/
class Project implements \Zend_Acl_Resource_Interface {
/**
* #ManyToMany(targetEntity="User", mappedBy="projects")
* #OrderBy({"displayName" = "ASC", "username" = "ASC"})
*/
protected $collaborators;
..
}
/**
* #Entity
* #Table(name="users")
*/
class User implements \Zend_Acl_Role_Interface {
/**
* #ManyToMany(targetEntity="Project", inversedBy="collaborators")
*/
protected $projects;
...
}
I tried to remove a collaborator using the following
$user = Application_DAO_User::findById($this->_getParam('userid'));
$proj = Application_DAO_Project::getProjectById($this->_getParam('id'));
Application_DAO_Project::removeCollaborator($proj, $user); // <---
// Application_DAO_User
public static function findById($id) {
return self::getStaticEm()->find('Application\Models\User', $id);
}
// Application_DAO_Project
public static function getProjectById($id) {
return self::getStaticEm()->find('Application\Models\Project', $id);
}
public static function removeCollaborator(Project $proj, User $collaborator) { // <---
$proj->getCollaborators()->remove($collaborator);
$collaborator->getProjects()->remove($proj);
self::getStaticEm()->flush();
}
And there isn't any errors but the database stays the same ...
This may be well over due but was just experiencing the same problem myself... According to the doctrine 2 documents, the function ArrayCollection->remove($i) is for removing by array index.
What you are after is:
getCollaborators()->removeElement($collaborator);
I went round in circles trying to figure this out until I realised that for this to work:
getCollaborators()->removeElement($collaborator);
$collaborator would have to be the actual object from the collaborators ArrayCollection. That is, if you pass in a new Collaborator object with the same parameters it won't remove it. That's because ArrayCollection uses array_search to look for the object you want to remove.
Hope that saves someone else a few hours...