yii2 find returns null - php

Why does findone() returns all public property as null.
class User extends \yii\db\ActiveRecord
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
$result = static::findOne(['username' => $username]);
var_dump($result);
return $result;
}
This returns
object(app\models\User)[81]
public 'id' => null
public 'username' => null
public 'password' => null
public 'authKey' => null
public 'accessToken' => null
private '_attributes' (yii\db\BaseActiveRecord) =>
array (size=6)
'id' => int 1
'username' => string 'admin' (length=5)
'password' => string '123456' (length=6)
'auth_key' => string 'jkkk' (length=4)
'created' => null
'modified' => null

You should simply remove db attributes from your model :
class User extends \yii\db\ActiveRecord
{
public static function findByUsername($username)
{
....
Yii automatically defines an attribute in Active Record for every column of the associated table. You should NOT redeclare any of the attributes.
Read more : http://www.yiiframework.com/doc-2.0/guide-db-active-record.html

Related

How to mysqli_result::fetch_array with key [table.attribute] in the array?

I'm trying to create a general method to automatically instantiate objects from a query like this:
SELECT town.*, content.*, user.*
FROM townhub.content
LEFT JOIN town ON content.townReceiver = town.id_town
LEFT JOIN user ON content.author = user.id_user
The method that I want to build should return 3 type of objects: Town, User and Content into an array. I thought on something like that:
protected function build_objects($result, Array $classes) {
$data = array();
$i = 0;
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
foreach ($classes as $class) {
$$class = new $class;
$$class = $$class->fill_object($$class, $row);
$data[$i][$class] = $$class;
}
$i++;
}
return $data;
}
And then, in each class, a method like that:
public function fill_object($object, Array $row) {
$attributes = get_object_vars($object);
foreach ($row as $attribute => $value) {
foreach ($attributes as $objAtt => $emptyValue) {
if ($attribute == $objAtt) {
$object->$attribute = $value;
}
}
}
return $object;
}
Actually, this is doing what I want, the following array (was printed using using var_dump($data) in build_objects() ):
array (size=4)
0 =>
array (size=3)
'Content' =>
object(Content)[4]
protected 'id_content' => string '1' (length=1)
public 'title' => string 'Hello World!' (length=10)
public 'description' => string 'Hello world description' (length=43)
public 'category' => string '1' (length=1)
public 'date' => string '2015-01-01' (length=10)
public 'townReceiver' => string '1' (length=1)
public 'author' => string '1' (length=1)
private 'dbHost' (Model) => string 'localhost' (length=9)
private 'dbUser' (Model) => string 'root' (length=4)
private 'dbPass' (Model) => string 'root' (length=4)
private 'dbName' (Model) => string 'townhub' (length=7)
private 'conn' (Model) => null
'Town' =>
object(Town)[5]
protected 'id_town' => string '1' (length=1)
public 'name' => string 'Isaac' (length=5)
public 'population' => string '750' (length=3)
private 'dbHost' (Model) => string 'localhost' (length=9)
private 'dbUser' (Model) => string 'root' (length=4)
private 'dbPass' (Model) => string 'root' (length=4)
private 'dbName' (Model) => string 'townhub' (length=7)
private 'conn' (Model) => null
'User' =>
object(User)[6]
protected 'id_user' => string '1' (length=1)
protected 'dni' => string '20011225' (length=9)
private 'password' => string '1234' (length=4)
public 'name' => string 'Isaac' (length=5)
public 'firstSurname' => string 'Surname1' (length=5)
public 'secondSurname' => string 'Surname2' (length=5)
public 'birthdate' => string '0000-00-00' (length=10)
public 'gender' => string 'H' (length=1)
public 'email' => string 'isaac#mail.com' (length=19)
public 'isAdmin' => string '1' (length=1)
public 'id_town' => string '1' (length=1)
private 'dbHost' (Model) => string 'localhost' (length=9)
private 'dbUser' (Model) => string 'root' (length=4)
private 'dbPass' (Model) => string 'root' (length=4)
private 'dbName' (Model) => string 'townhub' (length=7)
private 'conn' (Model) => null
The problem is that when I fech_array (in fill_object() method) town's names are overridden by user's names; so I can't get the town's name. The easy solution is to change attribute's names on db and classes; but I think that will be a bad solution...
Keep in mind that attribute's names should be equals on db and classes, so alias in the query is not possible.
There are any way to get with fetch_array an Array with key [table.attribute] instead [attribute]?
I would also like to know better ways to do this if what I want to do is not possible.
<?php
class DataCollectionHelper
{
/**
* $result var is the result of:
* "SELECT *
* FROM townhub.content".
*
* As you left join your tables, it may appear that you haven't any towns and users
* for particular content.
*
* #param $result
*
* #return array
*/
protected function build_objects($result)
{
$data = array();
$i = 0;
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$contentObject = new Content();
$contentObject->fill_object($row);
$data[$i]['Content'] = $contentObject;
$data[$i]['User'] = $this->getUserByContentAuthor($contentObject->getAuthor());
$data[$i]['Town'] = $this->getTownByContentByTownReceiver($contentObject->getTownReceiver());
$i++;
}
return $data;
}
/**
* #param integer $townReceiver
*
* #return Town
*/
private function getTownByContentByTownReceiver($townReceiver)
{
/**
* Here you have to get town data by your $townReceiver - property
* and return the object of Town
*/
}
/**
* #param integer $author
*
* #return User
*/
private function getUserByContentAuthor($author)
{
/**
* The same here for users
*/
}
}
class Content
{
/**
* #var integer
*/
protected $content_id;
/**
* #var string
*/
public $title;
/**
* #var integer
*/
public $townReceiver;
/**
* #var string
*/
public $description;
/**
* #var integer
*/
public $author;
/* other vars */
/**
* #param array $row
*
* #return $this
*/
public function fill_object(array $row)
{
/*
* It's not the best approach, to do like that.
* It's better to use setters or just set your properties
* $this->title = $row['title']; etc
*
* Still you could use $this instead of your $object variable
*/
$attributes = get_object_vars($this);
foreach ($row as $attribute => $value) {
foreach ($attributes as $objAtt => $emptyValue) {
if ($attribute == $objAtt) {
$this->$attribute = $value;
}
}
}
return $this;
}
/**
* #return int
*/
public function getTownReceiver()
{
return $this->townReceiver;
}
/**
* #return int
*/
public function getAuthor()
{
return $this->author;
}
}

