question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

PUT a property with object relation to null

See original GitHub issue

So I have an Person entity and a Country entity. The Person entity has this property

    /**
     * @var Country
     *
     * @ORM\ManyToOne(targetEntity="Country")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="countryOfNationalityId", referencedColumnName="id", nullable=true)
     * })
     * @Groups({"get_method", "put_method"})
     */
    private $countryOfNationality; 

The issue is that I can not make it NULL after it has been set already. So if I use PUT with {“countryOfNationality” : null}, I get this error: Expected argument of type \"App\\Entity\\Country\", \"NULL\" given at property path \"countryOfNationality\"."

Is there anyway to nullify a property with relation? Thanks.

Issue Analytics

  • State:open
  • Created 5 years ago
  • Comments:21 (7 by maintainers)

github_iconTop GitHub Comments

2reactions
Airone2000commented, Feb 28, 2019

public function setCountryOfNationality(Country $countryOfNationality): self

becomes …

public function setCountryOfNationality(?Country $countryOfNationality): self

and it should work.

0reactions
wow-appscommented, Jul 30, 2020

@osamaarefm , @mrtnzagustin cc. @teohhanhui

I solved this issue via EventSubscriber, check it out:

I has some entities with property cover which includes other entity. For those entities I’ve implement interface and add event subscriber:

<?php

// src/Entity/HasCoverInterface.php

namespace Api\Entity;

interface HasCoverInterface
{
    public function getCover(): ?ImageFile;

    public function setCover(?ImageFile $cover): self;
}
<?php

// src/EventSubscriber/RemoveCoverSubscriber.php

namespace Api\EventSubscriber;

use ApiPlatform\Core\EventListener\EventPriorities;
use Api\Entity\HasCoverInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class RemoveCoverSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::VIEW => ['setValueToNull', EventPriorities::PRE_WRITE],
        ];
    }

    public function setValueToNull(ViewEvent $event)
    {
        $request = $event->getRequest();
        if (!in_array($request->getMethod(), [Request::METHOD_PUT])) {
            return;
        }

        $class = $request->attributes->get('_api_resource_class');
        if (!in_array(HasCoverInterface::class, class_implements($class))) {
            return;
        }

        if (empty($request->getContent())) {
            return;
        }

        $content = json_decode($request->getContent(), true);
        if (!array_key_exists('cover', $content) || !is_null($content['cover'])) {
            return;
        }

        /** @var HasCoverInterface $object */
        $object = $event->getControllerResult();
        $object->setCover(null);

        $event->setControllerResult($object);
    }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Add property to object when it's not null - javascript
This works because Object.assign will skip over null parameters. If you are sure that the property value is not going to be "falsy", ......
Read more >
How to set nullable/optional property of database object to ...
1 Answer 1 · Retrieve the object of type Foo with Id 65 from the database · Modify NullableProperty to set it to...
Read more >
Set all Values in an Object to Null using JavaScript | bobbyhadz
To set all values in an object to null , pass the object to the Object.keys() method to get an array of the...
Read more >
Working with nullable reference types - EF Core
DbContext and DbSet ... Another strategy is to use non-nullable auto-properties, but to initialize them to null, using the null-forgiving operator ...
Read more >
Object.create() - JavaScript - MDN Web Docs
me.name = 'Matthew'; // "name" is a property set on "me", but not on "person" ... Thrown if proto is neither null nor...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found