I'm updating a website from Symfony 1.x to Symfony 2.1 during my internship, and i have some issues with Doctrine's Annotations. Btw i'm kinda newbie in Symfony2.
I meet this type of exception :
An exception has been thrown during the rendering of a template
("[Semantical Error] The annotation "#Doctrine\ORM\Mapping\OrderBy" in
property IHQS\NuitBlancheBundle\Entity\SC2Profile::$games does not
exist, or could not be auto-loaded.") in
"/var/www/sites/nuitblanche1/src/IHQS/NuitBlancheBundle/Resources/views/News/archives.html.twig".
And my code is:
<?php
namespace IHQS\NuitBlancheBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass="IHQS\NuitBlancheBundle\Model\SC2ProfileRepository")
* #ORM\Table(name="player")
*/
class SC2Profile
{
const SC2RACE_PROTOSS = "protoss";
const SC2RACE_TERRAN = "terran";
const SC2RACE_ZERG = "zerg";
const SC2RACE_RANDOM = "random";
static public $_sc2races = array(
self::SC2RACE_PROTOSS => self::SC2RACE_PROTOSS,
self::SC2RACE_TERRAN => self::SC2RACE_TERRAN,
self::SC2RACE_ZERG => self::SC2RACE_ZERG,
self::SC2RACE_RANDOM => self::SC2RACE_RANDOM
);
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToOne(targetEntity="User", inversedBy="sc2", cascade={"persist"})
* #Assert\NotBlank
*/
protected $user;
/**
* #ORM\Column(type="string", nullable=true)
*/
protected $sc2Role;
/**
* #ORM\Column(type="integer")
* #Assert\Regex("/\d+/")
*/
protected $sc2Id;
/**
* #ORM\Column(type="integer", nullable=true)
*/
protected $sc2RanksId;
/**
* #ORM\Column(type="string", nullable=true)
*/
protected $sc2Account;
/**
* #ORM\Column(type="string")
* #Assert\Choice(callback = "getSC2Races")
*/
protected $sc2Race;
/**
* #ORM\Column(type="string", nullable=true)
* #Assert\Regex("/\d+/")
*/
protected $sc2ProfileEsl;
/**
* #ORM\Column(type="string", nullable=true)
* #Assert\Regex("/\d+/")
*/
protected $sc2ProfileSc2cl;
/**
* #ORM\Column(type="string", nullable=true)
*/
protected $sc2ProfilePandaria;
/**
* #ORM\Column(type="text", nullable=true)
*/
protected $sc2Ranks;
/**
* #ORM\ManyToMany(targetEntity="Team", mappedBy="players")
*/
protected $teams;
/**
* #ORM\OneToMany(targetEntity="GamePlayer", mappedBy="player")
* #ORM\OrderBy({"id" = "DESC"})
*/
protected $games;
protected $stats;
protected $statsInit = false;
public function getId() {
return $this->id;
}
public function getUser() {
return $this->user;
}
public function setUser(User $user) {
$this->user = $user;
}
public function getUsername() {
return $this->user->getUserName();
}
public function getSc2Role() {
return $this->sc2Role;
}
public function setSc2Role($sc2Role) {
$this->sc2Role = $sc2Role;
}
public function getSc2Id() {
return $this->sc2Id;
}
public function setSc2Id($sc2Id) {
$this->sc2Id = $sc2Id;
}
public function getSc2RanksId()
{
return $this->sc2RanksId;
}
public function setSc2RanksId($sc2RanksId)
{
$this->sc2RanksId = $sc2RanksId;
}
public function getSc2Account() {
return $this->sc2Account;
}
public function setSc2Account($sc2Account) {
$this->sc2Account = $sc2Account;
}
public function getSc2Race() {
return $this->sc2Race;
}
public function setSc2Race($sc2Race) {
if(!in_array($sc2Race, SC2Profile::$_sc2races))
{
throw new \InvalidArgumentException('Invalid parameter "' . $sc2Race . '" for StarCraft 2 Race');
}
$this->sc2Race = $sc2Race;
}
public function getSc2ProfileEsl() {
return $this->sc2ProfileEsl;
}
public function setSc2ProfileEsl($sc2ProfileEsl) {
$this->sc2ProfileEsl = $sc2ProfileEsl;
}
public function getSc2ProfileSc2cl() {
return $this->sc2ProfileSc2cl;
}
public function setSc2ProfileSc2cl($sc2ProfileSc2cl) {
$this->sc2ProfileSc2cl = $sc2ProfileSc2cl;
}
public function getSc2ProfilePandaria() {
return $this->sc2ProfilePandaria;
}
public function setSc2ProfilePandaria($sc2ProfilePandaria) {
$this->sc2ProfilePandaria = $sc2ProfilePandaria;
}
public function getGames() {
$games = $this->games;
$result = array();
foreach($games as $game)
{
$result[] = $game->getGame();
}
return $result;
}
public function getWarGames()
{
$warGames = array();
foreach($this->getGames() as $game)
{
$wg = $game->getWarGame();
if($wg instanceof WarGame)
{
$warGames[$wg->getId()] = $wg;
}
}
return $warGames;
}
public function getReplays() {
$games = $this->games;
$result = array();
foreach($games as $game)
{
if(!$game->getGame()) { continue; }
if(!$game->getGame()->getReplay()) { continue; }
$result[] = $game->getGame();
}
return $result;
}
public function getStats()
{
if($this->statsInit) { return $this->stats; }
$this->initStatsVariables();
$counter = 0;
foreach($this->getWarGames() as $game)
{
$team2 = false;
foreach($game->getTeam2() as $p2)
{
if($p2->getPlayer() && $p2->getPlayer()->getId() == $this->getId()) { $team2 = true; break; }
}
if($team2) { continue; }
$type = "_" . $game->getType();
if($game->getTeam1Result() == Game::RESULT_WIN) { $this->stats[$type]["wins"]++; }
if($game->getTeam1Result() == Game::RESULT_LOSS) { $this->stats[$type]["losses"]++; }
if($game->getType() == Game::TYPE_1v1)
{
$type = $type.$game->getTeam2Race();
if($game->getTeam1Result() == Game::RESULT_WIN) { $this->stats[$type]["wins"]++; }
if($game->getTeam1Result() == Game::RESULT_LOSS) { $this->stats[$type]["losses"]++; }
}
}
foreach($this->stats as $type => $data)
{
$this->stats[$type]["ratio"] = (($data["losses"] + $data["wins"]) == 0)
? 0
: round(100 * $data["wins"] / ($data["losses"] + $data["wins"]));
}
$this->statsInit = true;
return $this->stats;
}
public function initStatsVariables()
{
$this->stats = array(
"_1v1" => array(),
"_2v2" => array(),
"_3v3" => array(),
"_4v4" => array(),
"_1v1protoss" => array(),
"_1v1terran" => array(),
"_1v1zerg" => array(),
"_1v1random" => array()
);
foreach($this->stats as $type => $data)
{
$this->stats[$type] = array(
"wins" => 0,
"losses" => 0,
"ratio" => 0
);
}
}
public function get2v2Teams()
{
$teams = array();
foreach($this->getWarGames() as $game)
{
if($game->getType() != Game::TYPE_2v2)
{
continue;
}
$team2 = false;
foreach($game->getTeam2() as $p2)
{
if($p2->getPlayer() && $p2->getPlayer()->getId() == $this->getId()) { $team2 = true; break; }
}
if($team2) { continue; }
// looking for ally
$ally = null;
$members = $game->getTeam1();
foreach($members as $member)
{
if($member->getName() != $this->getSc2Account())
{
$ally = $member;
break;
}
}
// updating hash table
$key = $ally->getName(). '_' . $ally->getRace();
if(!isset($teams[$key]))
{
$teams[$key] = array(
"allyName" => $ally->getName(),
"allyRace" => $ally->getRace(),
"wins" => 0,
"losses" => 0
);
}
if($game->getTeam1Result() == Game::RESULT_WIN) { $teams[$key]["wins"]++; }
if($game->getTeam1Result() == Game::RESULT_LOSS) { $teams[$key]["losses"]++; }
}
foreach($teams as $key => $team)
{
$teams[$key]["ratio"] = (($team["losses"] + $team["wins"]) == 0)
? 0
: round(100 * $team["wins"] / ($team["losses"] + $team["wins"]));
}
usort($teams, function($a, $b) {
if($a['wins'] == $b['wins'])
{
if($a['losses'] == $b['losses']) { return 0; }
return $a['losses'] > $b['losses'] ? 1 : -1;
}
return $a['wins'] < $b['wins'] ? 1 : -1;
});
return $teams;
}
public function setSc2Ranks(array $sc2ranks)
{
$this->sc2Ranks = serialize($sc2ranks);
}
public function getSc2Ranks()
{
return unserialize($this->sc2Ranks);
}
public function __toString() {
return $this->getSc2Account();
}
}
And i'm also meetin the same problem with the Constraint/Regex who is not auto-loaded or doesn't exists.Though i have all my doctrine bundles working.
My question is kinda simple : What i'm doing wrong? (I know it's not a very spécific one!)
The problem doesn't look to be with the #ORM\OrderBy({"id" = "DESC"}) annotation. That looks correct and you have included use Doctrine\ORM\Mapping as ORM;.
It looks like the problem has to do with the relationship between your SC2Profile entity and your GamePlayer entity. Are both these entities in the IHQS\NuitBlancheBundle\Entity namespace?
You could try updating the relationship to use the fully qualified class name.
/**
* #ORM\OneToMany(targetEntity="\IHQS\NuitBlancheBundle\Entity\GamePlayer", mappedBy="player")
* #ORM\OrderBy({"id" = "DESC"})
*/
protected $games;
Lastly, ensure that the opposite relationship (ManyToOne) has been setup in your GamePlayer entity.
/**
* #ORM\ManyToOne(targetEntity="SC2Profile", inversedBy="games")
* #ORM\JoinColumn(name="id", referencedColumnName="referenced_id")
*/
protected $player;
Related
I have a problem.. When I execute this code:
public function korisnici(){
$modelk = new Korisnici();
$upit = $modelk::find()->asArray()->orderBy('id DESC')->all();
$items = [];
foreach ($upit as $key => $value) {
foreach ($value as $kljuc => $vrijednost){
$items[] = [$kljuc => $vrijednost];
}
}
return $items;
}
private static $users = $this->korisnici();
It gives me this error: syntax error, unexpected '$this' (T_VARIABLE)..
Can someone help me, how can I call this function?
Here's my whole class:
class User extends \yii\base\Object implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
public $arr;
public function korisnici(){
$modelk = new Korisnici();
$upit = $modelk::find()->asArray()->orderBy('id DESC')->all();
$items = [];
foreach ($upit as $key => $value) {
foreach ($value as $kljuc => $vrijednost){
$items[] = [$kljuc => $vrijednost];
}
}
return $items;
}
public $users = $this->korisnici();
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
foreach (self::$users as $user) {
if ($user['accessToken'] === $token) {
return new static($user);
}
}
return null;
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
foreach (self::$users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
return null;
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->id;
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
}
I'm trying to change this default model from Yii Framework so I can login using database...
Looks like you have copied it from a class. The following will work like a regular function. Still not sure where you get $modelk = new Korisnici(); from
function korisnici(){
$modelk = new Korisnici();
$upit = $modelk::find()->asArray()->orderBy('id DESC')->all();
$items = [];
foreach ($upit as $key => $value) {
foreach ($value as $kljuc => $vrijednost){
$items[] = [$kljuc => $vrijednost];
}
}
return $items;
}
print_r(korisnici());
EDIT: After looking at your whole class:
You need to use the __construct method.
public function __construct()
{
$this->users = $this->korisnici();
}
Is it possible with laravel to retrieve a model property when using $queryBuilder->get() method ?
My database have weird naming convention (old app), and I have written one get*Attribute() method for each field, so I can access it by doing $model->prettyName, instead of $model->weird_Convention_Name, but when I use the $queryBuilder->get(), I get the database field, not the model properties.
Is there a way of doing this ?
EDIT
Here a sample of code:
Model
<?php
namespace Model\Day;
use Illuminate\Database\Eloquent\Builder;
/**
* Class Incomplete
* #package Model
* #subpackage Day
* #property string $alarm
* #property string $status
* #property string $mark1
* #property int $dayRate
* #property bool $isHalfDay
* #property bool $noPause
* #property bool $isTracked
* #property bool $noTime
* #property string $dayType
* #property string $shortDay
* #property \DateTime $date
* #property \DateTime $startDay
* #property \DateTime $startBreak
* #property \DateTime $endBreak
* #property \DateTime $startBreak2
* #property \DateTime $endBreak2
* #property \DateTime $endDay
* #property string $statusDescription
* #property string $subtype
* #property string $subcode
* #property string $description
* #property int $locationId
* #property string $locationDes
*
* #method \Eloquent currentUser()
*/
class Incomplete extends \Eloquent
{
/**
* The database table used by the model.
* #var string
*/
protected $table = 'vlogger_pending';
/**
* The primary key for the model.
* #var string
*/
protected $primaryKey = null;
/**
* The sequence name used for incrementing
* #var string
*/
protected $sequence = null;
/**
* Indicates if the IDs are auto-incrementing.
* #var bool
*/
public $incrementing = false;
/**
* Indicates if the model should be timestamped.
* #var bool
*/
public $timestamps = false;
/***********************************************************************
* SCOPES
***********************************************************************/
/**
* Add a where statement for current logged in user
* #param Builder $query
* #return Builder
*/
public function scopeCurrentUser(Builder $query)
{
return $query->where('usr_id', '=', \Auth::user()->id);
}
/***********************************************************************
* ACCESSORS
***********************************************************************/
public function getAlarmAttribute()
{
return $this->attributes['alarm'];
}
public function getStatusAttribute()
{
return $this->attributes['status'];
}
public function getMark1Attribute()
{
return $this->attributes['mark1'];
}
public function getDayRateAttribute()
{
return (int)$this->attributes['day_rate'];
}
public function getIsHalfDayAttribute()
{
return !!$this->attributes['half_day'];
}
public function getNoPauseAttribute()
{
return !!$this->attributes['no_pause'];
}
public function getIsTrackedAttribute()
{
return !!$this->attributes['tracked'];
}
public function getNoTimeAttribute()
{
return !!$this->attributes['no_hours'];
}
public function getDayTypeAttribute()
{
return $this->attributes['day_type'];
}
public function getShortDayAttribute()
{
return $this->attributes['dd'];
}
public function getDateAttribute()
{
$date = $this->attributes['day'];
if (null !== $date) {
$date = \DateTime::createFromFormat('U', strtotime($date));
}
return $date;
}
public function getStartDayAttribute()
{
$date = $this->attributes['dstart'];
if (null !== $date) {
$date = \DateTime::createFromFormat('U', strtotime($date));
}
return $date;
}
public function getStartBreakAttribute()
{
$date = $this->attributes['pstart'];
if (null !== $date) {
$date = \DateTime::createFromFormat('U', strtotime($date));
}
return $date;
}
public function getEndBreakAttribute()
{
$date = $this->attributes['pend'];
if (null !== $date) {
$date = \DateTime::createFromFormat('U', strtotime($date));
}
return $date;
}
public function getStartBreak2Attribute()
{
$date = $this->attributes['s_pstart2'];
if (null !== $date) {
$date = \DateTime::createFromFormat('U', strtotime($date));
}
return $date;
}
public function getEndBreak2Attribute()
{
$date = $this->attributes['s_pend2'];
if (null !== $date) {
$date = \DateTime::createFromFormat('U', strtotime($date));
}
return $date;
}
public function getEndDayAttribute()
{
$date = $this->attributes['dend'];
if (null !== $date) {
$date = \DateTime::createFromFormat('U', strtotime($date));
}
return $date;
}
public function getStatusDescriptionAttribute()
{
return $this->attributes['status_des'];
}
public function getSubtypeAttribute()
{
return $this->attributes['sub_type'];
}
public function getSubcodeAttribute()
{
return $this->attributes['sub_code'];
}
public function getDescriptionAttribute()
{
return $this->attributes['des'];
}
public function getLocationIdAttribute()
{
return (int)$this->attributes['location'];
}
public function getLocationDesAttribute()
{
return $this->attributes['location_des'];
}
/***********************************************************************
* MUTATORS
***********************************************************************/
public function setAlarmAttribute($value)
{
$this->attributes['alarm'] = $value;
return $this;
}
public function setStatusAttribute($value)
{
$this->attributes['status'] = $value;
return $this;
}
public function setMark1Attribute($value)
{
$this->attributes['mark1'] = $value;
return $this;
}
public function setDayRateAttribute($value)
{
$this->attributes['day_rate'] = $value;
return $this;
}
public function setIsHalfDayAttribute($value)
{
$this->attributes['half_day'] = $value;
return $this;
}
public function setNoPauseAttribute($value)
{
$this->attributes['no_pause'] = $value;
return $this;
}
public function setIsTrackedAttribute($value)
{
$this->attributes['tracked'] = $value;
return $this;
}
public function setNoTimeAttribute($value)
{
$this->attributes['no_hours'] = $value;
return $this;
}
public function setDayTypeAttribute($value)
{
$this->attributes['day_type'] = $value;
return $this;
}
public function setShortDayAttribute($value)
{
$this->attributes['dd'] = $value;
return $this;
}
public function setDateAttribute($value)
{
$this->attributes['day'] = $value;
return $this;
}
public function setStartDayAttribute($value)
{
$this->attributes['dstart'] = $value;
return $this;
}
public function setStartBreakAttribute($value)
{
$this->attributes['pstart'] = $value;
return $this;
}
public function setEndBreakAttribute($value)
{
$this->attributes['pend'] = $value;
return $this;
}
public function setStartBreak2Attribute($value)
{
$this->attributes['s_pstart2'] = $value;
return $this;
}
public function setEndBreak2Attribute($value)
{
$this->attributes['s_pend2'] = $value;
return $this;
}
public function setEndDayAttribute($value)
{
$this->attributes['dend'] = $value;
return $this;
}
public function setStatusDescriptionAttribute($value)
{
$this->attributes['status_des'] = $value;
return $this;
}
public function setSubtypeAttribute($value)
{
$this->attributes['sub_type'] = $value;
return $this;
}
public function setSubcodeAttribute($value)
{
$this->attributes['sub_code'] = $value;
return $this;
}
public function setDescriptionAttribute($value)
{
$this->attributes['des'] = $value;
return $this;
}
public function setLocationIdAttribute($value)
{
$this->attributes['location'] = $value;
return $this;
}
public function setLocationDesAttribute($value)
{
$this->attributes['location_des'] = $value;
return $this;
}
}
Controller
/**
* Get pending report for current logged user
* #return \Illuminate\Http\JsonResponse
*/
public function pendingReport()
{
return Response::json(Day\Incomplete::currentUser()->get());
}
Set $snakeAttributes in your model to false to use prettyName.
And use $appends to add formatted attribute when convert data to json.
class MyModel extends Eloquent {
public static $snakeAttributes = false;
protected $hidden = array('oldAttribute1', 'oldAttribute2');
protected $appends = array('attribute1', 'attribute2');
public function getAttribute1Attribute()
{
return 'Attribute1 Value';
}
public function getAttribute2Attribute()
{
return 'Attribute2 Value';
}
}
You can use "magick" __get():
private $aliases = array('
'prettyName' => 'weird_Convention_Name',
//...
');
public function __get($key)
{
if (!empty($this->aliases[$key]))
return parent::__get($this->aliases[$key]);
else
return parent::__get($key);
}
and always when you use $model->prettyName it return $model->weird_Convention_Name
I have installed a Magento Product Parts Interactive Diagram Extension in Magento CE 1.8.1.0.
The issue is it only renders one single Part Diagram per product. I need it to render all Diagrams for each product.
The code is :
public function getPartDiagram()
{
if ($this->getId()) {
return Mage::getModel('pws_productpartsdiagram/productpartsdiagram')->load($this->getId());
}
if (Mage::registry('product')) {
$collection = Mage::getModel('pws_productpartsdiagram/productpartsdiagram')->getCollection()
->addFieldToFilter('sku', Mage::registry('product')->getSku());
return $collection->getFirstItem();
}
return null;
}
If I return $collection->getLastItem(); it works and the last item is rendered on the front-end as expected.
But I cannot seem to get all items rendered, getItems does not work.
The code file is as follows, not sure but it might help.
<?php
/**
* Catalog product parts list block
*
* #category PWS
* #package ProductPartsDiagram
* #author Anda Bardeanu <info#pandawebstudio.com>
*/
class PWS_ProductPartsDiagram_Block_List extends Mage_Catalog_Block_Product_Abstract
{
protected $_productsCount = null;
const DEFAULT_PRODUCTS_COUNT = 5;
protected $_columnCount = 4;
protected $_items;
protected $_itemCollection;
protected $_itemLimits = array();
/**
* Initialize block's cache
*/
protected function _construct()
{
parent::_construct();
$this->addColumnCountLayoutDepend('empty', 6)
->addColumnCountLayoutDepend('one_column', 5)
->addColumnCountLayoutDepend('two_columns_left', 4)
->addColumnCountLayoutDepend('two_columns_right', 4)
->addColumnCountLayoutDepend('three_columns', 3);
$this->addData(array(
'cache_lifetime' => 86400,
'cache_tags' => array(Mage_Catalog_Model_Product::CACHE_TAG),
));
if (!$this->getData('template')) {
$this->setTemplate('pws_productpartsdiagram/list.phtml');
}
}
/**
* Get Key pieces for caching block content
*
* #return array
*/
public function getCacheKeyInfo()
{
return array(
'CATALOG_PRODUCT_PARTS_'.$this->getPartDiagram()->getId(),
Mage::app()->getStore()->getId(),
Mage::getDesign()->getPackageName(),
Mage::getDesign()->getTheme('template'),
Mage::getSingleton('customer/session')->getCustomerGroupId(),
'template' => $this->getTemplate(),
$this->getProductsCount()
);
}
/**
* Prepare collection with new products and applied page limits.
*
* return Mage_Catalog_Block_Product_New
*/
protected function _beforeToHtml()
{
$partDiagramId = -1;
$partDiagram = $this->getPartDiagram();
if ($partDiagram) {
$partDiagramId = $partDiagram->getId();
}
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());
$resource = Mage::getSingleton('core/resource');
$productsTable = $resource->getTableName('pws_productpartsdiagram_products');
// no pagination
$collection = $this->_addProductAttributesAndPrices($collection)
->addStoreFilter();
//->setPageSize($this->getProductsCount())
//->setCurPage(1);
$collection->getSelect()
->joinInner(
array('_table_products' => $productsTable),
'_table_products.product_id = e.entity_id',
array()
)
->from("", array('partdidagram_product_id'))
->where('_table_products.partdiagram_id = '. (int) $partDiagramId);
$this->setProductCollection($collection);
$this->_itemCollection = $collection;
return parent::_beforeToHtml();
}
/**
* Set how much product should be displayed at once.
*
* #param $count
* #return Mage_Catalog_Block_Product_New
*/
public function setProductsCount($count)
{
$this->_productsCount = $count;
return $this;
}
public function getPartDiagram()
{
if ($this->getId()) {
return Mage::getModel('pws_productpartsdiagram/productpartsdiagram')->load($this->getId());
}
if (Mage::registry('product')) {
$collection = Mage::getModel('pws_productpartsdiagram/productpartsdiagram')->getCollection()
->addFieldToFilter('sku', Mage::registry('product')->getSku());
return $collection->getFirstItem();
}
return null;
}
/**
* Get how much products should be displayed at once.
*
* #return int
*/
public function getProductsCount()
{
if (null === $this->_productsCount) {
$this->_productsCount = self::DEFAULT_PRODUCTS_COUNT;
}
return $this->_productsCount;
}
public function getItemCollection()
{
return $this->_itemCollection;
}
public function getItems()
{
if (is_null($this->_items)) {
$this->_items = $this->getItemCollection()->getItems();
}
return $this->_items;
}
public function getRowCount()
{
return ceil(count($this->getItemCollection()->getItems())/$this->getColumnCount());
}
public function setColumnCount($columns)
{
if (intval($columns) > 0) {
$this->_columnCount = intval($columns);
}
return $this;
}
public function getColumnCount()
{
return $this->_columnCount;
}
public function resetItemsIterator()
{
$this->getItems();
reset($this->_items);
}
public function getIterableItem()
{
$item = current($this->_items);
next($this->_items);
return $item;
}
/**
* Set how many items we need to show in block
* Notice: this parametr will be also applied
*
* #param string $type
* #param int $limit
* #return Mage_Catalog_Block_Product_List_Upsell
*/
public function setItemLimit($type, $limit)
{
if (intval($limit) > 0) {
$this->_itemLimits[$type] = intval($limit);
}
return $this;
}
public function getItemLimit($type = '')
{
if ($type == '') {
return $this->_itemLimits;
}
if (isset($this->_itemLimits[$type])) {
return $this->_itemLimits[$type];
}
else {
return 0;
}
}
}
I think you just want access to the collection of diagrams. So it might be simplest to add this code to your product view.phtml file:
$collection = Mage::getModel('pws_productpartsdiagram/productpartsdiagram')->getCollection()
->addFieldToFilter('sku', Mage::registry('product')->getSku());
foreach($collection as $productpartsdiagram){
//code to display each diagram
}
Alternatively extend the class which has public function getPartDiagram() in it and add your own function:
public function getPartDiagramsAll()
{
if (Mage::registry('product')) {
$collection = Mage::getModel('pws_productpartsdiagram/productpartsdiagram')->getCollection()
->addFieldToFilter('sku', Mage::registry('product')->getSku());
return $collection;
}
return null;
}
Call this function, then loop over the returned collection.
I'm studying ZendFramework2 Doctrine ORM, when I configure the source code ( MVC ) : classes , controllers. My application is about managing "Commande" and "Produit" , the issue is when I want to add a commande I have this Error :
Found entity of type Doctrine\Common\Collections\ArrayCollection on association
This is Commande.php :
class Commande {
/**
* #ORM\id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
protected $id;
/** #ORM\Column(type="string") */
protected $duree_commande;
/** #ORM\Column(type="string") */
protected $date_commande;
/**
* #ORM\ManyToOne(targetEntity="Produit", inversedBy="commandes",cascade={"persist"})
* #ORM\JoinColumn(name="produit_id", referencedColumnName="id")
*/
protected $produits;
public function __construct()
{
$this->produits = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getIdCommande()
{
return $this->id;
}
public function getDureeCommande()
{
return $this->duree_commande;
}
public function setIdCommande($id_commande)
{
$this->id = $id_commande;
}
public function setDureeCommande($duree_commande)
{
$this->duree_commande = $duree_commande;
}
public function getDateCommande()
{
return $this->date_commande;
}
public function setDateCommande($date_commande)
{
$this->date_commande = $date_commande;
}
public function getProduits()
{
return $this->produits;
}
public function addProduit($produit)
{
$this->produits->add($produit);
}
}
Produit.php :
class Produit {
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
protected $id;
/** #ORM\Column(type="string") */
protected $type_produit;
/** #ORM\OneToMany(targetEntity="Commande", mappedBy="produit", cascade={"persist"})
*/
protected $commande;
public function __construct()
{
$this->commandes = new \Doctrine\Common\Collections\ArrayCollection();
}
// getters/setters
public function getIdProduit()
{
return $this->id;
}
public function getTypeProduit()
{
return $this->type_produit;
}
public function setIdProduit($id_produit)
{
$this->id = $id_produit;
}
public function setTypeProduit($type_produit)
{
$this->type_produit = $type_produit;
}
function getCommande()
{
return $this->commande;
}
function setCommande(Commande $commande)
{
$commande->addProduit($this);
$this->commande = $commande;
}
}
I have this for Commande controller :
class CommandeController extends AbstractActionController
{
protected $em;
public function getEntityManager()
{
if (null === $this->em) {
$this->em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
}
return $this->em;
}
public function indexAction()
{
$em = $this->getEntityManager();
$commandes = $em->getRepository('Commande\Entity\Commande')->findAll();
return new ViewModel( array(
'commandes' => $commandes,
));
}
public function addAction()
{
if ($this->request->isPost()) {
$commande = new Commande();
$commande->setDureeCommande($this->getRequest()->getPost('dureeCommande'));
$commande->setDateCommande($this->getRequest()->getPost('dateCommande'));
$this->getEntityManager()->persist($commande);
$this->getEntityManager()->flush();
$newId = $commande->getIdCommande();
return $this->redirect()->toRoute('commande');
}
return new ViewModel();
}
public function editAction()
{
/* $objectManager = $this->getServiceLocator()
->get('Doctrine\ORM\EntityManager');
$commande = $objectManager->find('Commande\Entity\Commande', 13);
$commande->setDureeCommandes('Guilherme Blanco');
$objectManager->flush();
die(var_dump($commande->getIdCommande()));*/
$id = (int) $this->params()->fromRoute('id', 0);
$commande = $this->getEntityManager()->find('\Commande\Entity\Commande', $id);
if ($this->request->isPost()) {
$commande->setDureeCommande($this->getRequest()->getPost('dureeCommande'));
$commande->setDateCommande($this->getRequest()->getPost('dateCommande'));
$this->getEntityManager()->persist($commande);
$this->getEntityManager()->flush();
return $this->redirect()->toRoute('home');
}
return new ViewModel(array('commande' => $commande));
}
public function deleteAction()
{
/* $objectManager = $this->getServiceLocator()
->get('Doctrine\ORM\EntityManager');
$commande = $objectManager->find('Commande\Entity\Commande', 14);
$objectManager->remove($commande);
$objectManager->flush();
die(var_dump($commande->getIdCommande()));*/
$id = (int) $this->params()->fromRoute('id', 0);
$commande = $this->getEntityManager()->find('\Commande\Entity\Commande', $id);
if ($this->request->isPost()) {
$Produits = $commande->getProduits();
if (count($Produits)>1)
{
foreach ($Produits as $produit) {
$this->getEntityManager()->remove($produit);
}
}
$this->getEntityManager()->remove($commande);
$this->getEntityManager()->flush();
return $this->redirect()->toRoute('home');
}
return new ViewModel(array('commande' => $commande));
}
public function getCommandeTable()
{
}
}
and this for Produit Controller :
class ProduitController extends AbstractActionController
{
protected $em;
public function getEntityManager()
{
if (null === $this->em) {
$this->em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
}
return $this->em;
}
public function indexAction()
{
$em = $this->getEntityManager();
$produits = $em->getRepository('Commande\Entity\Produit')->findAll();
return new ViewModel( array(
'produits' => $produits,
));
}
public function addAction()
{
/*$objectManager = $this
->getServiceLocator()
->get('Doctrine\ORM\EntityManager');
$commande = $objectManager->find('Commande\Entity\Commande',13);
$produit = new \Commande\Entity\Produit();
$produit->setTitleProduit('commande13');
$produit->setCommande($commande);
$objectManager->persist($produit);
$objectManager->flush();
var_dump($commande->getTitleCommande());*/
$id = (int) $this->params()->fromRoute('id', 0);
$commande = $this->getEntityManager()->find('\Commande\Entity\Commande', $id);
if ($this->request->isPost()) {
$produit = new Produit();
$produit->setTypeProduit($this->getRequest()->getPost('typeProduit'));
$produit->setCommande($commande);
$this->getEntityManager()->persist($produit);
$this->getEntityManager()->flush();
return $this->redirect()->toRoute('home');
}
return new ViewModel(array('commande' => $commande));
}
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
$produit = $this->getEntityManager()->find('\Commande\Entity\Produit', $id);
if ($this->request->isPost()) {
$produit->setTypeProduit($this->getRequest()->getPost('typeProduit'));
$this->getEntityManager()->persist($produit);
$this->getEntityManager()->flush();
return $this->redirect()->toRoute('produit');
}
return new ViewModel(array('produit' => $produit));
}
public function deleteAction()
{
/* $em = $this
->getServiceLocator()
->get('Doctrine\ORM\EntityManager');
$commande = $em->find('Commande\Entity\Commande', 5);
if($commande)
{
echo 'Found an Commande\Entity\Commande: ' . PHP_EOL
. $commande->getIdCommande() . ' => ' . $commande->getTitleCommande() . '(' . get_class($commande) . ')' . PHP_EOL
. 'and ' . $commande->getProduits()->count() . ' Commande\Entity\Produit attached to it: ' . PHP_EOL;
if($produit = $commande->getProduits()->first())
{
echo 'Removing the first attached comment!' . PHP_EOL;
echo 'Removing comment with id=' . $produit->getIdProduit() . PHP_EOL;
$em->remove($produit);
$em->flush();
} else {
echo 'Could not find any comments to remove...' . PHP_EOL;
}
}
else
{
echo 'Could not find Commande\Entity\Commande with id=5';
}*/
$id = (int) $this->params()->fromRoute('id', 0);
$produit = $this->getEntityManager()->find('\Commande\Entity\Produit', $id);
if ($this->request->isPost()) {
$this->getEntityManager()->remove($produit);
$this->getEntityManager()->flush();
return $this->redirect()->toRoute('produit');
}
return new ViewModel(array('produit' => $produit));
}
public function getProduitTable()
{
}
}
Thanks for helping me.
If you need other information about my application tell me .
I am having a model and would need to update the record. every time $count ($count = $post->save()) is being NULL. how is it possible to know whether this record saved or not. if saved, i want to display the following message 'Post updated' and if not the other message 'Post cannot update'.
This is always going to the else port. how can i know model updated correctly or not?
$post = new Application_Model_Post($form->getValues());
$post->setId($id);
$count = $post->save();
//var_dump($count); exit;
if ($count > 0) {
$this->_helper->flashMessenger->addMessage('Post updated');
} else {
$this->_helper->flashMessenger->addMessage('Post cannot update');
}
Application_Model_Post code is as below,
class Application_Model_Post
{
/**
* #var int
*/
protected $_id;
/**
* #var string
*/
protected $_title;
/**
* #var string
*/
protected $_body;
/**
* #var string
*/
protected $_created;
/**
* #var string
*/
protected $_updated;
/**
* #var Application_Model_PostMapper
*/
protected $_mapper;
/**
* Class Constructor.
*
* #param array $options
* #return void
*/
public function __construct(array $options = null)
{
if (is_array($options)) {
$this->setOptions($options);
}
}
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key=> $value) {
$method = 'set'.ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
public function setId($id)
{
$this->_id = $id;
return $this;
}
public function getId()
{
return $this->_id;
}
public function setTitle($title)
{
$this->_title = (string) $title;
return $this;
}
public function getTitle()
{
return $this->_title;
}
public function setBody($body)
{
$this->_body = $body;
return $this;
}
public function getBody()
{
return $this->_body;
}
public function setCreated($ts)
{
$this->_created = $ts;
return $this;
}
public function getCreated()
{
return $this->_created;
}
/**
* Set data mapper.
*
* #param mixed $mapper
* #return Application_Model_Post
*/
public function setMapper($mapper)
{
$this->_mapper = $mapper;
return $this;
}
/**
* Get data mapper.
*
* Lazy loads Application_Model_PostMapper instance if no mapper
* registered.
*
* #return Application_Model_PostMapper
*/
public function getMapper()
{
if (null === $this->_mapper) {
$this->setMapper(new Application_Model_PostMapper());
}
return $this->_mapper;
}
/**
* Save the current post.
*
* #return void
*/
public function save()
{
$this->getMapper()->save($this);
}
public function getPost($id)
{
return $this->getMapper()->getPost($id);
}
/**
* Update the current post.
*
* #return void
*/
public function update($data, $where)
{
$this->getMapper()->update($data, $where);
}
/**
* Find a post.
*
* Resets entry state if matching id found.
*
* #param int $id
* #return Application_Model_Post
*/
public function find($id)
{
$this->getMapper()->find($id, $this);
return $this;
}
/**
* Fetch all posts.
*
* #return array
*/
public function fetchAll()
{
return $this->getMapper()->fetchAll();
}
}
getMapper refers to the class Application_Model_PostMapper.
class Application_Model_PostMapper
{
public function save(Application_Model_Post $post)
{
$data = array(
'title'=>$post->getTitle(),
'body'=>$post->getBody(),
'created'=>$post->getCreated()
);
if (null === ($id = $post->getId())) {
unset($data['id']);
$data['created'] = date('Y-m-d H:i:s');
$post->setId($this->getDbTable()->insert($data));
} else {
$this->getDbTable()->update($data, array('id = ?'=>$id));
}
}
public function getDbTable()
{
if (null === $this->_dbTable) {
$this->setDbTable('Application_Model_DbTable_Post');
}
return $this->_dbTable;
}
}
Class of Application_Model_DbTable_Post
class Application_Model_DbTable_Post extends Zend_Db_Table_Abstract
{
protected $_name = 'posts';
}
Let me know if anything is incorrect. i am a newbie to zend and did thsi while referring the zend site. http://framework.zend.com/manual/1.12/en/learning.quickstart.create-model.html
you can extend your script like this. zend dbtable triggers the Zend_Db_Exception on any error during any insert or update.
class Application_Model_PostMapper
{
public function save(Application_Model_Post $post)
{
$data = array(
'title'=>$post->getTitle(),
'body'=>$post->getBody(),
'created'=>$post->getCreated()
);
try {
if (null === ($id = $post->getId())) {
unset($data['id']);
$data['created'] = date('Y-m-d H:i:s');
$post->setId($this->getDbTable()->insert($data));
} else {
$this->getDbTable()->update($data, array('id = ?'=>$id));
}
} catch (Zend_Db_Exception $e) {
// error thrown by dbtable class
return $e->getMessage();
}
// no error
return true;
}
}
now you can check like this
$post = new Application_Model_Post($form->getValues());
$post->setId($id);
$isSaved = $post->save();
if ($isSaved === true) {
$this->_helper->flashMessenger->addMessage('Post updated');
} else {
// error
// $isSaved holds the error message
$this->_helper->flashMessenger->addMessage('Post cannot update');
}