PHP Warning: class_parents(): object or string expected - typo3

I am using TYPO3 and I have in my extension my own model, controller and repository file. In the Backend I created a record which worked without any issues. But when I try to load the FE I get the following error in DataMapper.php
PHP Warning: class_parents(): object or string expected in /home/app/vendor/typo3/cms/typo3/sysext/extbase/Classes/Persistence/Generic/Mapper/DataMapper.php line 284
00284: if ($propertyData['type'] === 'DateTime' || in_array('DateTime', class_parents($propertyData['type']))) {
I debugged it and found out that $propertyName contains the correct property name 'street' but $propertyData is an empty array.
My model looks like this:
<?php
namespace Snowflake\Htwapartmentexchange\Domain\Model;
use Snowflake\ApiRepository\Helpers\DateTime;
use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;
class Apartment extends AbstractEntity
{
protected $apartmentType = '';
protected $street = '';
protected $zip = '';
protected $city = '';
protected $price = '';
protected $countRooms = '';
protected $area = '';
protected $availableDate = '';
protected $description = '';
protected $firstname = '';
protected $lastname = '';
protected $mobile = '';
protected $mail = '';
protected $pictures = null;
/**
* Apartment constructor.
* #param $apartmentType
* #param $street
* #param $zip
* #param $city
* #param $price
* #param $countRooms
* #param $area
* #param $availableDate
* #param $description
* #param $firstname
* #param $lastname
* #param $mobile
* #param $mail
* #param $pictures
*/
public function __construct($apartmentType, $street, $zip, $city, $price, $countRooms, $area, $availableDate, $description, $firstname, $lastname, $mobile, $mail, $pictures)
{
$this->apartmentType = $apartmentType;
$this->street = $street;
$this->zip = $zip;
$this->city = $city;
$this->price = $price;
$this->countRooms = $countRooms;
$this->area = $area;
$this->availableDate = $availableDate;
$this->description = $description;
$this->firstname = $firstname;
$this->lastname = $lastname;
$this->mobile = $mobile;
$this->mail = $mail;
$this->pictures = $pictures;
}
/**
* #return mixed
*/
public function getApartmentType()
{
return $this->apartmentType;
}
/**
* #param mixed $apartmentType
*/
public function setApartmentType($apartmentType)
{
$this->apartmentType = $apartmentType;
}
/**
* #return mixed
*/
public function getStreet()
{
return $this->street;
}
/**
* #param mixed $street
*/
public function setStreet($street)
{
$this->street = $street;
}
/**
* #return mixed
*/
public function getZip()
{
return $this->zip;
}
/**
* #param mixed $zip
*/
public function setZip($zip)
{
$this->zip = $zip;
}
/**
* #return mixed
*/
public function getCity()
{
return $this->city;
}
/**
* #param mixed $city
*/
public function setCity($city)
{
$this->city = $city;
}
/**
* #return mixed
*/
public function getPrice()
{
return $this->price;
}
/**
* #param mixed $price
*/
public function setPrice($price)
{
$this->price = $price;
}
/**
* #return mixed
*/
public function getCountRooms()
{
return $this->countRooms;
}
/**
* #param mixed $countRooms
*/
public function setCountRooms($countRooms)
{
$this->countRooms = $countRooms;
}
/**
* #return mixed
*/
public function getArea()
{
return $this->area;
}
/**
* #param mixed $area
*/
public function setArea($area)
{
$this->area = $area;
}
/**
* #return DateTime
*/
public function getAvailableDate()
{
return $this->availableDate;
}
/**
* #param DateTime $availableDate
*/
public function setAvailableDate($availableDate)
{
$this->availableDate = $availableDate;
}
/**
* #return mixed
*/
public function getDescription()
{
return $this->description;
}
/**
* #param mixed $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* #return mixed
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* #param mixed $firstname
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
}
/**
* #return mixed
*/
public function getLastname()
{
return $this->lastname;
}
/**
* #param mixed $lastname
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
}
/**
* #return mixed
*/
public function getMobile()
{
return $this->mobile;
}
/**
* #param mixed $mobile
*/
public function setMobile($mobile)
{
$this->mobile = $mobile;
}
/**
* #return mixed
*/
public function getMail()
{
return $this->mail;
}
/**
* #param mixed $mail
*/
public function setMail($mail)
{
$this->mail = $mail;
}
/**
* #return mixed
*/
public function getPictures()
{
return $this->pictures;
}
/**
* #param mixed $pictures
*/
public function setPictures($pictures)
{
$this->pictures = $pictures;
}
}
Can you tell me what is wrong?

Found a solution.
The problem was that I didn't use PHPDoc comments on my model.
So I changed every property from this
protected $street = '';
to this
/**
* #var string
*/
protected $street = '';

class_parents(new $propertyData['type'])))
you should use new keyword for object
in line 284...

Related

magento2.3.7 Cart additional_options parameter lost after switching user