Many To Many Relation Key "articles" for array with keys "0, 1" does not exist in ::FrontEnd\devis.html.twig at line 35

I am working on a project and I am blocked in the association ManyToMany. I have an entity called Devis(in eng quotation) and an entity called articles. the problem is when I would like to display the articles of a specific quotation, it doesn't work.
here is the Devis Entity:
<?php
namespace DevisBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Devis
*
* #ORM\Table(name="devis")
* #ORM\Entity(repositoryClass="DevisBundle\Repository\DevisRepository")
*/
class Devis {
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
//les relations
/**
* #ORM\ManyToOne(targetEntity="UserBundle\Entity\User", inversedBy="devis_user", cascade={"persist"})
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
/**
* #ORM\ManyToOne(targetEntity="UserBundle\Entity\User", inversedBy="devis_enterprise")
* #ORM\JoinColumn(name="enterprise_id", referencedColumnName="id")
*/
private $enterprise;
/**
* #ORM\ManyToMany(targetEntity="ArticleBundle\Entity\Article", mappedBy="devis")
*/
private $articles;
public function __construct() {
$this->articles = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId() {
return $this->id;
}
/**
* Set user
*
* #param \UserBundle\Entity\User $user
* #return Devis
*/
public function setUser(\UserBundle\Entity\User $user = null) {
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \UserBundle\Entity\User
*/
public function getUser() {
return $this->user;
}
/**
* Set enterprise
*
* #param \UserBundle\Entity\User $enterprise
* #return Devis
*/
public function setEnterprise(\UserBundle\Entity\User $enterprise = null) {
$this->enterprise = $enterprise;
return $this;
}
/**
* Get enterprise
*
* #return \UserBundle\Entity\User
*/
public function getEnterprise() {
return $this->enterprise;
}
/**
* Add articles
*
* #param \ArticleBundle\Entity\Article $articles
* #return Devis
*/
public function addArticle(\ArticleBundle\Entity\Article $article) {
$article->addDevi($this);
$this->articles[] = $article;
return $this;
}
/**
* Remove articles
*
* #param \ArticleBundle\Entity\Article $articles
*/
public function removeArticle(\ArticleBundle\Entity\Article $articles) {
$this->articles->removeElement($articles);
}
/**
* Get articles
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getArticles() {
return $this->articles;
}
}
Article Entity
<?php
namespace ArticleBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Article
*
* #ORM\Table(name="article")
* #ORM\Entity(repositoryClass="ArticleBundle\Repository\ArticleRepository")
*/
class Article
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=true)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=255, nullable=true)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="prix", type="string", length=255, nullable=true)
*/
private $prix;
//les relations
/**
* #ORM\ManyToMany(targetEntity="DevisBundle\Entity\Devis", inversedBy="articles")
* #ORM\JoinTable(name="articles_devis")
*/
private $devis;
/**
* #ORM\ManyToOne(targetEntity="UserBundle\Entity\User", inversedBy="articles")
* #ORM\JoinColumn(name="utilisateur_id", referencedColumnName="id")
*/
private $entreprise;
/**
* #ORM\ManyToOne(targetEntity="CategoryBundle\Entity\Category", inversedBy="articles")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $category;
public function __construct() {
$this->devis = new \Doctrine\Common\Collections\ArrayCollection();
}
public function __toString() {
return $this->name;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Article
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return Article
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set prix
*
* #param string $prix
* #return Article
*/
public function setPrix($prix)
{
$this->prix = $prix;
return $this;
}
/**
* Get prix
*
* #return string
*/
public function getPrix()
{
return $this->prix;
}
/**
* Set entreprise
*
* #param \UserBundle\Entity\User $entreprise
* #return Article
*/
public function setEntreprise(\UserBundle\Entity\User $entreprise = null)
{
$this->entreprise = $entreprise;
return $this;
}
/**
* Get entreprise
*
* #return \UserBundle\Entity\User
*/
public function getEntreprise()
{
return $this->entreprise;
}
/**
* Set category
*
* #param \CategoryBundle\Entity\Category $category
* #return Article
*/
public function setCategory(\CategoryBundle\Entity\Category $category = null)
{
$this->category = $category;
return $this;
}
/**
* Get category
*
* #return \CategoryBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
/**
* Add devis
*
* #param \DevisBundle\Entity\Devis $devis
* #return Article
*/
public function addDevi(\DevisBundle\Entity\Devis $devis)
{
$devis->addArticle($this);
$this->devis[] = $devis;
return $this;
}
/**
* Remove devis
*
* #param \DevisBundle\Entity\Devis $devis
*/
public function removeDevi(\DevisBundle\Entity\Devis $devis)
{
$this->devis->removeElement($devis);
}
/**
* Get devis
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDevis()
{
return $this->devis;
}
}
Controller
<?php
namespace DevisBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\RedirectResponse;
use DevisBundle\Entity\Devis;
use UserBundle\Entity\User;
class DevisController extends Controller {
/**
*
* #Route("/devis/{user_id}", name="devis")
* #Method("GET")
*/
public function devisAction($user_id) {
$em = $this->getDoctrine()->getManager();
$entreprise = new User();
$mes_devis = new Devis();
$enterprises = new \Doctrine\Common\Collections\ArrayCollection();
$user = $this->get('security.context')->getToken()->getUser();
$mes_devis = $em->getRepository('DevisBundle:Devis')->devisByUser($user_id);
$categories = $em->getRepository('CategoryBundle:Category')->findAll();
return $this->render('::FrontEnd/devis.html.twig', array(
'user' => $user,
'categories' => $categories,
'mes_devis' => $mes_devis,
));
}
}
The Devis.html.twig
<div class="cart_main">
<h2>Mes devis ({{ mes_devis|length }})</h2>
{% for devis in mes_devis %}
<div class="container">
<div class="cart-items">
<h4>Entreprise : {{ devis.enterprise }}</h4>
<script>$(document).ready(function (c) {
$('.close1').on('click', function (c) {
$('.cart-header').fadeOut('slow', function (c) {
$('.cart-header').remove();
});
});
});
</script>
{% for article in mes_devis.articles %}
<div class="cart-header">
<div class="close1"> </div>
<div class="cart-sec">
<div class="cart-item cyc">
<img src="{{ asset ('bundles/theme_front_end/images/ts4.jpg') }}"/>
</div>
<div class="cart-item-info">
<h3>Mast & Harbour<span>Model No: 3578</span></h3>
<h4><span>Rs. $ </span>150.00</h4>
<p class="qty">Qty ::</p>
<input min="1" type="number" id="quantity" name="quantity" value="1" class="form-control input-small">
</div>
<div class="clearfix"></div>
<div class="delivery">
<p>Service Charges:: Rs.50.00</p>
</div>
</div>
</div>
<script>$(document).ready(function (c) {
$('.close2').on('click', function (c) {
$('.cart-header2').fadeOut('slow', function (c) {
$('.cart-header2').remove();
});
});
});
</script>
{% endfor %}
</div>
<div class="cart-total">
<a class="continue" href="#">Continue to basket</a>
<div class="price-details">
<h3>Price Details</h3>
<span>Total</span>
<span class="total">350.00</span>
<span>Discount</span>
<span class="total">---</span>
<span>Delivery Charges</span>
<span class="total">100.00</span>
<div class="clearfix"></div>
</div>
<h4 class="last-price">TOTAL</h4>
<span class="total final">450.00</span>
<div class="clearfix"></div>
<a class="order" href="#">Place Order</a>
<div class="total-item">
<h3>OPTIONS</h3>
<h4>COUPONS</h4>
<a class="cpns" href="#">Apply Coupons</a>
<p>Log In to use accounts - linked coupons</p>
</div>
</div>
</div>
<div class="clearfix"></div>
{% endfor %}
</div>
and the errors is:
Key "articles" for array with keys "0, 1" does not exist in ::FrontEnd\devis.html.twig at line 35
when I do var_dump($mes_devis) I got
array (size=2)
0 =>
object(DevisBundle\Entity\Devis)[1024]
private 'id' => int 7
private 'isConfirmed' => boolean false
private 'articleadded' => null
private 'user' =>
object(UserBundle\Entity\User)[856]
protected 'id' => int 5
private 'nom' => string 'kamel' (length=5)
private 'prenom' => string 'bouslama' (length=8)
private 'date_naissance' => string '14/10/1992' (length=10)
private 'sexe' => string 'Homme' (length=5)
private 'mobile' => string '50966301' (length=8)
private 'ville' => string 'monastir' (length=8)
private 'site_web' => string 'www.rochdi.com' (length=14)
private 'logo_entreprise' => null
private 'raison_social_entreprise' => null
private 'denomination_entreprise' => null
private 'slogan_entreprise' => null
private 'presentation_entreprise' => null
private 'code_postal_entreprise' => null
private 'longitude_entreprise' => null
private 'laltitude_entreprise' => null
private 'registre_commerce_entreprise' => null
private 'date_creation_entreprise' => null
private 'effectif_entreprise' => null
private 'capital_social_entreprise' => null
private 'fax_entreprise' => null
private 'pack_commercial_entreprise' => null
private 'nom_entreprise' => null
private 'adresse' => string 'Adresse' (length=7)
private 'articles' =>
object(Doctrine\ORM\PersistentCollection)[881]
...
private 'devis_user' =>
object(Doctrine\ORM\PersistentCollection)[904]
...
private 'devis_enterprise' =>
object(Doctrine\ORM\PersistentCollection)[906]
...
protected 'username' => string 'kamel' (length=5)
protected 'usernameCanonical' => string 'kamel' (length=5)
protected 'email' => string 'kamel#gmail.com' (length=15)
protected 'emailCanonical' => string 'kamel#gmail.com' (length=15)
protected 'enabled' => boolean true
protected 'salt' => string 'koikc9294lws8wgwgo8ss4owg84swg8' (length=31)
protected 'password' => string '$2y$13$koikc9294lws8wgwgo8ssu.9zbRplUObbvJEIyuVZvbE9VnateEOi' (length=60)
protected 'plainPassword' => null
protected 'lastLogin' =>
object(DateTime)[854]
...
protected 'confirmationToken' => null
protected 'passwordRequestedAt' => null
protected 'groups' => null
protected 'locked' => boolean false
protected 'expired' => boolean false
protected 'expiresAt' => null
protected 'roles' =>
array (size=1)
...
protected 'credentialsExpired' => boolean false
protected 'credentialsExpireAt' => null
private 'enterprise' =>
object(Proxies\__CG__\UserBundle\Entity\User)[1122]
public '__initializer__' =>
object(Closure)[1023]
...
public '__cloner__' =>
object(Closure)[1022]
...
public '__isInitialized__' => boolean false
protected 'id' => string '6' (length=1)
private 'nom' (UserBundle\Entity\User) => null
private 'prenom' (UserBundle\Entity\User) => null
private 'date_naissance' (UserBundle\Entity\User) => null
private 'sexe' (UserBundle\Entity\User) => null
private 'mobile' (UserBundle\Entity\User) => null
private 'ville' (UserBundle\Entity\User) => null
private 'site_web' (UserBundle\Entity\User) => null
private 'logo_entreprise' (UserBundle\Entity\User) => null
private 'raison_social_entreprise' (UserBundle\Entity\User) => null
private 'denomination_entreprise' (UserBundle\Entity\User) => null
private 'slogan_entreprise' (UserBundle\Entity\User) => null
private 'presentation_entreprise' (UserBundle\Entity\User) => null
private 'code_postal_entreprise' (UserBundle\Entity\User) => null
private 'longitude_entreprise' (UserBundle\Entity\User) => null
private 'laltitude_entreprise' (UserBundle\Entity\User) => null
private 'registre_commerce_entreprise' (UserBundle\Entity\User) => null
private 'date_creation_entreprise' (UserBundle\Entity\User) => null
private 'effectif_entreprise' (UserBundle\Entity\User) => null
private 'capital_social_entreprise' (UserBundle\Entity\User) => null
private 'fax_entreprise' (UserBundle\Entity\User) => null
private 'pack_commercial_entreprise' (UserBundle\Entity\User) => null
private 'nom_entreprise' (UserBundle\Entity\User) => null
private 'adresse' (UserBundle\Entity\User) => null
private 'articles' (UserBundle\Entity\User) => null
private 'devis_user' (UserBundle\Entity\User) => null
private 'devis_enterprise' (UserBundle\Entity\User) => null
protected 'username' => null
protected 'usernameCanonical' => null
protected 'email' => null
protected 'emailCanonical' => null
protected 'enabled' => null
protected 'salt' => null
protected 'password' => null
protected 'plainPassword' => null
protected 'lastLogin' => null
protected 'confirmationToken' => null
protected 'passwordRequestedAt' => null
protected 'groups' => null
protected 'locked' => null
protected 'expired' => null
protected 'expiresAt' => null
protected 'roles' => null
protected 'credentialsExpired' => null
protected 'credentialsExpireAt' => null
private 'articles' =>
object(Doctrine\ORM\PersistentCollection)[1121]
private 'snapshot' =>
array (size=0)
...
private 'owner' =>
&object(DevisBundle\Entity\Devis)[1024]
private 'association' =>
array (size=16)
...
private 'em' =>
object(Doctrine\ORM\EntityManager)[686]
...
private 'backRefFieldName' => string 'devis' (length=5)
private 'typeClass' =>
object(Doctrine\ORM\Mapping\ClassMetadata)[857]
...
private 'isDirty' => boolean false
private 'initialized' => boolean false
private 'coll' =>
object(Doctrine\Common\Collections\ArrayCollection)[1120]
...
1 =>
object(DevisBundle\Entity\Devis)[1119]
private 'id' => int 8
private 'isConfirmed' => boolean false
private 'articleadded' => null
private 'user' =>
object(UserBundle\Entity\User)[856]
protected 'id' => int 5
private 'nom' => string 'kamel' (length=5)
private 'prenom' => string 'bouslama' (length=8)
private 'date_naissance' => string '14/10/1992' (length=10)
private 'sexe' => string 'Homme' (length=5)
private 'mobile' => string '50966301' (length=8)
private 'ville' => string 'monastir' (length=8)
private 'site_web' => string 'www.rochdi.com' (length=14)
private 'logo_entreprise' => null
private 'raison_social_entreprise' => null
private 'denomination_entreprise' => null
private 'slogan_entreprise' => null
private 'presentation_entreprise' => null
private 'code_postal_entreprise' => null
private 'longitude_entreprise' => null
private 'laltitude_entreprise' => null
private 'registre_commerce_entreprise' => null
private 'date_creation_entreprise' => null
private 'effectif_entreprise' => null
private 'capital_social_entreprise' => null
private 'fax_entreprise' => null
private 'pack_commercial_entreprise' => null
private 'nom_entreprise' => null
private 'adresse' => string 'Adresse' (length=7)
private 'articles' =>
object(Doctrine\ORM\PersistentCollection)[881]
...
private 'devis_user' =>
object(Doctrine\ORM\PersistentCollection)[904]
...
private 'devis_enterprise' =>
object(Doctrine\ORM\PersistentCollection)[906]
...
protected 'username' => string 'kamel' (length=5)
protected 'usernameCanonical' => string 'kamel' (length=5)
protected 'email' => string 'kamel#gmail.com' (length=15)
protected 'emailCanonical' => string 'kamel#gmail.com' (length=15)
protected 'enabled' => boolean true
protected 'salt' => string 'koikc9294lws8wgwgo8ss4owg84swg8' (length=31)
protected 'password' => string '$2y$13$koikc9294lws8wgwgo8ssu.9zbRplUObbvJEIyuVZvbE9VnateEOi' (length=60)
protected 'plainPassword' => null
protected 'lastLogin' =>
object(DateTime)[854]
...
protected 'confirmationToken' => null
protected 'passwordRequestedAt' => null
protected 'groups' => null
protected 'locked' => boolean false
protected 'expired' => boolean false
protected 'expiresAt' => null
protected 'roles' =>
array (size=1)
...
protected 'credentialsExpired' => boolean false
protected 'credentialsExpireAt' => null
private 'enterprise' =>
object(Proxies\__CG__\UserBundle\Entity\User)[1118]
public '__initializer__' =>
object(Closure)[1023]
...
public '__cloner__' =>
object(Closure)[1022]
...
public '__isInitialized__' => boolean false
protected 'id' => string '8' (length=1)
private 'nom' (UserBundle\Entity\User) => null
private 'prenom' (UserBundle\Entity\User) => null
private 'date_naissance' (UserBundle\Entity\User) => null
private 'sexe' (UserBundle\Entity\User) => null
private 'mobile' (UserBundle\Entity\User) => null
private 'ville' (UserBundle\Entity\User) => null
private 'site_web' (UserBundle\Entity\User) => null
private 'logo_entreprise' (UserBundle\Entity\User) => null
private 'raison_social_entreprise' (UserBundle\Entity\User) => null
private 'denomination_entreprise' (UserBundle\Entity\User) => null
private 'slogan_entreprise' (UserBundle\Entity\User) => null
private 'presentation_entreprise' (UserBundle\Entity\User) => null
private 'code_postal_entreprise' (UserBundle\Entity\User) => null
private 'longitude_entreprise' (UserBundle\Entity\User) => null
private 'laltitude_entreprise' (UserBundle\Entity\User) => null
private 'registre_commerce_entreprise' (UserBundle\Entity\User) => null
private 'date_creation_entreprise' (UserBundle\Entity\User) => null
private 'effectif_entreprise' (UserBundle\Entity\User) => null
private 'capital_social_entreprise' (UserBundle\Entity\User) => null
private 'fax_entreprise' (UserBundle\Entity\User) => null
private 'pack_commercial_entreprise' (UserBundle\Entity\User) => null
private 'nom_entreprise' (UserBundle\Entity\User) => null
private 'adresse' (UserBundle\Entity\User) => null
private 'articles' (UserBundle\Entity\User) => null
private 'devis_user' (UserBundle\Entity\User) => null
private 'devis_enterprise' (UserBundle\Entity\User) => null
protected 'username' => null
protected 'usernameCanonical' => null
protected 'email' => null
protected 'emailCanonical' => null
protected 'enabled' => null
protected 'salt' => null
protected 'password' => null
protected 'plainPassword' => null
protected 'lastLogin' => null
protected 'confirmationToken' => null
protected 'passwordRequestedAt' => null
protected 'groups' => null
protected 'locked' => null
protected 'expired' => null
protected 'expiresAt' => null
protected 'roles' => null
protected 'credentialsExpired' => null
protected 'credentialsExpireAt' => null
private 'articles' =>
object(Doctrine\ORM\PersistentCollection)[1117]
private 'snapshot' =>
array (size=0)
...
private 'owner' =>
&object(DevisBundle\Entity\Devis)[1119]
private 'association' =>
array (size=16)
...
private 'em' =>
object(Doctrine\ORM\EntityManager)[686]
...
private 'backRefFieldName' => string 'devis' (length=5)
private 'typeClass' =>
object(Doctrine\ORM\Mapping\ClassMetadata)[857]
...
private 'isDirty' => boolean false
private 'initialized' => boolean false
private 'coll' =>
object(Doctrine\Common\Collections\ArrayCollection)[1116]
...
You have made a mistake in your second loop, it's not mes_devis.articles but devis.articles :
{% for article in devis.articles %}
<div class="cart-header">
<div class="close1"> </div>
<div class="cart-sec">
<div class="cart-item cyc">
<img src="{{ asset ('bundles/theme_front_end/images/ts4.jpg') }}"/>
</div>
<div class="cart-item-info">
<h3>Mast & Harbour<span>Model No: 3578</span></h3>
<h4><span>Rs. $ </span>150.00</h4>
<p class="qty">Qty ::</p>
<input min="1" type="number" id="quantity" name="quantity" value="1" class="form-control input-small">
</div>
<div class="clearfix"></div>
<div class="delivery">
<p>Service Charges:: Rs.50.00</p>
</div>
</div>
</div>
<script>$(document).ready(function (c) {
$('.close2').on('click', function (c) {
$('.cart-header2').fadeOut('slow', function (c) {
$('.cart-header2').remove();
});
});
});
</script>
{% endfor %}

