我想能夠使用實體驗證約束來驗證,如果外鍵book_id是有效的,請參閱以下內容:Symfony的實體驗證驗證外鍵存在
book.php中
/**
* Book
*
* @ORM\Table("book")
* @ORM\Entity
* @ORM\Entity(repositoryClass="AppBundle\Repository\BookRepository")
*/
class Book
{
/**
* @var integer
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
* @ORM\Column(name="name", type="string")
* @Assert\Length(
* max = 250,
* maxMessage = "Name cannot be longer than {{ limit }} characters",
* groups={"create","update"}
*)
*/
private $name;
/**
* @ORM\OneToOne(targetEntity="Loan", mappedBy="book", fetch="LAZY")
*/
protected $loan;
}
貸款.PHP
/**
* Loan
*
* @ORM\Table("loan")
* @ORM\Entity
* @ORM\Entity(repositoryClass="AppBundle\Repository\LoanRepository")
*/
class Loan
{
/**
* @var integer
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var integer
* @ORM\Column(name="book_id", type="integer")
*/
protected $book_id;
/**
* @var string
* @ORM\Column(name="name", type="string")
* @Assert\Length(
* max = 500,
* maxMessage = "Person cannot be longer than {{ limit }} characters",
* groups={"create","update"}
*)
*/
private $person;
/**
* @ORM\OneToOne(targetEntity="Book", inversedBy="loan")
* @ORM\JoinColumn(name="book_id", referencedColumnName="id")
*/
protected $book;
}
這裏是我當前如何驗證貸款實體
$loan = new Loan();
$loan->setPerson($person);
$loan->setBookId($id);
/** @var ConstraintViolation $error */
foreach ($this->get('validator')->validate($loan,null,['create'])->getIterator() as $index => $error) {
$errorMessages[] = $error->getMessage();
}
我想也許我可以這樣添加自定義驗證的貸款實體:
/**
* @Assert\IsTrue(message = "The book does not exist")
* @return bool
*/
public function isBookLegal(BookRepository $bookRepository)
{
return !$bookRepository->fetchById($this->book_id);
}
但我結束了與後續的例外:
Type error: Too few arguments to function
AppBundle\Entity\Loan::isBookLegal(), 0 passed and exactly 1 expected
首先將foreach的第一個參數賦值給一個變量,然後在foreach中使用它,這只是討厭的。其次,當你打電話給你的'isBookLegal'時,你可以不帶參數地調用它 - 這就是爲什麼你會得到這個消息。 – Edwin
但是,如何通過驗證觸發isBookLegal?換句話說,我該如何驗證將參數傳遞給此函數? – Freid001