After opening and exiting the reserved shopping cart, I switch between different accounts in the browser, and the additional_options field in the quote_item_options table is lost, resulting in incomplete display of product specifications
How to modify the core file to add the additional_options field
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Checkout\Model;
use Magento\Customer\Api\Data\CustomerInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Quote\Api\Data\CartInterface;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\QuoteIdMaskFactory;
use Psr\Log\LoggerInterface;
/**
* Represents the session data for the checkout process
*
* #api
* #SuppressWarnings(PHPMD.CouplingBetweenObjects)
* #SuppressWarnings(PHPMD.CookieAndSessionMisuse)
* #SuppressWarnings(PHPMD.TooManyFields)
* #since 100.0.2
*/
class Session extends \Magento\Framework\Session\SessionManager
{
const CHECKOUT_STATE_BEGIN = 'begin';
/**
* Quote instance
*
* #var Quote
*/
protected $_quote;
/**
* Customer Data Object
*
* #var CustomerInterface|null
*/
protected $_customer;
/**
* Whether load only active quote
*
* #var bool
*/
protected $_loadInactive = false;
/**
* A flag to track when the quote is being loaded and attached to the session object.
*
* Used in trigger_recollect infinite loop detection.
*
* #var bool
*/
private $isLoading = false;
/**
* Loaded order instance
*
* #var \Magento\Sales\Model\Order
*/
protected $_order;
/**
* #var \Magento\Sales\Model\OrderFactory
*/
protected $_orderFactory;
/**
* #var \Magento\Customer\Model\Session
*/
protected $_customerSession;
/**
* #var \Magento\Quote\Api\CartRepositoryInterface
*/
protected $quoteRepository;
/**
* #var \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress
*/
protected $_remoteAddress;
/**
* #var \Magento\Framework\Event\ManagerInterface
*/
protected $_eventManager;
/**
* #var \Magento\Store\Model\StoreManagerInterface
*/
protected $_storeManager;
/**
* #var \Magento\Customer\Api\CustomerRepositoryInterface
*/
protected $customerRepository;
/**
* #param QuoteIdMaskFactory
*/
protected $quoteIdMaskFactory;
/**
* #param bool
*/
protected $isQuoteMasked;
/**
* #var \Magento\Quote\Model\QuoteFactory
*/
protected $quoteFactory;
/**
* #var LoggerInterface|null
*/
private $logger;
/**
* #param \Magento\Framework\App\Request\Http $request
* #param \Magento\Framework\Session\SidResolverInterface $sidResolver
* #param \Magento\Framework\Session\Config\ConfigInterface $sessionConfig
* #param \Magento\Framework\Session\SaveHandlerInterface $saveHandler
* #param \Magento\Framework\Session\ValidatorInterface $validator
* #param \Magento\Framework\Session\StorageInterface $storage
* #param \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager
* #param \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
* #param \Magento\Framework\App\State $appState
* #param \Magento\Sales\Model\OrderFactory $orderFactory
* #param \Magento\Customer\Model\Session $customerSession
* #param \Magento\Quote\Api\CartRepositoryInterface $quoteRepository
* #param \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $remoteAddress
* #param \Magento\Framework\Event\ManagerInterface $eventManager
* #param \Magento\Store\Model\StoreManagerInterface $storeManager
* #param \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
* #param QuoteIdMaskFactory $quoteIdMaskFactory
* #param \Magento\Quote\Model\QuoteFactory $quoteFactory
* #param LoggerInterface|null $logger
* #throws \Magento\Framework\Exception\SessionException
* #SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
\Magento\Framework\App\Request\Http $request,
\Magento\Framework\Session\SidResolverInterface $sidResolver,
\Magento\Framework\Session\Config\ConfigInterface $sessionConfig,
\Magento\Framework\Session\SaveHandlerInterface $saveHandler,
\Magento\Framework\Session\ValidatorInterface $validator,
\Magento\Framework\Session\StorageInterface $storage,
\Magento\Framework\Stdlib\CookieManagerInterface $cookieManager,
\Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory,
\Magento\Framework\App\State $appState,
\Magento\Sales\Model\OrderFactory $orderFactory,
\Magento\Customer\Model\Session $customerSession,
\Magento\Quote\Api\CartRepositoryInterface $quoteRepository,
\Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $remoteAddress,
\Magento\Framework\Event\ManagerInterface $eventManager,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
QuoteIdMaskFactory $quoteIdMaskFactory,
\Magento\Quote\Model\QuoteFactory $quoteFactory,
LoggerInterface $logger = null
) {
$this->_orderFactory = $orderFactory;
$this->_customerSession = $customerSession;
$this->quoteRepository = $quoteRepository;
$this->_remoteAddress = $remoteAddress;
$this->_eventManager = $eventManager;
$this->_storeManager = $storeManager;
$this->customerRepository = $customerRepository;
$this->quoteIdMaskFactory = $quoteIdMaskFactory;
$this->quoteFactory = $quoteFactory;
parent::__construct(
$request,
$sidResolver,
$sessionConfig,
$saveHandler,
$validator,
$storage,
$cookieManager,
$cookieMetadataFactory,
$appState
);
$this->logger = $logger ?: ObjectManager::getInstance()
->get(LoggerInterface::class);
}
/**
* Set customer data.
*
* #param CustomerInterface|null $customer
* #return \Magento\Checkout\Model\Session
* #codeCoverageIgnore
*/
public function setCustomerData($customer)
{
$this->_customer = $customer;
return $this;
}
/**
* Check whether current session has quote
*
* #return bool
* #codeCoverageIgnore
*/
public function hasQuote()
{
return isset($this->_quote);
}
/**
* Set quote to be loaded even if inactive
*
* #param bool $load
* #return $this
* #codeCoverageIgnore
*/
public function setLoadInactive($load = true)
{
$this->_loadInactive = $load;
return $this;
}
/**
* Get checkout quote instance by current session
*
* #return Quote
* #throws \Magento\Framework\Exception\LocalizedException
* #throws NoSuchEntityException
* #SuppressWarnings(PHPMD.CyclomaticComplexity)
* #SuppressWarnings(PHPMD.NPathComplexity)
*/
public function getQuote()
{
$this->_eventManager->dispatch('custom_quote_process', ['checkout_session' => $this]);
if ($this->_quote === null) {
if ($this->isLoading) {
throw new \LogicException("Infinite loop detected, review the trace for the looping path");
}
$this->isLoading = true;
$quote = $this->quoteFactory->create();
if ($this->getQuoteId()) {
try {
if ($this->_loadInactive) {
$quote = $this->quoteRepository->get($this->getQuoteId());
} else {
$quote = $this->quoteRepository->getActive($this->getQuoteId());
}
$customerId = $this->_customer
? $this->_customer->getId()
: $this->_customerSession->getCustomerId();
if ($quote->getData('customer_id') && (int)$quote->getData('customer_id') !== (int)$customerId) {
$quote = $this->quoteFactory->create();
$this->setQuoteId(null);
}
/**
* If current currency code of quote is not equal current currency code of store,
* need recalculate totals of quote. It is possible if customer use currency switcher or
* store switcher.
*/
if ($quote->getQuoteCurrencyCode() != $this->_storeManager->getStore()->getCurrentCurrencyCode()) {
$quote->setStore($this->_storeManager->getStore());
$this->quoteRepository->save($quote->collectTotals());
/*
* We mast to create new quote object, because collectTotals()
* can to create links with other objects.
*/
$quote = $this->quoteRepository->get($this->getQuoteId());
}
if ($quote->getTotalsCollectedFlag() === false) {
$quote->collectTotals();
}
} catch (NoSuchEntityException $e) {
$this->setQuoteId(null);
}
}
if (!$this->getQuoteId()) {
if ($this->_customerSession->isLoggedIn() || $this->_customer) {
$quoteByCustomer = $this->getQuoteByCustomer();
if ($quoteByCustomer !== null) {
$this->setQuoteId($quoteByCustomer->getId());
$quote = $quoteByCustomer;
}
} else {
$quote->setIsCheckoutCart(true);
$quote->setCustomerIsGuest(1);
$this->_eventManager->dispatch('checkout_quote_init', ['quote' => $quote]);
}
}
if ($this->_customer) {
$quote->setCustomer($this->_customer);
} elseif ($this->_customerSession->isLoggedIn()) {
$quote->setCustomer($this->customerRepository->getById($this->_customerSession->getCustomerId()));
}
$quote->setStore($this->_storeManager->getStore());
$this->_quote = $quote;
$this->isLoading = false;
}
if (!$this->isQuoteMasked() && !$this->_customerSession->isLoggedIn() && $this->getQuoteId()) {
$quoteId = $this->getQuoteId();
/** #var $quoteIdMask \Magento\Quote\Model\QuoteIdMask */
$quoteIdMask = $this->quoteIdMaskFactory->create()->load($quoteId, 'quote_id');
if ($quoteIdMask->getMaskedId() === null) {
$quoteIdMask->setQuoteId($quoteId)->save();
}
$this->setIsQuoteMasked(true);
}
$remoteAddress = $this->_remoteAddress->getRemoteAddress();
if ($remoteAddress) {
$this->_quote->setRemoteIp($remoteAddress);
$xForwardIp = $this->request->getServer('HTTP_X_FORWARDED_FOR');
$this->_quote->setXForwardedFor($xForwardIp);
}
return $this->_quote;
}
/**
* Return the quote's key
*
* #return string
* #codeCoverageIgnore
*/
protected function _getQuoteIdKey()
{
return 'quote_id_' . $this->_storeManager->getStore()->getWebsiteId();
}
/**
* Set the current session's quote id
*
* #param int $quoteId
* #return void
* #codeCoverageIgnore
*/
public function setQuoteId($quoteId)
{
$this->storage->setData($this->_getQuoteIdKey(), $quoteId);
}
/**
* Return the current quote's ID
*
* #return int
* #codeCoverageIgnore
*/
public function getQuoteId()
{
return $this->getData($this->_getQuoteIdKey());
}
/**
* Load data for customer quote and merge with current quote
*
* #return $this
*/
public function loadCustomerQuote()
{
if (!$this->_customerSession->getCustomerId()) {
return $this;
}
$this->_eventManager->dispatch('load_customer_quote_before', ['checkout_session' => $this]);
try {
$customerQuote = $this->quoteRepository->getForCustomer($this->_customerSession->getCustomerId());
} catch (NoSuchEntityException $e) {
$customerQuote = $this->quoteFactory->create();
}
$customerQuote->setStoreId($this->_storeManager->getStore()->getId());
if ($customerQuote->getId() && $this->getQuoteId() != $customerQuote->getId()) {
if ($this->getQuoteId()) {
$quote = $this->getQuote();
$quote->setCustomerIsGuest(0);
$this->quoteRepository->save(
$customerQuote->merge($quote)->collectTotals()
);
$newQuote = $this->quoteRepository->get($customerQuote->getId());
$this->quoteRepository->save(
$newQuote->collectTotals()
);
$customerQuote = $newQuote;
}
$this->setQuoteId($customerQuote->getId());
if ($this->_quote) {
$this->quoteRepository->delete($this->_quote);
}
$this->_quote = $customerQuote;
} else {
$this->getQuote()->getBillingAddress();
$this->getQuote()->getShippingAddress();
$this->getQuote()->setCustomer($this->_customerSession->getCustomerDataObject())
->setCustomerIsGuest(0)
->setTotalsCollectedFlag(false)
->collectTotals();
$this->quoteRepository->save($this->getQuote());
}
return $this;
}
/**
* Associate data to a specified step of the checkout process
*
* #param string $step
* #param array|string $data
* #param bool|string|null $value
* #return $this
*/
public function setStepData($step, $data, $value = null)
{
$steps = $this->getSteps();
if ($value === null) {
if (is_array($data)) {
$steps[$step] = $data;
}
} else {
if (!isset($steps[$step])) {
$steps[$step] = [];
}
if (is_string($data)) {
$steps[$step][$data] = $value;
}
}
$this->setSteps($steps);
return $this;
}
/**
* Return the data associated to a specified step
*
* #param string|null $step
* #param string|null $data
* #return array|string|bool
*/
public function getStepData($step = null, $data = null)
{
$steps = $this->getSteps();
if ($step === null) {
return $steps;
}
if (!isset($steps[$step])) {
return false;
}
if ($data === null) {
return $steps[$step];
}
if (!is_string($data) || !isset($steps[$step][$data])) {
return false;
}
return $steps[$step][$data];
}
/**
* Destroy/end a session and unset all data associated with it
*
* #return $this
*/
public function clearQuote()
{
$this->_eventManager->dispatch('checkout_quote_destroy', ['quote' => $this->getQuote()]);
$this->_quote = null;
$this->setQuoteId(null);
$this->setLastSuccessQuoteId(null);
return $this;
}
/**
* Unset all session data and quote
*
* #return $this
*/
public function clearStorage()
{
parent::clearStorage();
$this->_quote = null;
return $this;
}
/**
* Clear misc checkout parameters
*
* #return void
*/
public function clearHelperData()
{
$this->setRedirectUrl(null)->setLastOrderId(null)->setLastRealOrderId(null)->setAdditionalMessages(null);
}
/**
* Revert the state of the checkout to the beginning
*
* #return $this
* #codeCoverageIgnore
*/
public function resetCheckout()
{
$this->setCheckoutState(self::CHECKOUT_STATE_BEGIN);
return $this;
}
/**
* Replace the quote in the session with a specified object
*
* #param Quote $quote
* #return $this
*/
public function replaceQuote($quote)
{
$this->_quote = $quote;
$this->setQuoteId($quote->getId());
return $this;
}
/**
* Get order instance based on last order ID
*
* #return \Magento\Sales\Model\Order
*/
public function getLastRealOrder()
{
$orderId = $this->getLastRealOrderId();
if ($this->_order !== null && $orderId == $this->_order->getIncrementId()) {
return $this->_order;
}
$this->_order = $this->_orderFactory->create();
if ($orderId) {
$this->_order->loadByIncrementId($orderId);
}
return $this->_order;
}
/**
* Restore last active quote
*
* #return bool True if quote restored successfully, false otherwise
*/
public function restoreQuote()
{
/** #var \Magento\Sales\Model\Order $order */
$order = $this->getLastRealOrder();
if ($order->getId()) {
try {
$quote = $this->quoteRepository->get($order->getQuoteId());
$quote->setIsActive(1)->setReservedOrderId(null);
$this->quoteRepository->save($quote);
$this->replaceQuote($quote)->unsLastRealOrderId();
$this->_eventManager->dispatch('restore_quote', ['order' => $order, 'quote' => $quote]);
return true;
} catch (NoSuchEntityException $e) {
$this->logger->critical($e);
}
}
return false;
}
/**
* Flag whether or not the quote uses a masked quote id
*
* #param bool $isQuoteMasked
* #return void
* #codeCoverageIgnore
*/
protected function setIsQuoteMasked($isQuoteMasked)
{
$this->isQuoteMasked = $isQuoteMasked;
}
/**
* Return if the quote has a masked quote id
*
* #return bool|null
* #codeCoverageIgnore
*/
protected function isQuoteMasked()
{
return $this->isQuoteMasked;
}
/**
* Returns quote for customer if there is any
*/
private function getQuoteByCustomer(): ?CartInterface
{
$customerId = $this->_customer
? $this->_customer->getId()
: $this->_customerSession->getCustomerId();
try {
$quote = $this->quoteRepository->getActiveForCustomer($customerId);
} catch (NoSuchEntityException $e) {
$quote = null;
}
return $quote;
}
}

