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;
}
}
Related
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...
I have TYPO3 7.6.18
this is my code:
$newVideo = new \Istar\Fefiles\Domain\Model\Video();
$videoName = $video['name'];
$videoTmpName = $video['tmp_name'];
$resourceFactory = \TYPO3\CMS\Core\Resource\ResourceFactory::getInstance();
$storage = $resourceFactory->getDefaultStorage();
$folder = $storage->getFolder("user_upload/");
$movedFile = $storage->addFile($videoTmpName, $folder, $videoName);
$newFileReference = $this->objectManager$this->objectManager->get('TYPO3\\CMS\\Extbase\\Domain\\Model\\FileReference');
$newFileReference->setFile($movedFile);
$newVideo->setVideo($newFileReference);
$this->videoRepository->add($newVideo);
$persistenceManager = $this->objectManager->get("TYPO3\\CMS\\Extbase\\Persistence\\Generic\\PersistenceManager");
$persistenceManager->persistAll();
The problem is it added two files to field video file reference. It's very sudenly! And second file is't the same, it's diferent files. I sure, I send one file. Where may be the problem ?
I have model photo, and there is field image
'image' => [
'exclude' => 0,
'label' => 'LLL:EXT:fefiles/Resources/Private/Language/locallang_db.xlf:image',
'config' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getFileFieldTCAConfig('image', [
'appearance' => [
'createNewRelationLinkTitle' => 'LLL:EXT:cms/locallang_ttc.xlf:images.addFileReference'
],
'maxitems' => 1,
], $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'])
],
Anf I see that when I create photo from BE, and upload image - this add second image, which was uploaded on site early. This is very strange! What happens ?
My video model:
<?php
namespace Istar\Fefiles\Domain\Model;
class Video extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
{
/**
* #var bool
*/
public $allow_for_user = true;
/**
* Title
*
* #var string
* #validate NotEmpty
*/
protected $title = '';
/**
* Description
*
* #var string
*/
protected $description = '';
/**
* rulesDescription
*
* #var string
*/
protected $rulesDescription = '';
/**
* User
*
* #var \Fhk\Feusersplus\Domain\Model\User>
*/
protected $user;
/**
* Videocategory
*
* #var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Istar\Fefiles\Domain\Model\Videocategory>
*/
protected $videocategory;
/**
* Videocomment
*
* #var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Istar\Fefiles\Domain\Model\Videocomment>
* #cascade remove
*/
protected $comment;
/**
* Allow
*
* #var int
*/
protected $allow = 0;
/**
* fskcheck
*
* #var int
*/
protected $fskcheck = 0;
/**
* private
*
* #var int
*/
protected $private = 0;
/**
* Video
* #validate NotEmpty
* #var \TYPO3\CMS\Extbase\Domain\Model\FileReference
* #cascade remove
*/
protected $video;
/**
* preview
*
* #var \TYPO3\CMS\Extbase\Domain\Model\FileReference
* #cascade remove
*/
protected $preview = null;
/**
* blurred
*
* #var \TYPO3\CMS\Extbase\Domain\Model\FileReference
* #cascade remove
*/
protected $blurred = null;
/**
* Crdate
*
* #var int
* #validate NotEmpty
*/
protected $crdate = 0;
/**
* Returns the title
*
* #return string $title
*/
public function getTitle()
{
return $this->title;
}
/**
* Sets the title
*
* #param string $title
* #return void
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* Returns the description
*
* #return string $description
*/
public function getDescription()
{
return $this->description;
}
/**
* Sets the description
*
* #param string $description
* #return void
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Returns the rulesDescription
*
* #return string $rulesDescription
*/
public function getRulesDescription()
{
return $this->rulesDescription;
}
/**
* Sets the rulesDescription
*
* #param string $rulesDescription
* #return void
*/
public function setRulesDescription($rulesDescription)
{
$this->rulesDescription = $rulesDescription;
}
/**
* Returns the video
*
* #return \TYPO3\CMS\Extbase\Domain\Model\FileReference $video
*/
public function getVideo()
{
return $this->video;
}
/**
* Returns the videocategory
*
* #return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Istar\Fefiles\Domain\Model\Videocategory> $videocategory
*/
public function getVideocategory()
{
return $this->videocategory;
}
/**
* Sets the videocategory
*
* #return void
*/
public function setVideocategory($videocategory)
{
$this->videocategory = $videocategory;
}
/**
* Returns the comment
*
* #return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\Istar\Fefiles\Domain\Model\Videocomment> $comment
*/
public function getComment()
{
return $this->comment;
}
/**
* Sets the comment
*
* #return void
*/
public function setComment($comment)
{
$this->comment = $comment;
}
/**
* Adds a comments to the video
*
* #param \Istar\Fefiles\Domain\Model\Videocomment $comment
* #return void
* #api
*/
public function addComment(\Istar\Fefiles\Domain\Model\Videocomment $comment)
{
$this->comment->attach($comment);
}
/**
* Removes a comment from the video
*
* #param \Istar\Fefiles\Domain\Model\Videocomment $comment
* #return void
* #api
*/
public function removeComment(\Istar\Fefiles\Domain\Model\Videocomment $comment)
{
$this->comment->detach($comment);
}
/**
* Returns the user
*
* #return \Fhk\Feusersplus\Domain\Model\User> $user
*/
public function getUser()
{
return $this->user;
}
/**
* Sets the user
*
* #return void
*/
public function setUser($user)
{
$this->user = $user;
}
/**
* Returns the allow
*
* #return int
*/
public function getAllow()
{
return $this->allow;
}
/**
* Sets the video
*
* #param \TYPO3\CMS\Extbase\Domain\Model\FileReference $video
* #return void
*/
public function setVideo($video)
{
$this->video = $video;
}
/**
* Returns the preview
*
* #return \TYPO3\CMS\Extbase\Domain\Model\FileReference $preview
*/
public function getPreview()
{
return $this->preview;
}
/**
* Sets the preview
*
* #param \TYPO3\CMS\Extbase\Domain\Model\FileReference $preview
*
* #return void
*/
public function setPreview($preview)
{
$this->preview = $preview;
}
/**
* Returns the blurred
*
* #return \TYPO3\CMS\Extbase\Domain\Model\FileReference $blurred
*/
public function getBlurred()
{
return $this->blurred;
}
/**
* Sets the blurred
*
* #param \TYPO3\CMS\Extbase\Domain\Model\FileReference $blurred
*
* #return void
*/
public function setBlurred($blurred)
{
$this->blurred = $blurred;
}
/**
* Returns the fskcheck
*
* #return int
*/
public function getFskcheck()
{
return $this->fskcheck;
}
/**
* Sets the fskcheck
*
* #return void
*/
public function setFskcheck($fskcheck)
{
$this->fskcheck = $fskcheck;
}
/**
* Returns the Private
*
* #return int
*/
public function getPrivate()
{
return $this->private;
}
/**
* Sets the private
*
* #return void
*/
public function setPrivate($private)
{
$this->private = $private;
}
/**
* Returns the crdate
* #return int $crdate
*/
public function getCrdate()
{
return $this->crdate;
}
/**
* Sets the crdate
*
* #param int $crdate
* #return void
*/
public function setCrdate($crdate)
{
$this->crdate = $crdate;
}
}
Have a look at the sys_file_reference table before and after you create a new record in the backend. Is there a new record added? And after saving an existing record you don't get the random image/video added?
Solution:
'foreign_match_fields' => array(
'fieldname' => 'image',
'tablenames' => 'tx_fefiles_domain_model_photo',
'table_local' => 'sys_file_reference',
),
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!
It would appear my lifecycle callbacks are not triggered when the form to upload my file is embedded in another form. If the upload form is on its own the lifecycle callbacks are triggered.
I have a form that creates a 'user' entity, for this user I have a one-on-one relationship with the 'ProfilePicture' entity which has the lifecycle callbacks, I want to upload the profilepicture file on the same form. I followed the "How to handle File Uploads" cookbook, but it doesn't explain how to handle embedded forms.
UserType
<?php
namespace CashBack\AdminBundle\Form\Type;
use CashBack\DefaultBundle\Entity\ProfilePicture;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
/* additional fields that should not be saved in this object need ->add('agreeWithTerms', null,array('mapped' => false))*/
$builder
->add('id','hidden',array('mapped' => false))
->add('username')
->add('password')
->add('firstname')
->add('lastname')
->add('email')
->add('gender')
->add('dateOfBirth','birthday')
->add('customrole')
->add('profilepicture', new ProfilePictureType())
->add('save', 'submit');
}
/* Identifier */
public function getName()
{
return 'User';
}
/* Makes sure the form doesn't need to guess the date type */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'CashBack\DefaultBundle\Entity\User',
'cascade_validation' => true,
));
}
}
ProfilePictureType
<?php
namespace CashBack\AdminBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ProfilePictureType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
/* additional fields that should not be saved in this object need ->add('agreeWithTerms', null,array('mapped' => false))*/
$builder
->add('id','hidden',array('mapped' => false))
->add('file','file');
}
/* Identifier */
public function getName()
{
return 'ProfilePicture';
}
/* Makes sure the form doesn't need to guess the date type */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'CashBack\DefaultBundle\Entity\ProfilePicture',
));
}
}
ProfilePicture Entity
<?php
namespace CashBack\DefaultBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class ProfilePicture
{
/**
* #var integer
*
* #ORM\Column(name="Id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $path;
public function getAbsolutePath()
{
return null === $this->path
? null
: $this->getUploadRootDir() . '/' . $this->path;
}
public function getWebPath()
{
return null === $this->path
? null
: $this->getUploadDir() . '/' . $this->path;
}
protected function getUploadRootDir()
{
// the absolute directory path where uploaded
// documents should be saved
return __DIR__ . '/../../../../web/' . $this->getUploadDir();
}
protected function getUploadDir()
{
// get rid of the __DIR__ so it doesn't screw up
// when displaying uploaded doc/image in the view.
return 'uploads/documents';
}
/**
* #Assert\File(maxSize="6000000")
*/
private $file;
private $temp;
/**
* Sets file.
*
* #param UploadedFile $file
*/
public function setFile(UploadedFile $file = null)
{
$this->file = $file;
// check if we have an old image path
if (isset($this->path)) {
// store the old name to delete after the update
$this->temp = $this->path;
$this->path = null;
} else {
$this->path = 'initial';
}
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if (null !== $this->getFile()) {
// do whatever you want to generate a unique name
$filename = sha1(uniqid(mt_rand(), true));
$this->path = $filename . '.' . $this->getFile()->guessExtension();
}
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
if (null === $this->getFile()) {
return;
}
// if there is an error when moving the file, an exception will
// be automatically thrown by move(). This will properly prevent
// the entity from being persisted to the database on error
$this->getFile()->move($this->getUploadRootDir(), $this->path);
// check if we have an old image
if (isset($this->temp)) {
// delete the old image
unlink($this->getUploadRootDir() . '/' . $this->temp);
// clear the temp image path
$this->temp = null;
}
$this->file = null;
}
/**
* #ORM\PostRemove()
*/
public function removeUpload()
{
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
/**
* Get file.
*
* #return UploadedFile
*/
public function getFile()
{
return $this->file;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set path
*
* #param string $path
*
* #return ProfilePicture
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* #ORM\OneToOne(targetEntity="User", inversedBy="profilepicture")
* #ORM\JoinColumn(name="user_id", referencedColumnName="Id")
*/
protected $user;
/**
* Set user
*
* #param \CashBack\DefaultBundle\Entity\User $user
*
* #return ProfilePicture
*/
public function setUser(\CashBack\DefaultBundle\Entity\User $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \CashBack\DefaultBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
}
User Entity
<?php
namespace CashBack\DefaultBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity
*/
class User
{
/**
* #var string
*
* #ORM\Column(name="FirstName", type="string", length=10, nullable=true)
*/
private $firstname;
/**
* #var string
*
* #ORM\Column(name="LastName", type="string", length=20, nullable=true)
*/
private $lastname;
/**
* #var string
*
* #ORM\Column(name="Gender", type="string", length=1, nullable=true)
*/
private $gender;
/**
* #var string
*
* #ORM\Column(name="Email", type="string", length=50, nullable=false)
*/
private $email;
/**
* #var \DateTime
*
* #ORM\Column(name="DateOfBirth", type="date", nullable=false)
*/
private $dateofbirth;
/**
* #var string
*
* #ORM\Column(name="Username", type="string", length=50, nullable=false)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="Password", type="string", length=100, nullable=false)
*/
private $password;
/**
* #var integer
*
* #ORM\Column(name="Id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="CashBack\DefaultBundle\Entity\Tag", inversedBy="user")
* #ORM\JoinTable(name="user_tag",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="Id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="tag_id", referencedColumnName="Id")
* }
* )
*/
private $tag;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="CashBack\DefaultBundle\Entity\Customrole", inversedBy="user")
* #ORM\JoinTable(name="user_customrole",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="Id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="customrole_id", referencedColumnName="Id")
* }
* )
*/
private $customrole;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="CashBack\DefaultBundle\Entity\Shop", inversedBy="user")
* #ORM\JoinTable(name="user_shop",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="Id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="shop_id", referencedColumnName="Id")
* }
* )
*/
private $shop;
/**
* Constructor
*/
public function __construct()
{
$this->tag = new \Doctrine\Common\Collections\ArrayCollection();
$this->customrole = new \Doctrine\Common\Collections\ArrayCollection();
$this->shop = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set firstname
*
* #param string $firstname
*
* #return User
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* #return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set lastname
*
* #param string $lastname
*
* #return User
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* #return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* Set gender
*
* #param string $gender
*
* #return User
*/
public function setGender($gender)
{
$this->gender = $gender;
return $this;
}
/**
* Get gender
*
* #return string
*/
public function getGender()
{
return $this->gender;
}
/**
* Set email
*
* #param string $email
*
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set dateofbirth
*
* #param \DateTime $dateofbirth
*
* #return User
*/
public function setDateofbirth($dateofbirth)
{
$this->dateofbirth = $dateofbirth;
return $this;
}
/**
* Get dateofbirth
*
* #return \DateTime
*/
public function getDateofbirth()
{
return $this->dateofbirth;
}
/**
* Set username
*
* #param string $username
*
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* #param string $password
*
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add tag
*
* #param \CashBack\DefaultBundle\Entity\Tag $tag
*
* #return User
*/
public function addTag(\CashBack\DefaultBundle\Entity\Tag $tag)
{
$this->tag[] = $tag;
return $this;
}
/**
* Remove tag
*
* #param \CashBack\DefaultBundle\Entity\Tag $tag
*/
public function removeTag(\CashBack\DefaultBundle\Entity\Tag $tag)
{
$this->tag->removeElement($tag);
}
/**
* Get tag
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTag()
{
return $this->tag;
}
/**
* Add customrole
*
* #param \CashBack\DefaultBundle\Entity\Customrole $customrole
*
* #return User
*/
public function addCustomrole(\CashBack\DefaultBundle\Entity\Customrole $customrole)
{
$this->customrole[] = $customrole;
return $this;
}
/**
* Remove customrole
*
* #param \CashBack\DefaultBundle\Entity\Customrole $customrole
*/
public function removeCustomrole(\CashBack\DefaultBundle\Entity\Customrole $customrole)
{
$this->customrole->removeElement($customrole);
}
/**
* Get customrole
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCustomrole()
{
return $this->customrole;
}
/**
* Add shop
*
* #param \CashBack\DefaultBundle\Entity\Shop $shop
*
* #return User
*/
public function addShop(\CashBack\DefaultBundle\Entity\Shop $shop)
{
$this->shop[] = $shop;
return $this;
}
/**
* Remove shop
*
* #param \CashBack\DefaultBundle\Entity\Shop $shop
*/
public function removeShop(\CashBack\DefaultBundle\Entity\Shop $shop)
{
$this->shop->removeElement($shop);
}
/**
* Get shop
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getShop()
{
return $this->shop;
}
/** #ORM\OneToOne(targetEntity="ProfilePicture", mappedBy="user", cascade={"persist", "all"}) */
protected $profilepicture;
/**
* Set profilepicture
*
* #param \CashBack\DefaultBundle\Entity\ProfilePicture $profilepicture
*
* #return User
*/
public function setProfilepicture(\CashBack\DefaultBundle\Entity\ProfilePicture $profilepicture)
{
$this->profilepicture = $profilepicture;
$profilepicture->setUser($this);
return $this;
}
/**
* Get profilepicture
*
* #return \CashBack\DefaultBundle\Entity\ProfilePicture
*/
public function getProfilepicture()
{
return $this->profilepicture;
}
}
User controller
//adds a new entity from data received via Ajax, no redirect
public function addAjaxAction(Request $request)
{
$user = new User();
$form = $this->createForm(new UserType(), $user);
$form->handleRequest($request);
$user = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
//prepare the response, e.g.
$response = array("code" => 100, "success" => true);
//you can return result as JSON , remember to 'use' Response!
return new Response(json_encode($response));
}
EDIT: when checking the profiler I saw that the following object is submitted in the form:
If i check the profiler I see the following object being submitted in the form: {"username":"test","password":"test","firstname":"test","lastname":"test","email":"test","gender":"t","dateOfBirth":{"month":"1","day":"1","year":"1902"},"customrole":["2"],"id":"","profilepicture":{"id":""},"_token":"YUDiZLi8dY6jtmEhZWk6ivnH3vsQIpnM_fxQ3ClJ2Gw"}
Profile picture is thus empty.
I get
Warning: spl_object_hash() expects parameter 1 to be object, boolean given in /Path/vendor/doctrine-mongodb-odm/lib/Doctrine/ODM/MongoDB/UnitOfWork.php line 1504
error when I try to do $dm->flush();
I persist object like this
$eve = new Event();
$eve->setEvent($event);
Here $event is array which gets converted to object using the setEvent() function.
The event class is given below.
<?php
namespace CE\MainBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\Document(collection="events")
* #MongoDB\Index(keys={"coordinates"="2d"})
*/
Class Event{
/**
* #MongoDB\Id
*/
protected $id;
/**
* #MongoDB\String
* #MongoDB\Index(unique=true,order="asc")
*/
protected $eid;
/**
* #MongoDB\Int
*/
protected $start_time;
/**
* #MongoDB\Int
*/
protected $end_time;
/**
* #MongoDB\String
*/
protected $title;
/**
* #MongoDB\String
*/
protected $description;
/**
* #MongoDB\String
*/
protected $host;
/**
* #MongoDB\String
*/
protected $location;
/**
* #MongoDB\String
*/
protected $pic_square;
/**
* #MongoDB\EmbedOne(targetDocument="Coordinates")
*/
protected $coordinates=array();
/**
* #MongoDB\Int
* #MongoDB\Index(order="asc")
*/
protected $city_id;
/**
* #MongoDB\String
*/
protected $city_name;
/**
* #MongoDB\String
*/
protected $country;
/**
* #MongoDB\String
*/
protected $timezone;
/**
* #MongoDB\String
*/
protected $owner;
/**
* #MongoDB\Collection
* #MongoDB\Index(order="asc")
*/
protected $tags = array();
/**
* #MongoDB\EmbedOne(targetDocument="Event_status")
*/
protected $event_status = array();
/**
* Get id
*
* #return id $id
*/
public function getId()
{
return $this->id;
}
/**
* Set eid
*
* #param string $eid
*/
public function setEid($eid)
{
$this->eid = $eid;
}
/**
* Get eid
*
* #return string $eid
*/
public function getEid()
{
return $this->eid;
}
/**
* Set start_time
*
* #param int $startTime
*/
public function setStartTime($startTime)
{
$this->start_time = $startTime;
}
/**
* Get start_time
*
* #return int $startTime
*/
public function getStartTime()
{
return $this->start_time;
}
/**
* Set end_time
*
* #param int $endTime
*/
public function setEndTime($endTime)
{
$this->end_time = $endTime;
}
/**
* Get end_time
*
* #return int $endTime
*/
public function getEndTime()
{
return $this->end_time;
}
/**
* Set title
*
* #param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* Get title
*
* #return string $title
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* #param string $description
*/
public function setDescription($description)
{
$this->description = $description;
}
/**
* Get description
*
* #return string $description
*/
public function getDescription()
{
return $this->description;
}
/**
* Set host
*
* #param string $host
*/
public function setHost($host)
{
$this->host = $host;
}
/**
* Get host
*
* #return string $host
*/
public function getHost()
{
return $this->host;
}
/**
* Set location
*
* #param string $location
*/
public function setLocation($location)
{
$this->location = $location;
}
/**
* Get location
*
* #return string $location
*/
public function getLocation()
{
return $this->location;
}
/**
* Set pic_square
*
* #param string $picSquare
*/
public function setPicSquare($picSquare)
{
$this->pic_square = $picSquare;
}
/**
* Get pic_square
*
* #return string $picSquare
*/
public function getPicSquare()
{
return $this->pic_square;
}
/**
* Set coordinates
*
* #param CE\MainBundle\Document\coordinates $coordinates
*/
public function setCoordinates(\CE\MainBundle\Document\Coordinates $coordinates)
{
$this->coordinates = $coordinates;
}
/**
* Get coordinates
*
* #return CE\MainBundle\Document\coordinates $coordinates
*/
public function getCoordinates()
{
return $this->coordinates;
}
/**
* Set city_id
*
* #param int $cityId
*/
public function setCityId($cityId)
{
$this->city_id = $cityId;
}
/**
* Get city_id
*
* #return int $cityId
*/
public function getCityId()
{
return $this->city_id;
}
/**
* Set city_name
*
* #param string $cityName
*/
public function setCityName($cityName)
{
$this->city_name = $cityName;
}
/**
* Get city_name
*
* #return string $cityName
*/
public function getCityName()
{
return $this->city_name;
}
/**
* Set country
*
* #param string $country
*/
public function setCountry($country)
{
$this->country = $country;
}
/**
* Get country
*
* #return string $country
*/
public function getCountry()
{
return $this->country;
}
/**
* Set timezone
*
* #param string $timezone
*/
public function setTimezone($timezone)
{
$this->timezone = $timezone;
}
/**
* Get timezone
*
* #return string $timezone
*/
public function getTimezone()
{
return $this->timezone;
}
/**
* Set owner
*
* #param int $owner
*/
public function setOwner($owner)
{
$this->owner = $owner;
}
/**
* Get owner
*
* #return int $owner
*/
public function getOwner()
{
return $this->owner;
}
/**
* Set tags
*
* #param collection $tags
*/
public function setTags($tags)
{
$this->tags = $tags;
}
/**
* Get tags
*
* #return collection $tags
*/
public function getTags()
{
return $this->tags;
}
/**
* Set event_status
*
* #param CE\MainBundle\Document\event_status $eventStatus
*/
public function setEventStatus(\CE\MainBundle\Document\Event_status $eventStatus)
{
$this->event_status = $eventStatus;
}
/**
* Get event_status
*
* #return CE\MainBundle\Document\event_status $eventStatus
*/
public function getEventStatus()
{
return $this->event_status;
}
public function setEvent($event){
$this->eid = $event['eid'];
$this->start_time = $event['start_time'];
$this->end_time = $event['end_time'];
$this->description = $event['description'];
$this->host = $event['host'];
$this->location = $event['location'];
$this->pic_square = $event['pic_square'];
$this->city_id = (int)$event['city_id'];
$this->city_name = $event['city_name'];
$this->country = $event['country'];
$this->timezone = $event['timezone'];
$this->owner = $event['owner'];
$this->title = $event['title'];
$this->tags = $event['tags'];
$loc=new Coordinates();
$loc->setLongitude($event['coordinates']['longitude']);
$loc->setLatitude($event['coordinates']['latitude']);
$this->coordinates = $loc;
$stat = new Event_status();
$stat->setAttendCount($event['event_status']['attend_count']);
$stat->setAttendList($event['event_status']['attend_list']);
$stat->setClickCount($event['event_status']['click_count']);
$this->event_status = $stat;
}
}
/**
* #MongoDB\EmbeddedDocument
*/
Class Coordinates{
/**
* #MongoDB\Float
*/
protected $longitude;
/**
* #MongoDB\Float
*/
protected $latitude;
/**
* Set longitude
*
* #param float $longitude
*/
public function setLongitude($longitude)
{
$this->longitude = $longitude;
}
/**
* Get longitude
*
* #return float $longitude
*/
public function getLongitude()
{
return $this->longitude;
}
/**
* Set latitude
*
* #param float $latitude
*/
public function setLatitude($latitude)
{
$this->latitude = $latitude;
}
/**
* Get latitude
*
* #return float $latitude
*/
public function getLatitude()
{
return $this->latitude;
}
}
/**
* #MongoDB\EmbeddedDocument
*/
Class Event_status{
/**
* #MongoDB\Int
*/
protected $attend_count;
/**
* #MongoDB\Int
* #MongoDB\Index(order="desc")
*/
protected $click_count;
/**
* #MongoDB\Collection
*/
protected $attend_list = array();
/**
* Set attend_count
*
* #param int $attendCount
*/
public function setAttendCount($attendCount)
{
$this->attend_count = $attendCount;
}
/**
* Get attend_count
*
* #return int $attendCount
*/
public function getAttendCount()
{
return $this->attend_count;
}
/**
* Set click_count
*
* #param int $clickCount
*/
public function setClickCount($clickCount)
{
$this->click_count = $clickCount;
}
/**
* Get click_count
*
* #return int $clickCount
*/
public function getClickCount()
{
return $this->click_count;
}
public function incClickCount($i){
$this->click_count = $this->click_count + $i;
}
/**
* Set attend_list
*
* #param collection $attendList
*/
public function setAttendList($attendList)
{
$this->attend_list = $attendList;
}
/**
* Get attend_list
*
* #return collection $attendList
*/
public function getAttendList()
{
return $this->attend_list;
}
}
And I am trying to persist following object
object(CE\MainBundle\Document\Event)#302 (17) {
["id":protected]=>
NULL
["eid":protected]=>
string(15) "116189838391483"
["start_time":protected]=>
int(1356069600)
["end_time":protected]=>
int(1356080400)
["title":protected]=>
string(38) "Sex on December 20, 2012 Just In Case"
["description":protected]=>
string(322) "Spread the word
Maps : http://maps.google.nl/maps?f=q&source=s_q&hl=nl&q=Vondelpark,+1071+AA+Oud-Zuid,+Amsterd%C3%A3,+Amsterdam,+Noord-Holland&sll=52.469397,5.509644&sspn=5.134105,16.907959&ie=UTF8&geocode=FR_rHgMdG0pKAA&split=0&hq=&hnear=1071+AA+Amsterdam,+Noord-Holland&ll=52.360231,4.873273&spn=0.010051,0.033023&z=16
"
["host":protected]=>
string(19) "Sébastien Carvalho"
["location":protected]=>
string(21) "Amsterdam, VondelPark"
["pic_square":protected]=>
string(89) "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc4/71137_116189838391483_7509117_q.jpg"
["coordinates":protected]=>
object(CE\MainBundle\Document\Coordinates)#344 (2) {
["longitude":protected]=>
float(4.88969)
["latitude":protected]=>
float(52.37403)
}
["city_id":protected]=>
int(2759794)
["city_name":protected]=>
string(9) "Amsterdam"
["country":protected]=>
string(11) "Netherlands"
["timezone":protected]=>
string(16) "Europe/Amsterdam"
["owner":protected]=>
string(10) "1345873725"
["tags":protected]=>
array(39) {
[0]=>
string(3) "sex"
[1]=>
string(6) "decemb"
[2]=>
string(4) "just"
[3]=>
string(4) "case"
[4]=>
string(6) "spread"
[5]=>
string(4) "word"
[6]=>
string(3) "map"
[7]=>
string(1) ":"
[8]=>
string(5) "http:"
[9]=>
string(5) "googl"
[10]=>
string(2) "nl"
[11]=>
string(1) "f"
[12]=>
string(1) "q"
[13]=>
string(5) "sourc"
[14]=>
string(0) ""
[15]=>
string(2) "hl"
[16]=>
string(10) "vondelpark"
[17]=>
string(2) "aa"
[18]=>
string(3) "oud"
[19]=>
string(4) "zuid"
[20]=>
string(7) "amsterd"
[21]=>
string(2) "c3"
[22]=>
string(2) "a3"
[23]=>
string(9) "amsterdam"
[24]=>
string(5) "noord"
[25]=>
string(7) "holland"
[26]=>
string(3) "sll"
[27]=>
string(4) "sspn"
[28]=>
string(2) "ie"
[29]=>
string(4) "utf8"
[30]=>
string(6) "geocod"
[31]=>
string(2) "fr"
[32]=>
string(11) "rhgmdg0pkaa"
[33]=>
string(5) "split"
[34]=>
string(2) "hq"
[35]=>
string(5) "hnear"
[36]=>
string(2) "ll"
[37]=>
string(3) "spn"
[38]=>
string(1) "z"
}
["event_status":protected]=>
object(CE\MainBundle\Document\Event_status)#305 (3) {
["attend_count":protected]=>
int(0)
["click_count":protected]=>
int(0)
["attend_list":protected]=>
array(0) {
}
}
}
Please tell me where is the error?