Search code examples
phpmysqlsymfonypostman

Symfony - Expected value of type '' got "string" instead


I am trying to pass id from one country table to user table but I can't' pass this error..

Expected value of type "ProjectBundle\Base\Entity\Country" for association field "ProjectBundle\Base\Entity\User#$country", got "string" instead.

My User entity class

class User extends BaseUser
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 * @Groups({"user_data"})
 */
protected $id;

/**
 * @ORM\ManyToOne(targetEntity="Country")
 * @JoinColumn(name="country_id", referencedColumnName="id")
 */
private $country;


/**
 * @return mixed
 */
public function getCountry()
{
    return $this->country;
}

/**
 * @param mixed $country
 */
public function setCountry($country)
{
    $this->country = $country;
}

My User service

 public function registerUser($country)
{
    $user = new User();
    $user->setCountry($country);

    $this->em->persist($user);
    $this->em->flush();


    return $user;
}

My User controller

 public function registerUserAction()
{
    $this->requirePostParams(['country_id']);

    $country = $this->data['country_id'];

    $user =  $this->get('member')->registerUser($country);

    return $this->success($user);
}

So I am passing country_id value via postman and I get this error.


Solution

  • The Problem is that

    $user->setCountry()
    

    expects an instance of your Country Entity. But you try to call it with the ID of an country. Doctrine does not fetch the Entity from the given ID.

    To fix this you have two options:

    1. fetch the country with the ID

      in your user Service:

      public function registerUser($countryId)
      { 
          $country = $this->countryRepository->findById($countryId);
          $user = new User();
          $user->setCountry($country);
      
          $this->em->persist($user);
          $this->em->flush();
      
          return $user;
      }
      

      You have to add the CountryRepository as a dependency in your service.

    2. add the countryID column as a attribute to your UserEntity

      in your User entity:

      /**
      * @var int
      *
      * @ORM\Column(name="country_id", type="integer", nullable=true)
      */
      protected $countryId;
      
      /**
       * @return int
       */
      public function getCountryId()
      {
          return $this->countryId;
      }
      
      /**
       * @param int $countryId
       */
      public function setCountryId($countryId)
      {
          $this->countryId = $countryId;
      }
      

      in your user Service:

      public function registerUser($countryId)
      { 
          $user = new User();
          $user->setCountryId($countryId);
      
          $this->em->persist($user);
          $this->em->flush();
      
          return $user;
      }