Display an image in a form type of some model SYLIUS

i have created a new model which have an attribute "image" , i have generated the CRUD using the SyliusResourcesBundle ,
what i'm trying to achieve is to display an image in the edit form type , how can i do that ? thx in advance
my form type :
<?php
namespace AppBundle\Form\Type;
use Sylius\Bundle\ResourceBundle\Form\Type\DefaultResourceType as BaseSliderType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class SliderType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->add('lib','text'
);$builder->add('title','text'
);
$builder->add('description','text'
);
$builder->add('file',FileType::class
);
}
public function getName()
{
return 'app_slider';
}
}
?>
my model:
<?php
namespace AppBundle\Entity;
use Sylius\Component\Resource\Model\ResourceInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* Slider
*/
class Slider implements ResourceInterface, \Serializable
{
/**
* #var int
*/
private $id;
/**
* #var string
*/
private $lib;
/**
* #var string
*/
private $title;
/**
* #var string
*/
private $description;
private $file;
/**
* #return mixed
*/
public function getFile()
{
return $this->file;
}
/**
* #param mixed $file
*/
public function setFile($file)
{
$this->file = $file;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set lib
*
* #param string $lib
* #return Slider
*/
public function setLib($lib)
{
$this->lib = $lib;
return $this;
}
/**
* Get lib
*
* #return string
*/
public function getLib()
{
return $this->lib;
}
/**
* Set title
*
* #param string $title
* #return Slider
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* #param string $description
* #return Slider
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* #var string
*/
private $condition;
/**
* Set condition
*
* #param string $condition
* #return Slider
*/
public function setCondition($condition)
{
$this->condition = $condition;
return $this;
}
/**
* Get condition
*
* #return string
*/
public function getCondition()
{
return $this->condition;
}
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->lib,
$this->title,
$this->description,
// see section on salt below
// $this->salt,
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->lib,
$this->title,
$this->description,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
}

Updating an Entity with a file field

I'm trying to update my Recipe Entity that has a file field, in particular an image.
THIS IS MY ENTITY
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Article
*
* #ORM\Table()
* #ORM\HasLifecycleCallbacks
* #ORM\Entity
*/
class Article
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="titolo", type="string", length=255)
*/
private $titolo;
/**
* #var string
*
* #ORM\Column(name="autore", type="string", length=255)
*/
private $autore;
/**
* #var string
*
* #ORM\Column(name="testo", type="text")
*/
private $testo;
/**
* #var string
*
* #ORM\Column(name="categoria", type="string", length=100)
*/
private $categoria;
/**
* #var string $image
* #Assert\File( maxSize = "1024k", mimeTypesMessage = "Perfavore inserisci un'immagine valida!")
* #ORM\Column(name="image", type="string", length=255, nullable=true)
*/
private $image;
/**
* #var date
*
* #ORM\Column(name="data", type="date")
*/
public $data;
/**
* #var integer
*
* #ORM\Column(name="rate", type="integer",nullable=true)
*/
private $rate;
/**
* #ORM\OneToMany(targetEntity="CommentoArticle", mappedBy="article")
*/
protected $commentoarticle;
public function __construct()
{
$this->commentoarticle = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set titolo
*
* #param string $titolo
*
* #return Article
*/
public function setTitolo($titolo)
{
$this->titolo = $titolo;
return $this;
}
/**
* Get titolo
*
* #return string
*/
public function getTitolo()
{
return $this->titolo;
}
/**
* Set autore
*
* #param string $autore
*
* #return Article
*/
public function setAutore($autore)
{
$this->autore = $autore;
return $this;
}
/**
* Get autore
*
* #return string
*/
public function getAutore()
{
return $this->autore;
}
/**
* Set testo
*
* #param string $testo
*
* #return Article
*/
public function setTesto($testo)
{
$this->testo = $testo;
return $this;
}
/**
* Get testo
*
* #return string
*/
public function getTesto()
{
return $this->testo;
}
/**
* Set image
*
* #param string $image
*/
public function setImage($image)
{
$this->image = $image;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
public function getFullImagePath() {
return null === $this->image ? null : $this->getUploadRootDir(). $this->image;
}
protected function getUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
return $this->getTmpUploadRootDir().$this->getId()."/";
}
protected function getTmpUploadRootDir() {
// the absolute directory path where uploaded documents should be saved
return __DIR__ . '/../../../web/imgArticoli/';
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function uploadImage() {
// the file property can be empty if the field is not required
if (null === $this->image) {
return;
}
if(!$this->id){
$this->image->move($this->getTmpUploadRootDir(), $this->image->getClientOriginalName());
}else{
$this->image->move($this->getUploadRootDir(), $this->image->getClientOriginalName());
}
$this->setImage($this->image->getClientOriginalName());
}
/**
* #ORM\PostPersist()
*/
public function moveImage()
{
if (null === $this->image) {
return;
}
if(!is_dir($this->getUploadRootDir())){
mkdir($this->getUploadRootDir());
}
copy($this->getTmpUploadRootDir().$this->image, $this->getFullImagePath());
unlink($this->getTmpUploadRootDir().$this->image);
}
/**
* Set data
*
* #param \DateTime $data
*
* #return Article
*/
public function setData($data)
{
$this->data = $data;
return $this;
}
/**
* Get data
*
* #return \DateTime
*/
public function getData()
{
return $this->data;
}
/**
* Set categoria
*
* #param string $categoria
*
* #return Article
*/
public function setCategoria($categoria)
{
$this->categoria = $categoria;
return $this;
}
/**
* Get categoria
*
* #return string
*/
public function getCategoria()
{
return $this->categoria;
}
/**
* Add commentoarticle
*
* #param \AppBundle\Entity\CommentoArticle $commentoarticle
*
* #return Article
*/
public function addCommentoArticle(\AppBundle\Entity\CommentoArticle $commentoarticle)
{
$this->commentoarticle[] = $commentoarticle;
return $this;
}
/**
* Remove commentoarticle
*
* #param \AppBundle\Entity\CommentoArticle $commentoarticle
*/
public function removeCommentoArticle(\AppBundle\Entity\CommentoArticle $commentoarticle)
{
$this->commentoarticle->removeElement($commentoarticle);
}
/**
* Get commentoarticle
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCommentoArticle()
{
return $this->commentoarticle;
}
/**
* Set rate
*
* #param integer $rate
*
* #return Article
*/
public function setRate($rate)
{
$this->rate = $rate;
return $this;
}
/**
* Get rate
*
* #return integer
*/
public function getRate()
{
return $this->rate;
}
}
In the controller i have the update action
THIS IS THE CONTROLLER ACTION
public function update_ricettaAction(Request $request, $id)
{
//$this->denyAccessUnlessGranted('ROLE_ADMIN', null, 'Non puoi accedere a questa pagina!');
$em = $this->getDoctrine()->getManager();
$recipe = $em->getRepository('AppBundle:Recipe')->find($id);
$form = $this->createForm(new RecipeType($recipe), $recipe);
$form->handleRequest($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
try
{
$em->persist($recipe);
$em->flush();
return $this->redirect($this->generateUrl('successricettaupdate'));
} catch (\Exception $e)
{
$form->addError(new FormError('errore nel database: ' . $e->getMessage()));
}
if ($form->isValid())
{
$var = $recipe;
$em->persist($var);
$em->flush();
return $this->redirect($this->generateUrl('successricettaupdate'));
} else
{
}
}
return $this->render('administration/update_ricetta.html.twig', array(
'recipe' => $recipe,
'form' => $form->createView()));
}
When i submit the form, to update all, some, or just one field of the entity, i get the error:
Error: Call to a member function move() on a non-object
I don't know what can it be...
Any suggestion?
SOLVED
I solved my own problem, and this is the solution if can help anyone:
In the Entity, i modified this:
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function uploadImage() {
// the file property can be empty if the field is not required
if (null === $this->image) {
return;
}
if(!$this->id){
$this->image->move($this->getTmpUploadRootDir(), $this->image->getClientOriginalName());
}else{
$this->image->move($this->getUploadRootDir(), $this->image->getClientOriginalName());
}
$this->setImage($this->image->getClientOriginalName());
}
in to this:
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function uploadImage() {
// the file property can be empty if the field is not required
if (null === $this->image) {
return;
}
if(!$this->id){
$this->image->move($this->getTmpUploadRootDir(), $this->image->getClientOriginalName());
}else{
return null;
}
}
Now I don't get any error, and the updating works!

Zend2 Framework - Doctrine ORM giving Mapping Exception

I'm trying to use Doctrine 2 ORM for one of my Zend2 applications. I did the setup within the application using Doctrine modules with the help of composer.
I'm able to persist the data to the database, but when i make a find() call on the object manager it is giving me a Mapping Exception, with the following message.
Doctrine\Common\Persistence\Mapping\MappingException
File:
/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/MappingException.php:96
Message:
Class 'User' does not exist
Below are the Doctrine settings added under the Application module config file
'driver' => array(
'application_entities' => array(
'class' =>'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => array(__DIR__ . '/../src/Application/Entity')
),
'orm_default' => array(
'drivers' => array(
'Application\Entity' => 'application_entities'
)
)
)
),
This is the User Entity created under Application\src\Entity folder
<?php
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class User {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="NONE")
* #var int
*/
protected $user_id;
/**
* #ORM\Column(type="integer")
* #var int
*/
protected $network_id;
/**
* #ORM\Column(type="string", length=64)
* #var string
*/
protected $network_name;
/**
* #ORM\Column(type="string", length=64)
* #var string
*/
protected $job_title;
/**
* #ORM\Column(type="string", length=64)
* #var string
*/
protected $location;
/**
* #ORM\Column(type="string", length=64)
* #var string
*/
protected $first_name;
/**
* #ORM\Column(type="string", length=64)
* #var string
*/
protected $last_name;
/**
* #ORM\Column(type="string", length=255)
* #var string
*/
protected $url;
/**
* #ORM\Column(type="string", length=255)
* #var string
*/
protected $img_url;
/**
* #ORM\Column(type="string", length=255)
* #var string
*/
protected $department;
/**
* #ORM\Column(type="string", length=255)
* #var string
*/
protected $email_address;
/**
* #ORM\Column(type="boolean")
* #var string
*/
protected $verified;
/**
* #return the int
*/
public function getUserId() {
return $this->user_id;
}
/**
* #param int $user_id
*/
public function setUserId($user_id) {
$this->user_id = $user_id;
return $this;
}
/**
* #return the int
*/
public function getNetworkId() {
return $this->network_id;
}
/**
* #param int $network_id
*/
public function setNetworkId($network_id) {
$this->network_id = $network_id;
return $this;
}
/**
* #return the string
*/
public function getNetworkName() {
return $this->network_name;
}
/**
* #param string $network_name
*/
public function setNetworkName($network_name) {
$this->network_name = $network_name;
return $this;
}
/**
* #return the string
*/
public function getJobTitle() {
return $this->job_title;
}
/**
* #param string $job_title
*/
public function setJobTitle($job_title) {
$this->job_title = $job_title;
return $this;
}
/**
* #return the string
*/
public function getLocation() {
return $this->location;
}
/**
* #param string $location
*/
public function setLocation($location) {
$this->location = $location;
return $this;
}
/**
* #return the string
*/
public function getFirstName() {
return $this->first_name;
}
/**
* #param string $first_name
*/
public function setFirstName($first_name) {
$this->first_name = $first_name;
return $this;
}
/**
* #return the string
*/
public function getLastName() {
return $this->last_name;
}
/**
* #param string $last_name
*/
public function setLastName($last_name) {
$this->last_name = $last_name;
return $this;
}
/**
* #return the string
*/
public function getUrl() {
return $this->url;
}
/**
* #param string $url
*/
public function setUrl($url) {
$this->url = $url;
return $this;
}
/**
* #return the string
*/
public function getImgUrl() {
return $this->img_url;
}
/**
* #param string $img_url
*/
public function setImgUrl($img_url) {
$this->img_url = $img_url;
return $this;
}
/**
* #return the string
*/
public function getDepartment() {
return $this->department;
}
/**
* #param string $department
*/
public function setDepartment($department) {
$this->department = $department;
return $this;
}
/**
* #return the string
*/
public function getEmailAddress() {
return $this->email_address;
}
/**
* #param string $email_address
*/
public function setEmailAddress($email_address) {
$this->email_address = $email_address;
return $this;
}
/**
* #return the boolean
*/
public function getVerified() {
return $this->verified;
}
/**
* #param boolean $verified
*/
public function setVerified($verfied) {
$this->verified = $verfied;
return $this;
}
}
Now, when I do persist operation on the above entity from Application module's IndexController, it is working fine. But when I do the find operation using the same object mapper in the same IndexController, it is giving the mapping exception.
Below is how I'm doing this:
$objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
$objectManager->persist($user);
$objectManager->flush();
$user = $objectManager->find('User', $uniqueID);
Can anyone help me with this issue??
Regards.
Your entity is not called User but Application\Entity\User. So replace this line:
$user = $objectManager->find('User', $uniqueID);
With this:
$user = $objectManager->find('Application\Entity\User', $uniqueID);

