How can I use a configuration setting from config.yml in annotation - doctrine-orm

Sometimes, I just need to place the value with a config from the end user, just like the database prefix, uploaded File maxSize like below, and etc...
/**
* File
*
* #ORM\Table(name="{projectName}media_file")
* #ORM\Entity(repositoryClass="FileRepository")
* #ORM\HasLifecycleCallbacks()
*/
class File
{
/**
* #var File
*
* #Assert\File(maxSize="{configFromYML}")
*/
protected $file;
What can I do for it? thanks

As far as I know, this is not possible: the configuration parameters are only available in the container.
For the table prefix, maybe you can use the following solution:
How to setup table prefix in symfony2
For the validation, I think the only way to do this is to create a custom validation constraint and to configure it as a service: http://symfony.com/doc/master/validation/custom_constraint.html#constraint-validators-with-dependencies
Hope this will help!

Related

The database schema is not in sync with the current mapping file (but it is !)

I just fixed some things in my code. I'm now trying to validate my schema
php bin/console doctrine:schema:validate
Doctrine tells me my mapping is correct but my database schema is not. So I'm doing a
schema:update --dump-sql
which results in the same ALTER again and again, that I already performed many times.
Here is the ALTER :
ALTER TABLE migration_versions CHANGE version version VARCHAR(14) NOT NULL;
I did it (with --force), the entity is reflecting the change already :
**
* MigrationVersions
*
* #ORM\Table(name="migration_versions")
* #ORM\Entity
*/
class MigrationVersions
{
/**
* #var string
*
* #ORM\Column(name="version", type="string", length=14, nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $version;
I am correct right ? its varchar, lenght 14...
And so is it in my database
I don't think Im making a mistake here but I may be missing something.
Have you already verified that the server_version in the doctrine config file is correct? (config/packages/doctrine.yaml in symfony5)
It happened to me that I was using MariaDB (version 10.4.11-MariaDB - Source distribution) and in the file doctrine.yaml the server_version parameter had the value 5.7.
After I corrected that, the error no longer occurred.
Also you can check this question

UploadableFilePath field in entity definition is ignored (uploadable doctrine extensions)

Summary
My problem is connected with the fact that the entity field marked with #Gedmo\UploadableFilePath annotation is ignored by Symfony3. I am using the Uploadable behavior extension for Doctrine2.
CODE
In my entity I have:
/**
* #ORM\Column
* #Gedmo\UploadableFileName
*/
private $name;
/*
* #ORM\Column
* #Gedmo\UploadableFilePath
*/
private $path;
SYMPTOMS
At first, I have noticed though that the path column is not generated in MySQL.
Then I found out that whenever I delete name field I get the following error:
[Gedmo\Exception\InvalidMappingException] Class
"AppBundle\Entity\plik" must have an UploadableFilePath or Uploadable
FileName field.
Documentation
In doctrine-uploadable documentation I see that:
#Gedmo\Mapping\Annotation\UploadableFilePath: This annotation is used
to set which field will receive the path to the file. The field MUST
be of type "string". Either this one or UploadableFileName annotation
is REQUIRED to be set.
so it seems that I should be able to set $path field only.
Help request
Please advice why is UploadableFilePath field not being generated and why can't I delete the $name field?
It seems that I have made a simple typo. There was lack of one * in the comment line.
/**
* #ORM\Column
* #Gedmo\UploadableFilePath
*/
private $path;
It seems that symfony ignores annotations in such a case.

Entity-class mapping invalid: inconsistent with each other

I have a table "cms_objects" // Object.php - that stores all object info
I have another table "cms_media" // Media.php - that stores all media info
An object can have many media items (post with lots of different images)
In Object.php
/**
* #ORM\OneToMany(targetEntity="Media", mappedBy="Object")
*/
private $cms_media;
In Media.php
/**
* #ORM\ManyToOne(targetEntity="Object", inversedBy="cms_media")
* #ORM\JoinColumn(name="object_id", referencedColumnName="id")
*
* #Annotation\Exclude()
*/
private $object;
When I run: php public/index.php orm:validate-schema - I get:
[Mapping] FAIL - The entity-class 'Application\Entity\Cms\Media' mapping is invalid:
* The mappings Application\Entity\Cms\Media#object and Application\Entity\Cms\Object#cms_media are inconsistent with each other.
[Mapping] FAIL - The entity-class 'Application\Entity\Cms\Object' mapping is invalid:
* The association Application\Entity\Cms\Object#cms_media refers to the owning side field Application\Entity\Cms\Media#Object which does not exist.
Ideally, I need to be able to create a ZF2 form with element: 'media' or 'cms_media' but I haven't been able to validate it yet...
You can try to use FQCN inside the annotations. Instead of
/**
* #ORM\OneToMany(targetEntity="Media", mappedBy="Object")
*/
try
/**
* #ORM\OneToMany(targetEntity="Application\Entity\Cms\Media", mappedBy="Object")
*/
in both entities.
Also i would like to recommend using camelCased entity properties instead of underscored_ones. Hydration process of the entities with underscored properties using DoctrineObject hydrator is problematic. You can find more details here.
BEWARE - Using unnecessary bi-directional associations increases your object graph and domain model complexity. Best practice is avoiding bi-directional associations if possible.
For this case, you can rewrite the same mapping using uni-directional relation between Post (Object) and Media entities if you don't need reverse access from Media to Post like
$media->getPost()
For example Application/Entity/Cms/Post.php :
/** #ORM\Entity **/
class Post
{
/**
* One to many, unidirectional
* #ORM\ManyToMany(targetEntity="Application\Entity\Cms\Media")
* #ORM\JoinTable(name="post_to_media",
* joinColumns={#ORM\JoinColumn(name="post_id", referencedColumnName="id")},
* inverseJoinColumns={
* #ORM\JoinColumn(name="media_id", referencedColumnName="id",unique=true)
* })
**/
private $media;
public function __construct()
{
$this->media = new \Doctrine\Common\Collections\ArrayCollection();
}
// ...
}
and Application/Entity/Cms/Media.php :
/** #ORM\Entity **/
class Media
{
// No need to know about post
}

Manually add new column in Doctrine2 not working

I inherited a zend framework code with doctrine2.
I am trying to add a new column manually to no avail.
1) I create the last_viewed column in db which is dateTime format.
2) I added in the entity file
/**
* #var datetime $lastViewed
*/
protected $last_viewed;
/**
* Set lastViewed
*
* #param datetime $lastViewed
*/
public function setlastViewed($lastViewed) {
$this->last_viewed = $last_viewed;
}
/**
* Get lastViewed
*
* #return datetime
*/
public function gelastViewed() {
return $this->last_viewed;
}
3) Updated the YML file
last_viewed:
type: datetime
But when I try and retrive via
$user->gelastViewed()
I get an empty value.
Also when the entity proxy is generated I don't see the column name in the function "__sleep" rest all other columns are there.
Any suggestions as to how to add this manually.
Turns out cache was the culprit. Restarted Memcache and it works now !!!

