Giter Club home page Giter Club logo

doctrinebehaviors's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

doctrinebehaviors's Issues

ORMException: Entity of type XXX is missing an assigned ID for field 'id'.

Hi,
i have a problem using the TranslatetableListener. The service is configured and available. I configured everything like in your example. In the normal Category Entity the id generate strategy ist set to NONE. This seems not to work because I always get the following error message

ORMException: Entity of type XXX\Prototype\CategoryBundle\Entity\Category is missing an assigned ID for field 'id'. The identifier generation strategy for this entity requires the ID field to be populated before EntityManager#persist() is called. If you want automatically generated identifiers instead you need to adjust the metadata mapping accordingly.

Anyway the TranslatetableListeneris triggered and adds the metadata (i have checked this by set an echo 'Hello'; in die TranslatableListener Class)

In my opinion something wents wrong here.

Fix notice in (Undefined index: name)

Since there is no way to suppress notices in symfony without setting the debug to false (that's not the solution), there is a problem to fix in /vendor/knplabs/doctrine-behaviors/src/Knp/DoctrineBehaviors/ORM/Translatable/TranslatableListener.php line 109.

Translatable => translation not recorded in database.

Hello,

I'm facing a very strange behavior of translatable.
I followed the informations i found to add the traits to my entity, then i created a translation 'entity'.

I then used the generate:crud function from symfony console.

But when i try to create a new record, the translation is not put in the database, only the CsVictims record is created.
I modified my crud code to have access to the debugger after the creation and i get this as doctrine calls :

 "START TRANSACTION"
INSERT INTO CsVictims (id) 
VALUES 
  (null)
"COMMIT"

The mapping display no mapping errors.

i have added this line in my config.yml :

imports:
    - { resource: ../../vendor/knplabs/doctrine-behaviors/config/orm-services.yml }

My entity is the following :

<?php

namespace myproject\WebsiteBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;

/**
 * CsVictims
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="myproject\WebsiteBundle\Entity\CsVictimsRepository")
 */
class CsVictims
{

    use ORMBehaviors\Translatable\Translatable;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToMany(targetEntity="CsDisease", mappedBy="victims")
     */
    protected $diseases;

    protected $description;

    protected $name;

    public function __construct()
    {

        $this->diseases = new ArrayCollection();
    }

    public function __toString() {

        if ($this->getName() == null) {

            return "";
        }

        return $this->getName();
    }

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    public function setDiseases($diseases)
    {
        $this->diseases = $diseases;
    }

    public function getDiseases()
    {
        return $this->diseases;
    }

    public function getName() {

        return $this->translate($this->getCurrentLocale())->getName();
    }

    public function setName($name) {

        $this->translate($this->getCurrentLocale())->setName($name);

        return $this;
    }

    public function getDescription() {

        return $this->translate($this->getCurrentLocale())->getDescription();
    }

    public function setDescription($desc) {

        $this->translate($this->getCurrentLocale())->setDescription($desc);

        return $this;
    }
}

The translation 'entity' is the following :


<?php

namespace myproject\WebsiteBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;

/**
 * CsVictimsTranslation
 *
 * @ORM\Entity
 */
class CsVictimsTranslation
{

    use ORMBehaviors\Translatable\Translation;

    /**
     * @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;

    public function __toString() {

        return $this->name;
    }

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return CsVictims
     */
    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 CsVictims
     */
    public function setDescription($description)
    {

        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string 
     */
    public function getDescription()
    {
        return $this->description;
    }
}

The form type that was generated by the crud is the following :

<?php

namespace myproject\WebsiteBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class CsVictimsType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('description')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'myproject\WebsiteBundle\Entity\CsVictims'
        ));
    }

    public function getName()
    {
        return 'myproject_websitebundle_csvictimstype';
    }
}

and finally the controller code is the following (i modified the redirection to see what is happening with the debugguer tool) :


<?php

namespace myproject\WebsiteBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use myproject\WebsiteBundle\Entity\CsVictims;
use myproject\WebsiteBundle\Form\CsVictimsType;

/**
 * CsVictims controller.
 *
 */
class CsVictimsController extends Controller
{

...