Symfony 2 Embedded forms using one to many db relationship

I'm have a problem embedding forms from different entities in one form, my form is being displayed with firstname [input] lastname [input] address - but the address has no input next to it.
Basically I want to create a form where the user can add first name, last name, address1, address2, city, country ect and submit it it as one, although it's different tables.
The main form is no problem the only issue I'm having is with the second embedded form. Any help would be greatly appreciated.
Here is my code:
Member class:
namespace Pomc\MembersBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Pomc\MembersBundle\Entity\Member
*/
class Member
{
/**
* #var integer $id
*/
private $id;
/**
* #var string $firstName
*/
private $firstName;
/**
* #var string $lastName
*/
private $lastName;
/**
* #var Pomc\MembersBundle\Entity\Address
*/
private $address;
/**
* #var Pomc\MembersBundle\Entity\Telephone
*/
private $telephone;
public function __construct()
{
$this->address = new \Doctrine\Common\Collections\ArrayCollection();
$this->telephone = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set firstName
*
* #param string $firstName
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
}
/**
* Get firstName
*
* #return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Set lastName
*
* #param string $lastName
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
}
/**
* Get lastName
*
* #return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Add address
*
* #param Pomc\MembersBundle\Entity\Address $address
*/
public function addAddress(\Pomc\MembersBundle\Entity\Address $address)
{
$this->address[] = $address;
}
/**
* Get address
*
* #return Doctrine\Common\Collections\Collection
*/
public function getAddress()
{
return $this->address;
}
/**
* Add telephone
*
* #param Pomc\MembersBundle\Entity\Telephone $telephone
*/
public function addTelephone(\Pomc\MembersBundle\Entity\Telephone $telephone)
{
$this->telephone[] = $telephone;
}
/**
* Get telephone
*
* #return Doctrine\Common\Collections\Collection
*/
public function getTelephone()
{
return $this->telephone;
}
}
Here is the address class:
namespace Pomc\MembersBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Pomc\MembersBundle\Entity\Address
*/
class Address
{
/**
* #var integer $id
*/
private $id;
/**
* #var string $addressType
*/
private $addressType;
/**
* #var string $firstLine
*/
private $firstLine;
/**
* #var string $secondLine
*/
private $secondLine;
/**
* #var string $city
*/
private $city;
/**
* #var string $postCode
*/
private $postCode;
/**
* #var string $country
*/
private $country;
/**
* #var Pomc\MembersBundle\Entity\Member
*/
private $member;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set addressType
*
* #param string $addressType
*/
public function setAddressType($addressType)
{
$this->addressType = $addressType;
}
/**
* Get addressType
*
* #return string
*/
public function getAddressType()
{
return $this->addressType;
}
/**
* Set firstLine
*
* #param string $firstLine
*/
public function setFirstLine($firstLine)
{
$this->firstLine = $firstLine;
}
/**
* Get firstLine
*
* #return string
*/
public function getFirstLine()
{
return $this->firstLine;
}
/**
* Set secondLine
*
* #param string $secondLine
*/
public function setSecondLine($secondLine)
{
$this->secondLine = $secondLine;
}
/**
* Get secondLine
*
* #return string
*/
public function getSecondLine()
{
return $this->secondLine;
}
/**
* Set city
*
* #param string $city
*/
public function setCity($city)
{
$this->city = $city;
}
/**
* Get city
*
* #return string
*/
public function getCity()
{
return $this->city;
}
/**
* Set postCode
*
* #param string $postCode
*/
public function setPostCode($postCode)
{
$this->postCode = $postCode;
}
/**
* Get postCode
*
* #return string
*/
public function getPostCode()
{
return $this->postCode;
}
/**
* Set country
*
* #param string $country
*/
public function setCountry($country)
{
$this->country = $country;
}
/**
* Get country
*
* #return string
*/
public function getCountry()
{
return $this->country;
}
/**
* Set member
*
* #param Pomc\MembersBundle\Entity\Member $member
*/
public function setMember(\Pomc\MembersBundle\Entity\Member $member)
{
$this->member = $member;
}
/**
* Get member
*
* #return Pomc\MembersBundle\Entity\Member
*/
public function getMember()
{
return $this->member;
}
}
Here is the memberform:
namespace Pomc\MembersBundle\Form\Type;
use \Symfony\Component\Form\AbstractType;
use \Symfony\Component\Form\FormBuilder;
class MemberType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('firstName');
$builder->add('lastName');
$builder->add('address','collection', array( 'type' => new AddressType(),
'allow_add' => true,
'prototype' => true,
'by_reference' => false,
));
}
public function getDefaultOptions(array $options)
{
return array('data_class' => 'Pomc\MembersBundle\Entity\Member');
}
/**
* Returns the name of this type.
*
* #return string The name of this type
*/
function getName()
{
return 'member';
}
}
Here is the address form:
namespace Pomc\MembersBundle\Form\Type;
use \Symfony\Component\Form\AbstractType;
use \Symfony\Component\Form\FormBuilder;
class AddressType extends AbstractType
{
public function buildForm(Formbuilder $builder, array $options)
{
$builder->add('firstLine');
}
public function getDefaultOptions(array $options)
{
return array('data_class' => 'Pomc\MembersBundle\Entity\Address');
}
/**
* Returns the name of this type.
*
* #return string The name of this type
*/
function getName()
{
return 'address';
}
function getIdentifier()
{
return 'address';
}
}
Here is the controller:
namespace Pomc\MembersBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use \Pomc\MembersBundle\Entity\Member;
use \Symfony\Component\HttpFoundation\Request;
use \Pomc\MembersBundle\Form\Type\MemberType;
class DefaultController extends Controller
{
public function indexAction($name)
{
return $this->render('PomcMembersBundle:Default:index.html.twig', array('name' => $name));
}
public function newAction(Request $request)
{
$member = new Member();
$form = $this->get('form.factory')->create(new MemberType());
if($request->getMethod() == 'POST')
{
$form->bindRequest($request);
if($form->isValid())
{
$em = $this->getDoctrine()->getEntityManager();
$em->persist($member);
$em->flush();
}
}
return $this->render('PomcMembersBundle:Default:new.html.twig', array( 'form'=> $form->createView(),));
}
}
Here is the template:
<form action="{{ path('member_new') }}" method="post" {{ form_enctype(form)}}>
{{ form_widget(form) }}
<div>
{{ form_row(form.address)}}
</div>
<input type="submit" />
</form>
Been a long time user of this site, but this is my first question.
Thank you
Oh I faced the same problem, but I found the solution, hope this will help you :-)
You're forgetting to add an Address object to the member entity.
In your action you'll need to do the following:
$member = new Member();
$member->addAddress(new Address());
$form = $this->createForm(new MemberType(), $member);
And then in your template:
{% for address in form.address %}
{{ form_widget(address.firstLine) }}
{% endfor %}
Btw your 'firstline' widget doesn't relate to an entity property.
Btw if you called addAddress two times, you would of course get two 'firstline' widgets in your form.
Hope this works. best of luck.
Llewellyn, do you mean something like thid:
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('imBundle:Inspecciones')->find($id);
$entity_valores = $em->getRepository('imBundle:ValoresInspecciones')->findByInspecciones($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Inspecciones entity.');
}
$entity->setValoresInspecciones($entity_valores);
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('imBundle:Inspecciones:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}