Stof\DoctrineExtensionsBundle: missing identifier/primary key for Doctrine2

I am trying to get the Stof\DoctrineExtensionsBundle to run to be able to use DoctrineExtensions easily. However, the PHP interpreter tells me:
No identifier/primary key specified for Entity 'Stof\DoctrineExtensionsBundle\Entity\Translation'. Every Entity must have an identifier/primary key.
Does anyone know how to circumvent this problem? I guess it is possible somewhere in the annotations of Doctrine2, but I do not understand it that much and there already is an "orm:index" value (renaming it by "orm:Id", which seems to be the required value, does not work).
That’s the code of Translation entity class shipped with DoctrineExtensions:
/**
* Stof\DoctrineExtensionsBundle\Entity\Translation
*
* #orm:Entity(repositoryClass="Gedmo\Translatable\Entity\Repository\TranslationRepository")
* #orm:Table(
* name="ext_translations",
* indexes={#orm:index(name="translations_lookup_idx", columns={
* "locale", "object_class", "foreign_key"
* })},
* uniqueConstraints={#orm:UniqueConstraint(name="lookup_unique_idx", columns={
* "locale", "object_class", "foreign_key", "field"
* })}
* )
*/
class Translation extends AbstractTranslation
{
}
By the way, that’s the git repository if this helps anything. But I was not able to find this point within the documentation: https://github.com/stof/DoctrineExtensionsBundle
You can try to disable the stofdoctrineextensions in your app/config/config.yml before generate your entities getters/setters like this:
mappings:
StofDoctrineExtensionsBundle: false
Looks like the entities generator doesn't support external mapping yet.