Class doesn't fetch correctly the object's values

Given this class :
class Address {
public $id;
public $id_easypost;
public $street1;
public $street2;
public function __construct($id,$id_easypost,$street1,$street2) {
$this->$id = $id;
$this->$id_easypost = $id_easypost;
$this->$street1 = $street1;
$this->$street2 = $street2;
}
}
I don't get why, when creating an object like that:
$ad = new Address("1", "2", "3", "4");
Values are not "fetched" correctly :
object(Address)[15]
public 'id' => null
public 'id_easypost' => null
public 'street1' => null
public 'street2' => null
public '1' => string '1' (length=1)
public '2' => string '2' (length=1)
public '3' => string '3' (length=1)
public '4' => string '4' (length=1)
However, this class works correctly :
class Rider {
public $id;
public $name;
public $activated;
public $created_at;
public $updated_at;
public function __construct($id, $name, $activated, $created_at, $updated_at) {
$this->id = $id;
$this->name = $name;
$this->activated = $activated;
$this->created_at = $created_at;
$this->updated_at = $updated_at;
}
}
And "fetch" the values correctly.
object(Rider)[16]
public 'id' => string '1' (length=1)
public 'name' => string '2' (length=1)
public 'activated' => string '3' (length=1)
public 'created_at' => string '4' (length=1)
public 'updated_at' => string '5' (length=1)
How is that ?
You shouldn't use $ sign to access object properties. This is correct:
$this->id = $id;