 /**
     * Creates a new CsVictims entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity  = new CsVictims();
        $form = $this->createForm(new CsVictimsType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            //return $this->redirect($this->generateUrl('crud_csvictims_show', array('id' => $entity->getId())));
        }

        return $this->render(myprojectWebsiteBundle:CsVictims:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

...

Somme additionnal informations from the debugger :

Request POST Parameters

Key
myproject_websitebundle_csvictimstype

Value
{"name":"testEnglish1","description":"testEnglish2","_token":"f42fb730b0f96a71d140d7dd396ee28b46b192ad"}

_locale "en"

I'm fighting with this code and i'm trying to understand what can be wrong out there.

Did i miss something about the listener ? Should i register it manually in any other way than importing the yml file in config.yml ?

I may be doing a big mistake somewhere but i can't find where, so any help would be really appreciated.

Translation with form right way?

Hello! Now I try to use DoctrineBehaviors:Translation
Everything is fine but I have some problem with form.
Maybe somebody has some examples to work with form + translation.
I can't create sub form because I have next error

The form's view data is expected to be an instance of class Project\MailBundle\Entity\MessageTranslation, but is an instance of class Doctrine\ORM\PersistentCollection. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms an instance of class Doctrine\ORM\PersistentCollection to an instance of Project\MailBundle\Entity\MessageTranslation.

And this is correct because getTranslations() return a collection

builder->add('translations', new MessageTranslationType())

And I need to create some proxy class to Message entity.

Thanks a lot!

Add possibility to change the log handler (database, etc)

It would be more powerfull to be able to provide a service rather than just a callable Class to be able to log in database or any other ways.

For example by overiding:

knp.doctrine_behaviors.loggable_listener.logger_callable:
    id: my_bundle.entity_logger

Using loggable and blameable to keep user tracking on entity

This is more a support question than issue so my apologies. I'm working on a project where I'm using Symfony2 (latest) and SonataAdmin. I need to keep log of users actions by logging:

  • action/event date/time (when and at which time the user did something)
  • the user himself (the id of the user who did the action/event)
  • affected rows (which rows was affected by for example changing some data in a form)

I'm confused about loggable use since docs say "loggable is able to track lifecycle modifications and log them using any third party log system". Regarding this I have two questions:

  • what about if I one to log this in the same database without the need to use external logging system?
  • How do I display this data later?

Calling $entity->translate('xy') will creates multiply Translations

If you use the translate method as followed, you will get multiply Translations. Page is using the Translatable trait.

$testPage = new Page;

$testPage->translate('de')->setLabel('Lorem Ipsum');
$testPage->translate('de')->setLabel('Ipsum Testum');
$testPage->translate('de')->setLabel('Dolor Ipsum Lorem Test');

echo $testPage->translate('de')->getLabel();  // Output is void

$testPage->mergeNewTranslations();
echo 'Test: ' . $testPage->translate('de')->getLabel(); // Output is "Lorem Ipsum"

Working with __call and proxyCurrentLocaleTranslation has the same results.

I don't understand why newTranslations will be stored in a seperate Array. Chaning translate to:

public function translate($locale = null)
{
    // ...

    $this->mergeNewTranslations();

    return $translation;
}

worked fine, but I don't think, that this is not a good solution. In my mind the $newTranslations property is not necessary?

Delete a user entity that is already blamed by another entity

Hello,

So the scenario is like this: user A create a new Entity C and updates that entity so the entity C will have createdBy A and updatedBy A then user B deletes user A an exception will be thrown.

[1/2] PDOException: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`database`.`c`, CONSTRAINT `FK_F06D` FOREIGN KEY (`updatedBy_id`) REFERENCES `users` (`id`))   +

[2/2] DBALException: An exception occurred while executing 'DELETE FROM users WHERE id = ?' with params [10]:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`database`.`c`, CONSTRAINT `FK_F06D` FOREIGN KEY (`updatedBy_id`) REFERENCES `users` (`id`))   + 

Search or filter results by translatable fields in Knplabs doctrine behaviors bundle (Symfony2)

Hello,
I have seen some questions about this topic but without good answers.

I have entity Site with fields:
ID, host, enabled
and translatable entity SiteTranslations with fields name, description, keywords. (I use Knplabs translatable strategy)

I would like to filter results in list table by name, host and enabled values. For host and enabled field it is working ok, because those fields are in Site repository. But I can't find a solution how to filter by "name" which is in SiteTranslatable repository and in table sitetranslation.

Here is my form validation in controler:

….
if ($form->isValid()) { // a check to see if the form is valid 
     // filter records
      if($form->get('filter')->isClicked{
           if ($filter->getHost() !== null) $criteria['host'] = $filter->gethost();
           if ($filter->getEnabled() !== null) $criteria['enabled'] = $filter->getEnabled(); 
      }
}
…
$sites = $em->getRepository('PnetConlocoBundle:Site')->getList($criteria);

And getList function in repository:

public function getList($criteria = null)
{
             $qb = $this->createQueryBuilder('s')
                   ->select('s')
                   ->orderBy('s.root', 'ASC')
                   ->addOrderBy('s.lft', 'ASC'); 
         
            if($criteria !== null):
                foreach ($criteria as $field => $value):
                    if (!$this->getClassMetadata()->hasField($field)):
                        continue; // Make sure we only use existing fields (avoid any injection)
                    endif;  
                   
                    if ($this->getClassMetadata()->getTypeOfField($field) === 'string'
                        || $this->getClassMetadata()->getTypeOfField($field) === 'text'):
                        $qb ->andWhere($qb->expr()->like('s.'.$field, ':s_'.$field))
                            ->setParameter('s_'.$field, '%'.$value.'%');    // search LIKE %value%
                    else:    
                        $qb ->andWhere($qb->expr()->eq('s.'.$field, ':s_'.$field))
                            ->setParameter('s_'.$field, $value);
                    endif;
                endforeach;
            endif;        
        return $qb->getQuery()->getResult();
    }

Does anybody know how update this code that it will work also for translatable fields?

Thanks in advance.

docs: move the listeners to the top

Hi,

I suggest you to move the listeners block to the top of the doc. I've lost a bit of time because I didn't add the import. It should be said on a first block called Installation.

thanks anyway!

[Translatable] currentLocale = null

Using the trait \Knp\DoctrineBehaviors\Model\Translatable\Translation inside an Entity, I see that the property currentLocale is never setted , so we always obtain the default locale ('en') in all the calls to $this->translate().

In my symfony2 controller I've setted correctly the locale and all the requests goes with the correct locale.

If I change this getDefaultLocale, all the trasnlations are made correctly, so I think that is no problem with the fallback.

ODM support?

Hi, I like this project, but I don't see any ODM support in master branch.
it shouldn't be hard to implement this.
If there are any plans for support MongoDB?

Underscore column names

I believe most people use underscores for their column names. Any chance we could specific the name attribute in the Traits?

Or, do you know if it is possible to configure the way doctrine handles the column names if it is not specified?

I am happy to go through and add the name attributes to the ORM if this is something you will allow.

Tag v1.0.1

Can you please tag v1.0.1 so we have a stable version incorporating the new functionality since 1.0.0?

Optional updatedBy and updatedAt

Hi again,

Thanks for updating the docs! Something I'd love to do is to have the updatedBy and updatedAt as optionals parameters. I'm still new to Symfony2 & Doctrine2, so not sure which is the best option:

  • Annotations on the Entity to include the fields we want (as Gedmo does), instead of on the trait
  • Variable on the Entity to say which fields we want ( for example $updateDateOn = array('create') )

What do you think? Any idea on how to do the Annotations way?

thanks

[RFC] Time to switch to phpspec?

Hello ol' chap!

I'm thinking it could be a good time to switch DoctrineBehaviors lib and discuss the necessity to use real entity managers at some places.

[Feature Request] SortableBehavior

Would be good to have a sortable behaviour which has a listener to keep the entities in order (eg, you wouldn't have 1,2,6,7,8 - it would automatically fix it so that it was 1,2,3,4,5)

I think it should also have the option to specify a root so that you could sort between a category/parent etc.

If I can find some time I will work on this.

Managing translation

Do we actually need the mergeNewTranslations method?
Isn't it better to add them automatically, once the translate method is called?
Also any particular reason for the existence of isEmpty method?

If you like I can fix these things and send a PR.

[Geocodable] 'DISTANCE' returns miles, not km.

Hello,

After getting inconsistent results when computing distances using the DISTANCE function provided by this bundle, we discovered that the <@> operator actually returns miles, not kms (see here).

Looking at your tests and documentation, it would seem that you're unaware of this.

We've seen that postgresql also provides a function earth_distance which returns the distance in meters (and can also output other units be tweaking the earth function). This could help solve the problem.

I'd be happy to try to implement this solution if you think it's a good idea.

mapTranslation

Hi, it's the first time I post on github but I think I found an issue with the translatable behavior. You can have a more detailed version of my problem on stackoverflow : http://stackoverflow.com/questions/22867913/translation-behaviour-is-looking-for-enti-folder

Basically, when I was trying to map my schema it would return an error because it was looking for a folder "MyProject/MyBundle/Enti" instead of Entity. I opened the TranslatableListener and I think I found the issue.

On line 84 we got :

if (!$classMetadata->hasAssociation('translatable')) {
            $classMetadata->mapManyToOne([
                'fieldName'    => 'translatable',
                'inversedBy'   => 'translations',
                'joinColumns'  => [[
                    'name'                 => 'translatable_id',
                    'referencedColumnName' => 'id',
                    'onDelete'             => 'CASCADE'
                ]],
               'targetEntity' => substr($classMetadata->name, 0, -11) // Here why the substring? 
            ]);
        }

EDIT: I missused the bundle, sorry for any confusion.

Tree behavior in fixtures

How can i create a doctrine fixtures with a tree structure and make a $manager->flush(); for save all tree?

I just trying but i need pass an id in node constructor.

How to pass locale callable to translatableListener

Hi,
I'm stuck trying to pass the currentLocaleCallable to the translatableListener.

To me, the default orm-services.yml seems to pass it as third argument and I can't figure out why it is not present in the translatableListener constructor:

knp.doctrine_behaviors.translatable_listener:
        class:   "%knp.doctrine_behaviors.translatable_listener.class%"
        public:  false
        arguments:
            - "@knp.doctrine_behaviors.reflection.class_analyzer"
            - "%knp.doctrine_behaviors.reflection.is_recursive%"
            - "@knp.doctrine_behaviors.translatable_listener.current_locale_callable"
        tags:
            - { name: doctrine.event_subscriber }

    knp.doctrine_behaviors.translatable_listener.current_locale_callable:
        class:   "%knp.doctrine_behaviors.translatable_listener.current_locale_callable.class%"
        arguments:
            - "@service_container" # lazy request resolution
        public:  false

What am I missing?
Thank you very much for your help.

Translatable - How to access a property of the joined Translation entity in Symfony2 Form Type Entity with query_builder?

I have Category and CategoryTranslation entities and I want to load category.id and category_translation.title to form field, but I can't access title, because category has no method getTitle() (it is in the CategoryTranslation).

$builder
    ->add(
        'category',
        'entity',
        array(
            'class' => 'AcmeDemoBundle:Category',
            'property' => 'title',
            'query_builder' => function (CategoryRepository $repository) {
                return $repository->getAllCategoriesByLocaleQueryBuilder('en');
            },
        )
    )
);

The CategoryRepository method:

public function getAllCategoriesByLocaleQueryBuilder($locale)
{
    $queryBuilder = $this->getEntityManager()->createQueryBuilder();

    $queryBuilder
        ->select('c, c.id, ct.title')
        ->from('AcmeDemoBundle:Category', 'c')
        ->join('c.translations', 'ct')
        ->where('ct.locale = :locale')
        ->setParameter('locale', $locale);

    return $queryBuilder;
}

If I'm trying to select from CategoryTranslation when I can't set correct identifier for form field, because it is set from CategoryTranslation (CategoryTranslation.id but in this case I need CategoryTranslation.translatable_id)

I'm not sure if in this case I can use Symfony2 form field type entity or should I use other field type. Any suggestions?

Fallback and collection issue

Hello. This bundle is simple and effective.However i cant use it as server supports php 5.3
First i was wondering whether there is a way to support fallback if desired locale doesnt exist.Maybe you could use default locale if specified fails.

protected function findTranslationByLocale($locale)
{
    $translations = $this->getTranslations()->filter(function($translation) use ($locale) {
        return $locale === $translation->getLocale();
    });

    return $translations->first();
}

Also here why you dont use indexBy at metadata ?it would be simpler to use ->get($locale)

As for fallback i see no easy solution.. Eager or lazy loading and doing fallback at findTranslationByLocale code .In sql as i know there isnt an easy way to get the desired locale from the translations table and default if it doesnt exist apart coalesce which requires extra effort .Is there any real solution for this ?

having "getChildren" method already implemented in entity

Also, it may be common for entities using the tree to have "getChildren" method already implemented. Do you think that the "getChildren", "addChild" methods should be renamed to "getChildNodes" and "addChildNode" so these methods aren't overwritten?

Geocodable documentation is out of date

$listener->setGeolocationCallable(function($entity) use($geocoder) {
        $location = $geocoder->geocode($entity->getAddress());
        $geocoder->setLocation(new Point(
            $location->getLatitude(),
            $location->getLongitude()
        ));
    });

The listener is not correct because GeocodableListener::getLocation() must return a Point object, so it should be :

$listener->setGeolocationCallable(function($entity) use($geocoder) {
        $location = $geocoder->geocode($entity->getAddress());
        return new Point(
            $location->getLatitude(),
            $location->getLongitude()
        ));
    });

If I may, you should add the id of the GeocodableListerner (knp.doctrine_behaviors.geocodable_listener) in the documentation because as a novice I spent a while to find it :-)

Bug (typo+) in softDeletable doc

In README.md in softDeletable sample there is:

// get id
$id = $em->getId();

// now remove it
$em->remove($category);

// hey, i'm still here:
$category = $em->getRepository('Category')->findOneById($id);

// but i'm "deleted"
$category->isDeleted(); // === true

It does not work ;-(
My fix proposal:

// get id
$id = $category->getId();  // <---------------------- CHANGED

// now remove it
$em->remove($category);
$em->flush(); // <---------------------- ADDED

// hey, i'm still here:
$category = $em->getRepository('Category')->findOneById($id);

// but i'm "deleted"
$category->isDeleted(); // === true

[RFC] Timezonable behaviour

Hi guys,

Is there scope in the project to add a timezoneable behaviour? I'm thinking the behaviour would store the timezone of the last user to edit the entity in a $timezone class variable.

Additionally the timezone would be used to modify datetime objects flagged with timezoneable when the entity is loaded based on the current users timezone.

Cheers Leevi

Is it possible to have multiple roots?

Is it possible to have multiple roots?

I have the following Entity:

MenuItem:
    id
    menu_id
    name
    materializedPath

I need to be able to have multiple entities that do not have a root as they will just sit under a menu. The only items that would have a root is if they were under a specific MenuItem.

The tree seems to be built using only the first result.

[Geocodable] the DISTANCE function is broken.

Hi again,

As a follow up for this issue, I found another bug in the Geocodable trait, but this one is critical.

The signature of the constructor of your Point class looks like this :

public function __construct($latitude, $longitude);

But according to the documentation :

The module relies on representing Earth locations as values of type point, in which the first component is taken to represent longitude in degrees, and the second component is taken to represent latitude in degrees. Points are taken as (longitude, latitude) and not vice versa because longitude is closer to the intuitive idea of x-axis and latitude to y-axis.

Which is completely stupid because it's not compatible wtih the ll_to_earth function, which takes the latitude first.

Anyway, all your distance computations are off, which you can clearly see in the info I added here, since the first of your tests should fail.

But simply invert lat and long in the Point constructor would not be compatible with my new DISTANCE_IN_METERS function, not without some ugly hack (I think).

[ORM] Geocodable behaviour: use proper isEntitySupported logic in listener

In GeocodableListener method isEntitySupported checks only if method getLocation is present in entity. I find this incorrect, because for example I want to use location property in entity for storing city and country (not the actual location coordinates), but I don't need to use Geocodable behaviour. And because my entity has getLocation method listener is being used on prePersist/preUpdate which sets my location to NULL.
So instead it would be more convenient to check if the trait is being used in entity.

Timestampable Behaviour

When a child relationship updates, it does not update the parent even if it has Timestampable Trait. Is there a way we can force it to update the parent. I tried the following:

public function updateTimestamps()
    {
        if (null === $this->createdAt) {
            $this->createdAt = new \DateTime('now');
        }

        $this->updatedAt = new \DateTime('now');
        $this->getParent()->updateTimestamps();
    }

However, it does not work. I think this may be because updateTimestamps is a listener and Doctrine2 does not recognise any changes on the listener (It has to be recomputed I think?)

License?

the source files claim that the license is specified in the LICENSE file, but there is no such file. what is the license of this library?

[Translatable] Accessing translatable in Doctrine query builder

Hello,

I have Category and CategoryTranslation entities. Both are connected with Translatable.
I need to join CategoryTranslation back into the Category in Doctrine query builder.

$qb->join('ct.translatable', 'c');
(translatable comes from Knp\DoctrineBehaviors\Model\Translatable\Translation trait that is used by CategoryTranslation entity)

yells

"The parent object of entity result with alias 'c' was not found".`

Is it even possible? How to do that?

Fields from some traits not created in database. Might be useful to document.

Hi !

I have some entity (striped from non-pertinent code)

class MyEntity implements ORMBehaviors\Tree\NodeInterface, \ArrayAccess
{
    use ORMBehaviors\Tree\Node;
    use ORMBehaviors\Timestampable\Timestampable;
    use ORMBehaviors\Blameable\Blameable;
    use ORMBehaviors\Sluggable\Sluggable;

    private $id;
    //...
}

where the mappings are defined in a yaml configuration file.

I let doctrine:schema:update set up my database. The problem is that it does not create fields from Tree, Timestampable and Sluggable. The resulting schema is something like this :

id           | integer | non NULL | plain    |
createdby_id | integer |          | plain    |
updatedby_id | integer |          | plain    |
deletedby_id | integer |          | plain    |

Services and listeners where registered accordingly with the docs using the yaml file.

A specialized Repository is defined as described in the docs :

class MyEntityRepository extends EntityRepository
{
    use ORMBehaviors\Tree\Tree;  // There is a typo here in the docs
}

Here is a sample error thrown :

Doctrine\ORM\Query\QueryException: [Semantical Error] line 0, col 73 near
'materializedPath': Error: Class NameSpace\MyBundle\Entity\MyEntity has no field or
association named materializedPath

Caused by
Doctrine\ORM\Query\QueryException: SELECT t FROM
NameSpace\MyBundle\Entity\MyEntity t WHERE t.materializedPath LIKE :path
ORDER BY t.materializedPath ASC

thrown in this functional test method :

public function shouldBeAbleToAddChildMyEntity()
{
    $this->testedMyEntityService->persist($this->anAlreadyStoredMyEntity);

    $this->testedMyEntityService->persist($this->aValidMyEntity);
    $this->aValidMyEntity->setChildNodeOf($this->anAlreadyStoredMyEntity);

    $root = $this->entityManager
        ->getRepository('NameSpace\MyBundle\Entity\MyEntity')
        ->getTree();    // XXX EXCEPTION HERE

    $this->assertNotNull($root->getChildNodes());
}

This is resolved by manually adding the mapping informations for DoctrineBehaviors fields in my myentity.orm.yml file. I suppose this happens because code used via traits is considered in MyBundle and not in DoctrineBehavior and, as stated in the Symfony documentation,

A bundle can accept only one metadata definition format. For example, it's not possible
to mix YAML metadata definitions with annotated PHP entity class definitions.

What is not clear is why the Blameable fields are correctly set in the database schema. I did not find any annotation nor yaml mapping configuration for this trait.

My knowledge of PHP might be somewhat limited, but it took me some time to figure out. I think this could be documented.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.