I need to update password with sonata admin int fos userbundle 'bcrypt' password.
This is my admin class,
<?php
namespace AdminBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;
class UserAdmin extends Admin {
public function postPersist($object) {
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserBy(array('id'=>$object->id));
$user->setPlainPassword('test');
$userManager->updateUser($user);
}
This is my user entity,
<?php
// src/AppBundle/Entity/User.php
namespace AdminBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="telephone", type="text", length=30, nullable=false)
*/
private $telephone;
/**
* Set nonotification
*
* #param text $telephone
* #return User
*/
public function settelephone($telephone) {
$this->telephone = $telephone;
return $this;
}
/**
* Get telephone
*
* #return text
*/
public function gettelephone() {
return $this->telephone;
}
/**
* #var string
*
* #ORM\Column(name="name", type="text", length=60, nullable=false)
*/
private $name;
/**
* Set nonotification
*
* #param text $name
* #return User
*/
public function setname($name) {
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return text
*/
public function getname() {
return $this->name;
}
/**
* #var string
*
* #ORM\Column(name="surname", type="text", length=60, nullable=false)
*/
private $surname;
/**
* Set nonotification
*
* #param text $name
* #return User
*/
public function setsurname($surname) {
$this->surname = $surname;
return $this;
}
/**
* Get surname
*
* #return text
*/
public function getsurname() {
return $this->surname;
}
public function __construct() {
parent::__construct();
// your own logic
}
}
But I'm getting this error instead,
Attempted to call an undefined method named "get" of class
"AdminBundle\Admin\UserAdmin". Did you mean to call e.g.
"getActiveSubClass", "getActiveSubclassCode", "getBaseCodeRoute",
"getBaseControllerName", "getBaseRouteName", "getBaseRoutePattern",
"getBatchActions", "getBreadcrumbs", "getChild", "getChildren",
"getClass", "getClassnameLabel", "getCode", "getConfigurationPool",
"getCurrentChild", "getCurrentChildAdmin", "getDataSourceIterator",
"getDatagrid", "getDatagridBuilder", "getExportFields",
"getExportFormats", "getExtensions", "getFilterFieldDescription",
"getFilterFieldDescriptions", "getFilterParameters", "getFilterTheme",
"getForm", "getFormBuilder", "getFormContractor",
"getFormFieldDescription", "getFormFieldDescriptions",
"getFormGroups", "getFormTabs", "getFormTheme", "getIdParameter",
"getLabel", "getLabelTranslatorStrategy", "getList", "getListBuilder",
"getListFieldDescription", "getListFieldDescriptions",
"getManagerType", "getMaxPageLinks", "getMaxPerPage",
"getMenuFactory", "getModelManager", "getNewInstance",
"getNormalizedIdentifier", "getObject", "getObjectIdentifier",
"getObjectMetadata", "getParent", "getParentAssociationMapping",
"getParentFieldDescription", "getPerPageOptions",
"getPermissionsShow", "getPersistentParameter",
"getPersistentParameters", "getRequest", "getRoot", "getRootCode",
"getRouteBuilder", "getRouteGenerator", "getRouterIdParameter",
"getRoutes", "getSecurityHandler", "getSecurityInformation",
"getShow", "getShowBuilder", "getShowFieldDescription",
"getShowFieldDescriptions", "getShowGroups", "getShowTabs",
"getSideMenu", "getSubClasses", "getSubject", "getTemplate",
"getTemplates", "getTranslationDomain", "getTranslationLabel",
"getTranslator", "getUniqid", "getUrlsafeIdentifier" or
"getValidator"?
It would be great help someone can look into it.
You cannot access the container with $this->get('service.name') from a sonata admin class. You should use:
$container = $this->getConfigurationPool()->getContainer();
$userManager = $container->get('fos_user.user_manager');
Also, I don't know if your solution would work anyway. I would use something like this:
public function postPersist($object) {
$container = $this->getConfigurationPool()->getContainer();
$entityManager = $container->get('doctrine.orm.entity_manager');
$object->setPlainPassword('test');
$entityManager->persist($user);
$entityManager->flush();
}
And do yourself a favor and respect the naming conventions (getName instead of getname, etc)
Related
I have a OneToMany relation between two tables 'user' and 'profil'
(a user has one only profile, and a profile can be asseigned to many users)
I'm getting this error whenever I try to update the schema in doctrine console.
here is my two entities :
<?php
namespace CNAM\CMSBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping\ManyToOne;
/**
* user
*
* #ORM\Table(name="user")
* #ORM\Entity
*/
class user
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=40)
*/
private $password;
public function __construct()
{
}
/**
* #var boolean
*
* #ORM\Column(name="etat", type="boolean")
*/
private $etat;
/**
* #var profil $profil
*
* #ORMManyToOne(targetEntity="profil", inversedBy="users", cascade={"persist", "merge"})
* #ORMJoinColumns({
* #ORMJoinColumn(name="profil", referencedColumnName="id")
* })
*/
private $profil;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set id
*
* #param integer $id
* #return user
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* 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;
}
/**
* Set etat
*
* #param boolean $etat
* #return user
*/
public function setEtat($etat)
{
$this->etat = $etat;
return $this;
}
/**
* Get etat
*
* #return boolean
*/
public function getEtat()
{
return $this->etat;
}
/**
* Get profil
*
* #return integer
*/
public function getProfil()
{
return $this->profil;
}
/**
* Set profil
*
* #param integer $profil
* #return user
*/
public function setProfil($profil)
{
$this->profil = $profil;
return $this;
}
public function getUsername()
{
return $this->id;
}
public function getRoles()
{
return array('ROLE_USER');
}
public function getSalt()
{
return null;
}
public function eraseCredentials()
{
}
public function equals(UserInterface $user)
{
return $user->getId() == $this->getId();
}
}
<?php
namespace CNAM\CMSBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping\OneToMany;
/**
* profil
*
* #ORM\Table(name="profil")
* #ORM\Entity
*/
class profil
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="libelle", type="string", length=20)
*/
private $libelle;
/**
* #var ArrayCollection $users
*
* #ORMOneToMany(targetEntity="user", mappedBy="profil", cascade={"persist", "remove", "merge"})
*/
private $users;
public function __construct()
{
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set libelle
*
* #param string $libelle
* #return profil
*/
public function setLibelle($libelle)
{
$this->libelle = $libelle;
return $this;
}
/**
* Get libelle
*
* #return string
*/
public function getLibelle()
{
return $this->libelle;
}
/**
* Set id
*
* #param integer $id
* #return profil
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
public function __toString() {
return $this->libelle;
}
}
You have syntax mistake.
#ORMManyToOne - this is mistake.
#ORM\ManyToOne(targetEntity="Profil", inversedBy="users")
Above will be correct. And everywhere you use ORM You need to write ORM\something. ORM - is just a namespace, or simply path to the ORM classes in doctrine vendor directory!
Every class name should start with capital letter. It is a wright way! So you should write class User, but not class user!
You didn't show in Profil class, that you have a lot of users to each profil. the users field will be of array collection type (simple array but with useful methods.) So in Profil class in __construct() method:
public function __construct()
{
$this->users = new ArrayCollection();
}
You have One-To-Many, Bidirectional relation.
You can say :
Every (ONE) profile can have a lot of (MANY) users, which use it (One-To-Many)
Every user can use only one exact profile
So try this
// Class Profil
/**
* Bidirectional - One-To-Many (INVERSED SIDE)
* One Profile can have many users, which use it
*
* #var ArrayCollection $users
*
* #ORM\OneToMany(targetEntity="Path-to-your-user-class\Users", mappedBy="profil", cascade={"persist", "remove"}, orphanRemoval=true)
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
// Class user
/**
* Bidirectional - One-To-Many (OWNER SIDE)
* One user have only one profile (or profil)
*
* #var Profil $profil
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Profil", inversedBy="users")
* #ORM\JoinColumn(name="profil_id", referencedColumnName="id")
*/
private $profil;
I am working on some new project and the project is nearly done using Symfony framework, but the problem that i am used to CodeIgnitor Framework and basically as a Java developer/Android a lot of stuff i got confused with when working on Web development so here is the situation:
The website have a user end and an admin end (i am working on the Admin end), so there are these tables in the database which i really don't understand why they are built like this but this is not the problem
what i would like to know is how to add a service_category field with the corresponding translations in the service_category_translation using forms or any other way
this is the ServiceCategory Entity
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use JMS\Serializer\Annotation as Serializer;
/**
* class ServiceCategory
*
* #ORM\Table(name="service_category")
* #ORM\Entity
*
* #Serializer\ExclusionPolicy("all")
*/
class ServiceCategory
{
use ORMBehaviors\Timestampable\Timestampable;
use ORMBehaviors\SoftDeletable\SoftDeletable;
use ORMBehaviors\Translatable\Translatable;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*
* #Serializer\Expose
* #Serializer\Groups({"general-information", "service-offer"})
*/
private $id;
/**
* #var ServiceGroup
*
* #ORM\OneToMany(targetEntity="ServiceGroup", mappedBy="serviceCategory")
*
* #Serializer\Expose
* #Serializer\Groups({"service-offer"})
*/
private $serviceGroup;
/**
* Constructor
*/
public function __construct()
{
$this->serviceGroup = new ArrayCollection();
}
/**
* {#inheritdoc}
*/
public function __toString()
{
return $this->getName() ? $this->getName() : '';
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Get translated name
*
* #return string
*
* #Serializer\VirtualProperty
* #Serializer\SerializedName("name")
* #Serializer\Groups({"invoice-list", "service-offer"})
*/
public function getName()
{
if($this->getTranslations()->get($this->getCurrentLocale()) == null){
return 'sorry';
}
return $this->getTranslations()->get($this->getCurrentLocale())->getName();
}
/**
* Add serviceGroup
*
* #param ServiceGroup $serviceGroup
*
* #return ServiceCategory
*/
public function addServiceGroup(ServiceGroup $serviceGroup)
{
$this->serviceGroup[] = $serviceGroup;
return $this;
}
/**
* Remove serviceGroup
*
* #param ServiceGroup $serviceGroup
*/
public function removeServiceGroup(ServiceGroup $serviceGroup)
{
$this->serviceGroup->removeElement($serviceGroup);
}
/**
* Get serviceGroup
*
* #return Collection
*/
public function getServiceGroup()
{
return $this->serviceGroup;
}
}
and this is the ServiceCategoryTranslation Entity
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
/**
* Class ServiceCategoryTranslation
*
* #package CoreBundle\Entity
*
* #ORM\Entity
* #ORM\Table(name="service_category_translation")
*/
class ServiceCategoryTranslation
{
use ORMBehaviors\Translatable\Translation;
use ORMBehaviors\Timestampable\Timestampable;
use ORMBehaviors\SoftDeletable\SoftDeletable;
/**
* #ORM\Column(type="string", length=255)
*/
protected $name;
/**
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #param string
* #return null
*/
public function setName($name)
{
$this->name = $name;
}
public function __toString() {
return $this->name;
}
}
how can i achieve this ?
please don't guide me to symfony or doctrine documentation i have been lost there for two days now and i am running late on the schedule
Thanks in advance
You have a one-to-many-association from ServiceCategory (1) to ServiceCategoryTranslations (many) since I assume you
will manage the transaltions from the category. This have to be a bidirectional association, have a look
here
You have to add a property to manage the entities and describe the association. I will do it with annotations.
use Doctrine\Common\Collections\ArrayCollection;
class ServiceCategory
{
/**
* #OneToMany(targetEntity="ServiceCategoryTranslation", mappedBy="serviceCategory")
**/
private $translations;
public function __construct()
{
$this->translations = new ArrayCollection();
}
/**
* #return ServiceCategoryTranslation[]
*/
public function getStandort(){
return $this->translations;
}
/**
* #param ArrayCollection $translations
* #return ServiceCategory
*/
public function setTranslations(ArrayCollection $translations)
{
$this->translations->clear();
foreach ($translations as $translation){
$this->addTranslation($translation);
}
return $this;
}
/**
* #param ServiceCategoryTranslation $translation
* #return ServiceCategory
*/
public function addTranslation(ServiceCategoryTranslation $translation){
/* this is a way to keep the integerity */
$translation->setServiceCategory($this);
if(!$this->translation){
$this->translations = new ArrayCollection();
}
$this->translations->add($translation);
return $this;
}
/**
* #param ServiceCategoryTranslation $translation
* #return ServiceCategory
*/
public function removeStandort(ServiceCategoryTranslation $translation){
$this->translations->removeElement($translation);
return $this;
}
}
class ServiceCategoryTranslation
{
/**
* #ManyToOne(targetEntity="ServiceCategory", inversedBy="translations")
* #JoinColumn(name="translatable_id", referencedColumnName="id")
**/
private $serviceCategory;
/**
* #param ServiceCategoryTranslation $translation
* #return ServiceCategoryTranslation
*/
public function setServiceCategory(ServiceCategory $serviceCategory){
$this->serviceCategory = $serviceCategory;
return $this;
}
/* getter analog */
}
I need to save user with his profile fields. I establish relations. User has one Profile, Profile has one User. I add fields to register form. But when I saving object, I get error,
Undefined index: profile in /var/www/Symfony/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 2714 . Where my mistake, please help me. I am newbie)
Here is the code:
namespace Acme\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Profile
*
* #ORM\Table(name="acme_profile")
* #ORM\Entity
*/
class Profile
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="fio", type="string", length=255)
*/
protected $fio;
/**
* #ORM\Column(name="birthDate", type="date")
*/
protected $birthDate;
/**
* #ORM\OneToOne(targetEntity="Acme\UserBundle\Entity\User", cascade={"persist"})
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* #return mixed
*/
public function getFio()
{
return $this->fio;
}
/**
* #param $fio
* #return $this
*/
public function setFio($fio)
{
$this->fio = $fio;
return $this;
}
/**
* #return mixed
*/
public function getBirthDate()
{
return $this->birthDate;
}
/**
* #param $birthDate
* #return $this
*/
public function setBirthDate($birthDate)
{
$this->birthDate = $birthDate;
return $this;
}
/**
* #return mixed
*/
public function getUser()
{
return $this->user;
}
/**
* #param User $user
* #return $this
*/
public function setUser(User $user = null)
{
$this->user = $user;
return $this;
}
}
namespace Acme\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="acme_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\OneToOne(targetEntity="Acme\UserBundle\Entity\Profile", cascade={"persist"})
*/
protected $profile;
public function __construct()
{
parent::__construct();
}
public function setProfile(Profile $profile = null)
{
$this->profile = $profile;
return $this;
}
public function getProfile()
{
return $this->profile;
}
}
namespace Acme\UserBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class RegistrationFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// add your custom field
$builder->add('profile', new ProfileType());
}
public function getParent()
{
return 'fos_user_registration';
}
public function getName()
{
return 'acme_user_registration';
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\UserBundle\Entity\User'
));
}
}
You should use the MappedBy and InversedBy as specified in the documentation here : http://docs.doctrine-project.org/en/2.0.x/reference/association-mapping.html#owning-side-and-inverse-side
/**
* #ORM\OneToOne(targetEntity="Acme\UserBundle\Entity\Profile",
mappedBy="user"))
*/
and the other side you use :
/**
* #ORM\OneToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy="profile" cascade={"persist"})
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
I use symfony2.4 and KNP doctrine behaviors translatable.
I have entity Site (for ID, host, enabled) and entity SiteTranslation (for translated fields: name, descriptions, …).
I use query to get results
$qb = $this->createQueryBuilder('s')
->addSelect('translation') // to eager fetch translations (optional)
->leftJoin('s.translations', 'translation') // or innerJoin ?
->orderBy('s.root', 'ASC')
->addOrderBy('s.lft', 'ASC');
I would like to print result in Twig. For ID, host and enabled fields from Site entity it's easy:
{{ item.id }}
But I can't print translated fields (name, description, …)
{{ item.name }}
It doesn't work.
Error message:
ContextErrorException: Warning: call_user_func_array() expects parameter 1 to be a valid >callback, class 'Net\ConBundle\Entity\SiteTranslation' does not have a method 'name' in >D:\Users...\vendor\knplabs\doctrine->behaviors\src\Knp\DoctrineBehaviors\Model\Translatable\TranslatableMethods.php line 140
Getters and setters for translatable fields are in SiteTranslation entity.
UPDATE:
I still didn't find a solution for an error.
Here is Site entity:
<?php
namespace Pnet\ConlocoBundle\Entity;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
/**
* #UniqueEntity("host", message="site.host.unique", groups={"edit"})
* #Gedmo\Tree(type="nested")
* #ORM\Entity(repositoryClass="Pnet\ConlocoBundle\Entity\Repository\SiteRepository")
* #ORM\Table(name="site")
*/
class Site
{
use ORMBehaviors\Translatable\Translatable; // knp translatable strategy
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=40, unique=true)
* #Assert\NotBlank(message="site.host.notBlank", groups={"edit"})
* #Assert\Length(max = "40", maxMessage = "site.host.maxLength", groups={"edit"})
*/
protected $host;
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #Assert\Image()
*/
protected $image;
/**
* #ORM\Column(type="boolean")
* #Assert\Choice(choices = {"1", "0"}, message = "site.isDefault.choice", groups={"edit"})
*/
protected $isDefault;
/**
* #ORM\Column(type="boolean")
* #Assert\Choice(choices = {"1", "0"}, message = "site.enabled.choice", groups={"edit"})
*/
protected $enabled;
/**
* #ORM\Column(type="string", length=64, nullable=true)
*/
protected $analytics;
/**
* #Gedmo\TreeLeft
* #ORM\Column(name="lft", type="integer")
*/
private $lft;
/**
* #Gedmo\TreeLevel
* #ORM\Column(name="lvl", type="integer")
*/
private $lvl;
/**
* #Gedmo\TreeRight
* #ORM\Column(name="rgt", type="integer")
*/
private $rgt;
/**
* #Gedmo\TreeRoot
* #ORM\Column(name="root", type="integer", nullable=true)
*/
private $root;
/**
* #Gedmo\TreeParent
* #ORM\ManyToOne(targetEntity="Site", inversedBy="children")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $parent;
/**
* #ORM\OneToMany(targetEntity="Site", mappedBy="parent")
* #ORM\OrderBy({"lft" = "ASC"})
*/
private $children;
private $file;
public $idByFilter;
public $nameByFilter;
/**
* Proxy translations (Knp/Doctrine Behaviors)
* An extra feature allows you to proxy translated fields of a translatable entity.
* You can use it in the magic __call method of you translatable entity so that when
* you try to call getName (for example) it will return you the translated value
* of the name for current locale:
*/
public function __call($method, $arguments)
{
return $this->proxyCurrentLocaleTranslation($method, $arguments);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set host
*
* #param string $host
* #return Site
*/
public function setHost($host)
{
$this->host = $host;
return $this;
}
/**
* Get host
*
* #return string
*/
public function getHost()
{
return $this->host;
}
/**
* Set isDefault
*
* #param boolean $isDefault
* #return Site
*/
public function setIsDefault($isDefault)
{
$this->isDefault = $isDefault;
return $this;
}
/**
* Get isDefault
*
* #return boolean
*/
public function getIsDefault()
{
return $this->isDefault;
}
/**
* Set enabled
*
* #param boolean $enabled
* #return Site
*/
public function setEnabled($enabled)
{
$this->enabled = $enabled;
return $this;
}
/**
* Get enabled
*
* #return boolean
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* Set analytics
*
* #param string $analytics
* #return Site
*/
public function setAnalytics($analytics)
{
$this->analytics = $analytics;
return $this;
}
/**
* Get analytics
*
* #return string
*/
public function getAnalytics()
{
return $this->analytics;
}
/**
* Get ID from Filter
*
* #return string
*/
public function getIdByFilter()
{
return $this->idByFilter;
}
/**
* Get name from Filter
*
* #return string
*/
public function getNameByFilter()
{
return $this->nameByFilter;
}
/**
* Set image
*
* #param string $image
* #return Site
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set file
*
* #param string $file
* #return Site
*/
public function setFile($file)
{
$this->file = $file;
return $this;
}
/**
* Get file
*
* #return string
*/
public function getFile()
{
return $this->file;
}
/**
*
* Tree functions
*/
public function setParent(Site $parent = null)
{
$this->parent = $parent;
}
public function getParent()
{
return $this->parent;
}
public function getRoot()
{
return $this->root;
}
public function getLvl()
{
return $this->lvl;
}
public function getChildren()
{
return $this->children;
}
public function getLft()
{
return $this->lft;
}
public function getRgt()
{
return $this->rgt;
}
/**
* Add a method to the entity class that shows the name indented by nesting level
*/
public function getLeveledName()
{
return str_repeat(
html_entity_decode(' ', ENT_QUOTES, 'UTF-8'),
($this->getLvl()) * 3
) . $this->getName();
}
public function getLeveledPosition()
{
return str_repeat(
html_entity_decode(' ', ENT_QUOTES, 'UTF-8'),
($this->getLvl()) * 3
);
}
}
And here is SiteTranslation entity:
namespace Pnet\ConlocoBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
/**
* #ORM\Entity
*/
class SiteTranslation
{
use ORMBehaviors\Translatable\Translation;
/**
* #ORM\Column(type="string", length=60)
* #Assert\NotBlank(message="site.name.notBlank", groups={"edit"})
* #Assert\Length(max = "60", maxMessage = "site.name.maxLength", groups={"edit"})
*/
protected $name;
/**
* #ORM\Column(type="string", length=100)
* #Assert\NotBlank(message="site.title.notBlank", groups={"edit"})
* #Assert\Length(max = "100", maxMessage = "site.title.maxLength", groups={"edit"})
*/
protected $title;
/**
* #ORM\Column(type="string", length=200)
* #Assert\NotBlank(message="site.longTitle.notBlank", groups={"edit"})
* #Assert\Length(max = "200", maxMessage = "site.longTitle.maxLength", groups={"edit"})
*/
protected $longTitle;
/**
* #ORM\Column(type="string", length=250, nullable=true)
* #Assert\Length(max = "250", maxMessage = "site.keywords.maxLength", groups={"edit"})
*/
protected $keywords;
/**
* #ORM\Column(type="string", length=500, nullable=true)
* #Assert\Length(max = "500", maxMessage = "site.description.maxLength", groups={"edit"})
*/
protected $description;
/**
* Set name
*
* #param string $name
* #return Site
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set title
*
* #param string $title
* #return Site
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set longTitle
*
* #param string $longTitle
* #return Site
*/
public function setLongTitle($longTitle)
{
$this->longTitle = $longTitle;
return $this;
}
/**
* Get longTitle
*
* #return string
*/
public function getLongTitle()
{
return $this->longTitle;
}
/**
* Set keywords
*
* #param string $keywords
* #return Site
*/
public function setKeywords($keywords)
{
$this->keywords = $keywords;
return $this;
}
/**
* Get keywords
*
* #return string
*/
public function getKeywords()
{
return $this->keywords;
}
/**
* Set description
*
* #param string $description
* #return Site
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
}
TL;DR:
As a (probably dirty) workaround, use
{{ item.getName }}
in your Twig template instead of
{{ item.name }}
Explanation:
I came across the same issue and i think that this should be considered a bug in the Knp DoctrineBehaviors documentation when used with Twig. When you call this in your Twig template :
{{ item.name }}
This is what Twig does behind the scenes to get the name property :
try to get the name public property of the item object
if not found, checks for the name public method of the item object
if not found, checks for the getName() public method of the "item" object
if not found, checks for the __call() magic method (and calls it with the name parameter)
The problem here is step 4. The magic __call() method that you defined (as recommended by the official DoctrineBehaviors documentation) is called with the name parameter instead of getName. It then calls the proxyCurrentLocaleTranslation() method who tries to call the name public method of your translation class. Of course, it doesn't exist because you only have a getName() method.
See this issue in Twig : https://github.com/twigphp/Twig/issues/342
By using directly the {{ item.getName }} code in Twig, the proper method name will be called.
This work for me:
public function __call($method, $arguments)
{
try {
return $this->proxyCurrentLocaleTranslation($method, $arguments);
} catch (\Symfony\Component\Debug\Exception\ContextErrorException $e) {
return $this->proxyCurrentLocaleTranslation('get' . ucfirst($method), $arguments);
}
}
You haven't moved all the translatable properties/methods to your <Name>Translation class.
The exception clearly states that there is no name/getName method in your SiteTranslation class.
Please read my answer over here to see how Knp\DoctrineBehaviors's magic translation proxy is used correctly.
I have a Util class in a Symfony 2.4 proyect that get the slug from a book. The slug cannot be repeated. Each slug must be unique. I have the following code form the class that generate the slug. I have the error:
Fatal error: Using $this when not in object context in C:\xampp\htdocs\gens\src\
Sakya\GensBundle\Util\Util.php on line 38
namespace Sakya\GensBundle\Util;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityManager;
class Util
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public static function getSlug($slug)
{
$separador = '-';
$tildes=array('á','é','í','ó','ú');
$vocales=array('a','e','i','o','u');
str_replace($vocales,$tildes,$slug);
$slug = iconv('UTF-8', 'ASCII//TRANSLIT', $slug);
$slug = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $slug);
$slug = strtolower(trim($slug, $separador));
$slug = preg_replace("/[\/_|+ -]+/", $separador, $slug);
$i = 1;
while (! $this->em->getRepository("GensBundle:Libro")->findBySlug($slug)){
$slug = $slug."-".$i;
$i++;
}
return $slug;
}
}
It is mi Entity "Libro"
<?php
namespace Sakya\GensBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Sakya\GensBundle\Util\Util;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Libro
*
* #ORM\Table()
* #ORM\Entity
*/
class Libro
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="libro", type="string", length=255)
*/
private $libro;
/**
* #ORM\Column(type="string")
*
* #Assert\NotBlank()
*/
protected $slug;
/**
* #var string
*
* #ORM\Column(name="autor", type="string", length=255)
*/
private $autor;
/**
* #var string
*
* #ORM\Column(name="prefacio", type="string", length=700)
*/
private $prefacio;
/**
* #ORM\OneToMany(targetEntity="Capitulo", mappedBy="libro")
*/
private $capitulo;
public function __toString()
{
return $this->getLibro();
}
/**
* Constructor
*/
public function __construct()
{
$this->capitulo = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set libro
*
* #param string $libro
* #return Libro
*/
public function setLibro($libro)
{
$this->libro = $libro;
$this->slug = Util::getSlug($libro);
return $this;
}
/**
* Get libro
*
* #return string
*/
public function getLibro()
{
return $this->libro;
}
/**
* Set autor
*
* #param string $autor
* #return Libro
*/
public function setAutor($autor)
{
$this->autor = $autor;
return $this;
}
/**
* Get autor
*
* #return string
*/
public function getAutor()
{
return $this->autor;
}
/**
* Add capitulo
*
* #param \Sakya\GensBundle\Entity\Capitulo $capitulo
* #return Libro
*/
public function addCapitulo(\Sakya\GensBundle\Entity\Capitulo $capitulo)
{
$this->capitulo[] = $capitulo;
return $this;
}
/**
* Remove capitulo
*
* #param \Sakya\GensBundle\Entity\Capitulo $capitulo
*/
public function removeCapitulo(\Sakya\GensBundle\Entity\Capitulo $capitulo)
{
$this->capitulo->removeElement($capitulo);
}
/**
* Get capitulo
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCapitulo()
{
return $this->capitulo;
}
/**
* Set prefacio
*
* #param string $prefacio
* #return Libro
*/
public function setPrefacio($prefacio)
{
$this->prefacio = $prefacio;
return $this;
}
/**
* Get prefacio
*
* #return string
*/
public function getPrefacio()
{
return $this->prefacio;
}
/**
* Set slug
*
* #param string $slug
* #return Libro
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
}
How can I make a consult that check that the slug is not in the database form the Uti Class?
Thanks for all and sorry for my English
The problem is you are trying refer to a property from static method. Don't do it unless the property is also static.
The best way I can suggest is change the static method into not-static, then create a service from Util class, and make validation outside the entity. It's not a good idea using service inside entity class.
You didn't show the context but I can guess: if you want set slug based on a form - then the best way to achieve what you want would be create a validator.