Accessing object properties in PHP

I am trying to access properties of a custom object in PHP:
<?php
namespace App\Classes;
use Illuminate\Database\Eloquent\Model;
class AED extends Model {
protected $table = 'aeds';
protected $fillable = ['owner', 'street', 'postal_code', 'locality', 'latitude', 'longitude', 'annotation_type'];
public $timestamps = true;
public $id;
public $owner;
public $object;
public $street;
public $postalCode;
public $locality;
public $latitude;
public $longitude;
public $annotation_type;
public $distance;
public function set($data) {
foreach ($data as $key => $value) {
if(property_exists($this, $key)) {
$this->$key = $value;
}
}
}
}
The code to access these properties:
<?php
namespace App\Transformer;
use App\Classes\AED;
use League\Fractal\TransformerAbstract;
class AEDTransformer extends TransformerAbstract {
public function transform(AED $aed) {
return [
'data' => $aed->owner
];
}
}
When I call the function, I get this as a response:
{
data: [
{
data: null
}
],
meta: "TestMeta"
}
The strange thing is, when I just var_dump the object I get the full info:
...
protected 'original' =>
array (size=11)
'id' => int 1
'owner' => string 'Owner 1' (length=7)
'object' => string 'Object 1' (length=8)
'street' => string 'Street 1' (length=8)
'postal_code' => string '11111' (length=5)
'locality' => string 'Locality 1' (length=10)
'latitude' => float 100
'longitude' => float 100
'annotation_type' => string '1' (length=1)
'created_at' => string '0000-00-00 00:00:00' (length=19)
'updated_at' => string '0000-00-00 00:00:00' (length=19)
...
So the data can be taken from the database as expected and is being received as well. Why does the accessing not work then and I receive a "null".
I use the "set" method inside the custom function here:
class AEDHelper {
static public function searchAED($position) {
$var1 = $position['latitude'];
$var2 = $position['longitude'];
$var3 = $position['latitude'];
$queryResults = DB::select(DB::raw("SQLCODE"));
$results = [];
foreach ($queryResults as $results) {
$aed = new AED();
$aed->set($results);
$results[] = $aed;
}
return $results;
}
Here I create a new AED() instance. So I would guess I need to define the object properties therefore as now not Eloquent will be used but a custom AED class needs to be instantiated for displaying SQL results.
Best
you don't have to define fields in your model. Eloquent makes them available dynamically.
if you want to fill those fields you can without having them in your model. because the field will be available if you try to set a value for it.
here is how
$aed = new AED;
$aed->owner = "The Owner";
$aed->object = "The Object";
....
....
....
$aed->save();
or this will work as well
AED::create([
'owner' => "The Owner",
'object' => "The Object",
.....
.....
.....
]);
or if you want update an existing model.
$aed = AED::find(1);
// change owner
$aed->owner= "New Owner";
$aed->save();

find out a class variable's defined scope (from within the class)

Given:
class myClass extends \Phalcon\Mvc\Model
{
public $a;
protected $b;
private $c;
}
How can I test that $a is public, $b is protected, and $c is private from within myClass?
You can use ReflectionProperty -
class myClass
{
public $a;
protected $b;
private $c;
}
$obj = new myClass();
$reflect_a = new ReflectionProperty(get_class($obj), 'a');
$reflect_c = new ReflectionProperty(get_class($obj), 'c');
var_dump($reflect_a->isProtected());
var_dump($reflect_c->isPrivate());
Depending on the result you can hide or show them.
For your needs you can use use Models Meta-Data. You can get the attributes of the model within the model:
<?php
/**
* Posts Model
*
*/
class Posts extends \Phalcon\Mvc\Model
{
public $id;
public $users_id;
public $categories_id;
public $title;
public $slug;
public $content;
public $number_views;
public $number_replies;
public $votes_up;
public $votes_down;
public $sticked;
public $modified_at;
public $created_at;
public $edited_at;
public $status;
public $locked;
public $deleted;
public $accepted_answer;
private $foo_bar;
}
Somewhere in the controller:
var_dump($this->modelsMetadata->getAttributes(new Posts()));die;
Output:
array (size=18)
0 => string 'id' (length=2)
1 => string 'users_id' (length=8)
2 => string 'categories_id' (length=13)
3 => string 'title' (length=5)
4 => string 'slug' (length=4)
5 => string 'content' (length=7)
6 => string 'number_views' (length=12)
7 => string 'number_replies' (length=14)
8 => string 'votes_up' (length=8)
9 => string 'votes_down' (length=10)
10 => string 'sticked' (length=7)
11 => string 'created_at' (length=10)
12 => string 'modified_at' (length=11)
13 => string 'edited_at' (length=9)
14 => string 'status' (length=6)
15 => string 'locked' (length=6)
16 => string 'deleted' (length=7)
17 => string 'accepted_answer' (length=15)
Also you can create an model's method:
public function getAttributes()
{
$metaData = $this->getModelsMetaData();
return $metaData->getAttributes($this);
}
\Phalcon\Mvc\Model\MetaData::getAttributes Returns table attributes names - fields of table.
Also PHP's get_class_vars() returns an array of all properties visible in the current scope. In your case it should return all public properties.

Categories