Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine
This tutorial has a new version, check it out!

Creating an Entity Class

Video not working?

It looks like your browser may not support the H264 codec. If you're using Linux, try a different browser or try installing the gstreamer0.10-ffmpeg gstreamer0.10-plugins-good packages.

Thanks! This saves us from needing to use Flash or encode videos in multiple formats. And that let's us get back to making more videos :). But as always, please feel free to message us.

Doctrine is an ORM, or object relational mapper. A fancy term for a pretty cool idea. It means that each table in the database will have a corresponding class in our code. So if we want to create an article table, it means that we need to create an Article class. You can totally make this class by hand - it's just a normal PHP class.

Generating with make:entity

But there's a really nice generation tool from MakerBundle. We installed MakerBundle in the last tutorial, and before I started coding, I updated it to the latest version to get this new command. At your terminal, run:

php bin/console make:entity

Stop! That word "entity": that's important. This is the word that Doctrine gives to the classes that are saved to the database. As you'll see in a second, these are just normal PHP classes. So, when you hear "entity", think:

That's a normal PHP class that I can save to the database.

Let's call our class Article, and then, cool! We can start giving it fields right here. We need a title field. For field "type", hmm, hit "?" to see what all the different types are.

Notice, these are not MySQL types, like varchar. Doctrine has its own types that map to MySQL types. For example, let's use "string" and let the length be 255. Ultimately, that'll create a varchar column. Oh, and because we probably want this column to be required in the database, answer "no" for nullable.

Next, create a field called slug, use the string type again, and let's make it's length be 100, and no for nullable.

Next, content, set this to text and "yes" to nullable: maybe we allow articles to be drafted without content at first. And finally, a publishedAt field with a type set to datetime and yes to nullable. If this field is null, we'll know that the article has not been published.

When you're done, hit enter to finish. And don't worry if you make a mistake. You can always update things later, or delete the new entity class and start over.

Investigating the Entity Class

So... what did that just do? Only one thing: in src/Entity, this command generated a new Article class:

... lines 1 - 2
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\ArticleRepository")
*/
class Article
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $title;
/**
* @ORM\Column(type="string", length=100)
*/
private $slug;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $content;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $publishedAt;
public function getId()
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(string $slug): self
{
$this->slug = $slug;
return $this;
}
public function getContent(): ?string
{
return $this->content;
}
public function setContent(?string $content): self
{
$this->content = $content;
return $this;
}
public function getPublishedAt(): ?\DateTimeInterface
{
return $this->publishedAt;
}
public function setPublishedAt(?\DateTimeInterface $publishedAt): self
{
$this->publishedAt = $publishedAt;
return $this;
}
}

Well... to be fully honest, there is also a new ArticleRepository class, but I want you to ignore that for now. It's not important yet.

Anyways, this Article class is your entity. And, check it out! It's a normal, boring PHP class with a property for each column: id, title, slug, content, and publishedAt:

... lines 1 - 9
class Article
{
... lines 12 - 16
private $id;
... lines 18 - 21
private $title;
... lines 23 - 26
private $slug;
... lines 28 - 31
private $content;
... lines 33 - 36
private $publishedAt;
... lines 38 - 91
}

What makes this class special are the annotations! The @ORM\Entity above the class tells Doctrine that this is an entity that should be mapped to the database:

... lines 1 - 4
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\ArticleRepository")
*/
class Article
{
... lines 12 - 91
}

Then, above each property, we have some annotations that help doctrine know how to store that exact column:

... lines 1 - 4
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\ArticleRepository")
*/
class Article
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $title;
/**
* @ORM\Column(type="string", length=100)
*/
private $slug;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $content;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $publishedAt;
... lines 38 - 91
}

Actually, find your browser and Google for "doctrine annotations reference" to find a cool page. This shows you every annotation in Doctrine and every option for each one.

Back at the code, the properties are private. So, at the bottom of the class, the command generated getter and setter methods for each one:

... lines 1 - 9
class Article
{
... lines 12 - 38
public function getId()
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(string $slug): self
{
$this->slug = $slug;
return $this;
}
public function getContent(): ?string
{
return $this->content;
}
public function setContent(?string $content): self
{
$this->content = $content;
return $this;
}
public function getPublishedAt(): ?\DateTimeInterface
{
return $this->publishedAt;
}
public function setPublishedAt(?\DateTimeInterface $publishedAt): self
{
$this->publishedAt = $publishedAt;
return $this;
}
}

There's one really important thing to realize: this class is 100% your class. Feel free to add, remove or rename any properties or methods you want.

And... yea! With one command, our entity is ready! But, the database is still empty! We need to tell Doctrine to create the corresponding article table in the database. We do this with migrations.

Leave a comment!

61
Login or Register to join the conversation
Mike P. Avatar
Mike P. Avatar Mike P. | posted 3 years ago

One advice from my side:

If your $content property can be set publicly, I propose to change the annotation of "private $content;":

Old:
* @ORM\Column(type="text", nullable=true)

New:
* @ORM\Column(type="text", length=65535, nullable=true)

Before the change, Doctrine sets the field inside the DB to "longtext", which accepts string up to 4GB of space, which is in my case unwanted because everyone can set this field.
After the change Doctrine sets the type="text" correctly (Which means max. 65535 Chars)

1 Reply

Hey Mike P.!

Yea, if this is a field that some user can set directly (e.g. a comment box like this), then limiting the content is probably a good idea. I would use Symfony's Length validator to do this - so that the user gets a nice validation error message if it's too long. Adding the length to the column is also a nice idea - but I think of that more as a database "optimization" (not making the field bigger in the database than it needs to be) and use validation as the true "police" for preventing the long data :).

Cheers!

Reply
Iordanis G. Avatar
Iordanis G. Avatar Iordanis G. | posted 5 years ago

How can i generate the entity in my own Bundle ??
For example. I have UserBundle. By making "make:entity \User\Entity\User" ,
The command generates the file "User.php" at the desirable location( App/User/Entity).
But the "UserRepository.php" created at the App/Repository, when the desirable is at User/Repository.
In a few words, how can i generate the entity with the symfony 3.4 style "MyBundle: EntityName" ?
Thanks

1 Reply

Hey Iordanis G. ,

Good question! Currently it's impossible to do in one command run, you can find some related comments in MakerBundle: https://github.com/symfony/... . So, you can cheat: generate entity and its repository in src/Entity/ and src/Repository/ folders, but then manually move them into the bundle you want, and that's it. Just don't forget to tweak namespaces to match the new location.

Cheers!

1 Reply
Iordanis G. Avatar
Iordanis G. Avatar Iordanis G. | Victor | posted 5 years ago

ohh yes. After a lot research, i find out that "bundless" symfony 4 , for a reason wants one namespace for the entities!

Reply

Hey Iordanis G. ,

Yes, exactly! Well, we still use bundles, but now bundles are need to share code between projects only. So you may still want to make a bundle, but when you need to share the code between projects, and this bundle you'll install with Composer, so no bundles in src/ dir now.

Cheers!

1 Reply
Anton N. Avatar
Anton N. Avatar Anton N. | posted 5 years ago | edited

Hello! Thanks for tutorial!

I have a question about setters and form validation. Yes, it's not only about entities but maybe you could help.
Maker bundle and also PhpStorm generates setter with variable type. For, example integer:


public function setSomeNumber(int $someNumber): self
{
        $this->someNumber= $someNumber;
return $this;
    }

$someNumber has assert annotation.
 * @Assert\Range(
     *     min = 0,
     *     max = 100
     * )

So there should be a number between 0 and 100. And it works fine, until user type some text value into field (no html5 validation). In that case app crashes with an error: "Notice: A non well formed numeric value encountered". So, as I understand, first of all form tries to fill entity object and than validate it. But it fails because of type declaration. If I remove it, validation works fine.

Is there any right way to deal with it? Thanks!

1 Reply

Hey Anton N.!

GREAT question! What Symfony field type are you using for the someNumber field? Have you tried the NumberType? I believe (but I'm not 100% sure about this) it will throw a validation error before setting the bad data on the field.

So, try that out. If I'm wrong - let me know - I do think there may be some cases where the type-hints complicate things with the form+validation layer (but again, I can't remember 100% if this is one of those cases or not).

Cheers!

1 Reply
Anton N. Avatar
Anton N. Avatar Anton N. | weaverryan | posted 5 years ago | edited

Hello! Thanks for reply!

Yes, someNumber is integer value, but I used TextType to get simple text intput without browser up/down number arrows (customer asked =)). Now I made an experiment and it seems you are right, I need to use NumberType. In that case if I put some text value into number field, form saves ok without any errors, but field value becomes null. If I manually change html to input type="text" and put some text value, in that case Symfony form validate and highlight field as wrong value.

So thank you! Now I know that I shouldn't mess form fields types :)

1 Reply

Hey Anton N.!

Awesome! Woohoo! This "sanity validation" (that's my term) that form fields provide is not a very-well-known feature of the form fields. We normally think of them as just "how the form looks", but it's also "how the data is processed". Anyways - glad it's working!

Cheers!

1 Reply
Matthieu L. Avatar
Matthieu L. Avatar Matthieu L. | posted 5 years ago

Hi,
I love your tutorial so far, it is really awesome, crystal clear and funny to watch, so congrats and keep up the good work :)!
I had a question on how to store files uploaded by users (for instance profile pictures) in Symfony 4. I have seen that I can install a bundle dedicated to file upload VicUploaderBundle (https://github.com/dustin10.... Yet, I wonder what should be the best folder to store these files... Should it be in the public folder alongside static files ? Or should it be in a subfolder of the var folder ? Or maybe elsewhere :) ?

1 Reply
Tim K. Avatar

Hey Matthieu

Thanks for your kind words :)

Answering your question, yes, VichUploaderBundle is a great bundle for handling file uploads in Symfony. What I usually do is to store all uploaded files into a public directory, because I always have to show them to the public, but if you don't have to access them via web, then you can store them in any other place you want

Cheers!

1 Reply
mofogasy Avatar
mofogasy Avatar mofogasy | posted 1 year ago

hi, how to reuse my entities in another project ?
I have a projet that includes many entities and their controller and crud, etc

I want to reuse them in another projet. So I want to copy paste the files.

But I already have a problem at entity creation:
The cmd shows that make: entity creates the entity class and the repository class (and nothing else) .So I copy paste these two to the new projet but they are ignored:
When I try make:migration I got No database changes were detected. When I try make:entity and type the name of the entity class (Taxe), I got _Cannot find the entity manager for class "App\Entity\Taxe" . and make:controller with Taxe return _ Entity "Taxe" doesn't exist; .

So globally, how to create entity without the maker ? How can I reuse my entities/controllers/etc from another project pls?

Reply
mofogasy Avatar
mofogasy Avatar mofogasy | posted 1 year ago

Hello I need help:
Hello, I have a projet that includes many entities and their controller and crud, etc

I want to reuse them in another projet. So I want to copy paste the files.

But I already have a problem at entity creation:
The cmd shows that make: entity creates the entity class and the repository class (and nothing else) .So I copy paste these two to the new projet but they are ignored:
When I try make:migration I got No database changes were detected. When I try make:entity and type the name of the entity class (Taxe), I got _Cannot find the entity manager for class "App\Entity\Taxe" . and make:controller with Taxe return _ Entity "Taxe" doesn't exist; .

So globally, how to create entity without the maker ? How can I reuse my entities/controllers/etc from another project pls?

Reply

Hey Grenouille,

If you want to reuse some code - the best thing to do this without duplications is to make a bundle and install it in all your projects where that code is needed. Bundles are meant to keep a reusable code that can be added to many projects. We have a course about how to create a bundle here: https://symfonycasts.com/sc...

But if you just copy/paste some entities from one project to another - well, they just should work. The only problem is that if you would need to change something in that entity - you would need to do the same changes in both projects (or whatever projects you have). That's why extracting them to a bundle is a better idea - you can change them all at once in the bundle and the install new changes to all your projects.

What about the error - that's weird. Please, make sure that your entity mapping matches in both your projects. I.e. if you have PHP annotations mapping configured in one project, the same should be configured in another project so that it could just work after you copy/pasted the entities. Also, make sure the path is correct, i.e. src/Entity/YourEntityName.php (but it may depend on your project configuration).

But you don't have to use Maker to create an entity, you can create if manually of course, though it's recommend to you Maker to avoid misprints. You can easily install the maker in any project, and then run the make:entity command. But if you decided to make an entity manually - the best would be to copy/paste already existent entity and change it to your needs, i.e. change class name, file name, fields it has, etc. You can also copy/paste some example code from the official Symfony docs and change it to your needs as well.

I hope this helps!

Cheers!

Reply
mofogasy Avatar

Hey, thanks for the tips,
my main issue was version differences. The most impacting one is indeed annotations mapping. I tried to change them manually but I still got errors related to repository.

For the bundle, I won't use them as my first project won't be maintened. It will be a reference only

So I use another project as base with symfony 6 and the copy paste works.
Thanks for your help

Reply

Hey Grenouille,

You're welcome! You can also use "bin/console doctrine:schema:validate" command to make sure your mapping is valid and matches the DB schema. That's a good command to run when you solve the errors you see first.

Cheers!

Reply
Default user avatar
Default user avatar Alexander Steenbrugge | posted 3 years ago | edited

Hi,

Thx for the great course.

I unfortunately have a problem with the migrations.
When i use make:migration or doctrine:migrations:diff i always get the same migration.

`
final class Version20200524213128 extends AbstractMigration
{

public function getDescription() : string
{
    return '';
}

public function up(Schema $schema) : void
{
    // this up() migration is auto-generated, please modify it to your needs
    $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

    $this->addSql('ALTER TABLE category CHANGE parent_id parent_id INT DEFAULT NULL');
    $this->addSql('ALTER TABLE course CHANGE published_at published_at DATETIME DEFAULT NULL, CHANGE image_filename image_filename VARCHAR(255) DEFAULT NULL');
}

public function down(Schema $schema) : void
{
    // this down() migration is auto-generated, please modify it to your needs
    $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

    $this->addSql('ALTER TABLE category CHANGE parent_id parent_id INT DEFAULT NULL');
    $this->addSql('ALTER TABLE course CHANGE published_at published_at DATETIME DEFAULT \'NULL\', CHANGE image_filename image_filename VARCHAR(255) CHARACTER SET utf8mb4 DEFAULT \'NULL\' COLLATE `utf8mb4_unicode_ci`');
}

}
`

I noticed that this happens whit every nullable field.

I use mysql true xampp the mysql version is 5.5 amd that is what i use in my .env file.

Could you plz help me figure this out?

thx,
Alexander

Reply

Hey Alexander Steenbrugge

That's a bit weird :)
Can you try specifying the server version in your config/packages/doctrine.yaml file


doctrine:
    dbal:
        server_version: '5.5'

if that doesn't work, try upgrading MySql to 5.7, that's the recommended version to work with Symfony4+

Cheers!

Reply
Krzysztof-K Avatar
Krzysztof-K Avatar Krzysztof-K | posted 3 years ago

I can't find anything about using database views as Entity.
I have db view and I want tu use it in query builder in repositories.
What should I do? I'm using migrations of course, so view could (will?) be destroyed on migration.

The only one topic I've found is oldie - https://stackoverflow.com/q...

Reply

Hey Krzysztof K.!

Hmm, really good question :). As the StackOverflow shows, it "seems" simple enough... though there are some details to think about:

1) As I understand it, Doctrine doesn't really care whether an entity is mapped to a table or view. So, create a view (that part is up to you), then create a new entity that maps to it. Adding the readOnly=true thing is probably also a good idea.

2) The real problem is how to get Doctrine migrations to not try to overwrite your view as a real table. What you basically want to do is tell Doctrine that you want it to ignore your view when it calculates the database migration diff. That's always been possible, but recently it's become easier to do that (and I don't think this part is properly discussed on the StackOverflow). Here's how to do it:

A) Create a class (it won't have any interface or base class) with an __invoke($assetName): bool method - like in this class https://github.com/doctrine/DoctrineBundle/blob/master/Dbal/BlacklistSchemaAssetFilter.php

B) When we're finished, Doctrine will call this method during the "diff" process. It will pass you the table/view name that it's looking at (via the $assetName argument). If it matches your view, return false. Otherwise return true.

C) To tell Doctrine about this class, add the doctrine.dbal.schema_filter. That would look something like this:


# config/services.yaml
services:
    # all the normal stuff

    App\Doctrine\YourNewFilterClassName:
        tags: [doctrine.dbal.schema_filter]

That should do it! Let me know how it goes!

Cheers!

Reply
Krzysztof-K Avatar

It looks ok - I mean your instructions leads to read-only entity that is not destroying the view in the database. But... solving that bring me to another problem. There is no primary key in views! Even if it is possible to join (I didn't try yet) over field, migration fails over the no-primary-key error in creation of foreign key in another "plain" entity that join with that view.
I think it will force me to rethink my data model unless there's a method to stop creating that foreign key.

Reply

Hey Krzysztof K.!

Hmm, I'm not sure about this part - I don't have a lot of experience with views, so this is a little beyond my knowledge :). If you're setting up a relationship from a real entity to your view... then yea, that might be a problem due to the foreign key. But there is nothing that *makes* you execute the foreign key in the migration. It's annoying, but you can (of course) remove it manually from your migration, though I'm not sure if you can *avoid* having it be regenerated each time.

Let me know if you find anything out!

Cheers!

Reply
Krzysztof-K Avatar

There is a method.

ste had described it in answer at https://stackoverflow.com/q...

I'm exploring another way - materialized views in Oracle, but for temporary purposes I'm using modified IgnoreFksListener.

I've named all my views with 'view' prefix in entities, made them readonly and avoid to generate foreign keys with ignoreFksListener.

1 Reply
Default user avatar
Default user avatar Kutay Deril | posted 3 years ago

What if we want to create with odm? Is there command line for it too?

Reply

Hey Kutay,

Unfortunately, there is no way to generate it with MakerBundle (yet), but but might happen in the future. Btw, here's the thread you might be interested in:
https://github.com/symfony/...

Cheers!

Reply
Default user avatar
Default user avatar AXAstudillo | posted 3 years ago

what about if I want to make:entity from a table already created on my DDBB?

Reply
Diego-B Avatar
Diego-B Avatar Diego-B | AXAstudillo | posted 3 years ago | edited

Hey AXAstudillo

I think you will have to delete your entire project and start from scratch! :p
Haha, I'm just kidding. I'm no 100% sure of the answer but I think you have to create an entity class that map all of your table's field. Adding all the necessary constraints, foreign keys, etc, etc. Give it a try and let us know if it worked

Cheers!

Reply
Pedro-Araujo Avatar
Pedro-Araujo Avatar Pedro-Araujo | Diego-B | posted 9 months ago

Hi Diego. I don't quite understand your answer. So if I want to create an entity from an existing table I have to do it by hand? Can't I use the maker bundle for this?

Reply

Hey Pedro!

Yeah, probably the easiest way to do it by hand, especially if you need to do this for one or a few tables.. but sure you can leverage the maker bundle. I bet Diego mostly means that you need to make sure that the field is mapping to the correct column name in the DB, because the Maker will generate the field base on the configuration strategy in your project and on the entity property name you add.

Though if you have many legacy tables that you want to migrate to entities - doing it manually may be more time-consuming. I would recommend you to take a look at doctrine:mapping:import command that may help you with importing mapping information from an existing database. You can give it a try and see if it works for you well, otherwise fallback to the manual process with Maker.

I hope this helps!

Cheers!

Reply
Avraham M. Avatar
Avraham M. Avatar Avraham M. | posted 4 years ago

Hello!
I have created Product Entity according to tutorial
https://symfony.com/doc/cur...
Yet
$this->getDoctrine()->getRepository(Product::class)
causes
MappingException Class Product is not a valid entity or mapped super class

Can you please suggest solution?

Reply

Hey Avraham M.

Did you linked your repository to the product class? e.g.


/**
 * @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
 */
class Product

Cheers!

Reply
Avraham M. Avatar

Thanks Diego Aguiar !
yet I did added annotation to Entity class

namespace Bla\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Table(name="products")
* ORM\Entity(repositoryClass="Bla\Repository\ProductRepository")
*/
class Product

Is it about doctrine.yml file? symfony 4.3

orm:
auto_generate_proxy_classes: '%kernel.debug%'
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
mappings:
Bla:
is_bundle: false
type: annotation
dir: '%kernel.project_dir%/Bla/Entity'
prefix: 'Bla\Entity'
alias: Bla
//==============

I have an error:

Attempted to call an undefined method named "staticProxyConstructor" of class "Language_2c90222"

when services.yml lazy loading is lazy: true.
Can it cause Doctrine fail?
Please recommend lazy loading resource as well.

Thanks

Reply

I think I've detected your problem. You are trying to fetch the repository like this (Assuming you are running this code on a controller's method)


$this->getDoctrine()->getRepository(Product::class)

// Do it this way
$this->getDoctrine()->getManager()->getRepository(Product::class)

Give it a try and let me know.

You can read more about lazy services here: https://symfony.com/doc/current/service_container/lazy_services.html

Cheers!

Reply
Avraham M. Avatar
Avraham M. Avatar Avraham M. | MolloKhan | posted 4 years ago | edited

Hello Diego Aguiar!
Thanks!
I succeed to obtain $entityManager = $this->getDoctrine()->getManager();
Yet still MappingException: Class "App\Entity\Patient" is not a valid entity or mapped super class.
`
$patient = new Patient();
$patient->setFname('Alex1');

// FAILS
// MappingException: Class "App\Entity\Patient" is not a valid entity or mapped super class.
$entityManager->persist($patient);
// FAILS
// MappingException: Class "App\Entity\Patient" is not a valid entity or mapped super class.
`

Reply

That's weird!

Are you using annotations for your metadata or yaml? you can't use both. I may need to see your code. Is it possible to you to upload your project to Github or any other platform and give me access?

Cheers!

Reply
Avraham M. Avatar

Thanks Diego Aguiar!

Idea 1) metadata or yaml.

If I understand you correctly, I don't use Product.yml
There are doctrine.yml and services.yml .

Idea 2) Github -
Great idea, please let me check.
Is it possible to send a link to you privately?

Have a great weekend!

Reply

yes, send me the link to diego@symfonycasts.com

Cheers!

Reply
Avraham M. Avatar

Thanks Diego Aguiar
sent zipped project to email address from papaabramg@gmail.com

Reply

Hey man
I think I found the problem. In your Patient entity you missed an starting @ on line 8 ORM\Entity(repositoryClass="Ewave\Repository\PatientRepository")
Also, try enabling the auto_mapping Doctrine config


// doctrine.yaml
doctrine:
    orm:
        auto_mapping: true

Give it a try and let me know (Didn't have enough time to set up your project and try it myself). Cheers!

Reply
Avraham M. Avatar

Diego, thank you very very much!
You did it!!!
@ was missing..
ORM\Entity(repositoryClass="Ewave\Repository\PatientRepository")
=>

@ORM\Entity(repositoryClass="Ewave\Repository\PatientRepository")
set auto_mapping:true, as well, now it works.

Thank you very very much!!!

1 Reply

Awesome! I'm super glad to hear that everything is working as expected.
Cheers!

Reply
Avraham M. Avatar
Avraham M. Avatar Avraham M. | posted 4 years ago

Hello!
php /bin/console make:entity

I get
[ERROR] Only annotation mapping is supported by make:entity,

and when created Entity Product manually,
$this->getDoctrine()->getRepository(Product:class)
returns
MappingException Class Entity is not a valid entity or mapped super class.

Can you please suggest solution?

Reply

Hey Avraham M.

Yeah, MakerBundle works with annotations only. Btw, I replied to you on the other comment about the repository problem

Cheers!

Reply
Dominik Avatar
Dominik Avatar Dominik | posted 4 years ago | edited

Hi. Can I add own logic in entity setter? Is allowed add logic in this place. Or not?
Example.
On the top of document I defined allowed letters, and in setter I'm checking if incoming value is one of the allowed letters.
If not how to brake proces? Throw exception?

`
$allowedLetters = ['a','b','c'];

public function setLetter($letter){

   if(!in_array($letter,$allowedLetters)){
        throw new \Exception('Bad letter');
    }

    $this->letter = $letter;

}

`

Thank you.

Reply

Hey Usuri,

Technically you can do it :) But, by design, it's not recommended. Though, it depends! If you need to do a few actions, like "update invoice" and "send email" - better name that method properly e.g. "updateInvoiceAndSendEmail()". Though, in your case, I think it's totally valid to check that input value is valid and throw an exception if not - it's just validation to prevent incorrect state of your object 👍

Cheers!

Reply
Dmytro K. Avatar
Dmytro K. Avatar Dmytro K. | posted 4 years ago

Strange, but i don't have getId() method in /Entity/Article.php
There is "private $id" declared, but no corresponding getter.
Has there been any recent updates that require me adding an ID field manually with make:entity?

I created an Entity a bit differently because i didn't update maker at first (i think so). So firstly the Entity was created and process finished, no fields were offered to create. At this point i executed "composer update" and tried to recreate the Entity and now i was offered to add fields. I followed all the steps, but getId method was not created. Everything else looks ok.

Let me please know what should i consider next time in order to have getId in the Entity. Thank you

Reply

Hey Dmytro K.

Interesting situation :)

Maker asked you to add more fields because it detected that you alrady have an Article entity, if you wan't to repeat the process from the beginning, then you would have to remove the class file and re-run maker. But you don't have to, just add that getId() method manually and keep going

Cheers!

Reply
Deuklyoung K. Avatar
Deuklyoung K. Avatar Deuklyoung K. | posted 4 years ago

Hi, can I ask something?

How to remove table and entity class source If I want to drop a table by made make:entity?
There are any console command to clearly remove table and ORM class source?

I removed a php file in Entity folder and executed command "php bin/console make:migratiion".
Then, they made drop table query automatically.
But repository.php still leaves in Repository folder.

I want to remove repository.php file also by one command.

Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": "^7.1.3",
        "ext-iconv": "*",
        "composer/package-versions-deprecated": "^1.11", // 1.11.99
        "knplabs/knp-markdown-bundle": "^1.7", // 1.7.0
        "knplabs/knp-time-bundle": "^1.8", // 1.8.0
        "nexylan/slack-bundle": "^2.0,<2.2.0", // v2.0.0
        "php-http/guzzle6-adapter": "^1.1", // v1.1.1
        "sensio/framework-extra-bundle": "^5.1", // v5.1.4
        "stof/doctrine-extensions-bundle": "^1.3", // v1.3.0
        "symfony/asset": "^4.0", // v4.0.4
        "symfony/console": "^4.0", // v4.0.14
        "symfony/flex": "^1.0", // v1.17.6
        "symfony/framework-bundle": "^4.0", // v4.0.14
        "symfony/lts": "^4@dev", // dev-master
        "symfony/orm-pack": "^1.0", // v1.0.6
        "symfony/twig-bundle": "^4.0", // v4.0.4
        "symfony/web-server-bundle": "^4.0", // v4.0.4
        "symfony/yaml": "^4.0" // v4.0.14
    },
    "require-dev": {
        "doctrine/doctrine-fixtures-bundle": "^3.0", // 3.0.2
        "easycorp/easy-log-handler": "^1.0.2", // v1.0.4
        "fzaninotto/faker": "^1.7", // v1.7.1
        "symfony/debug-bundle": "^3.3|^4.0", // v4.0.4
        "symfony/dotenv": "^4.0", // v4.0.14
        "symfony/maker-bundle": "^1.0", // v1.4.0
        "symfony/monolog-bundle": "^3.0", // v3.1.2
        "symfony/phpunit-bridge": "^3.3|^4.0", // v4.0.4
        "symfony/profiler-pack": "^1.0", // v1.0.3
        "symfony/var-dumper": "^3.3|^4.0" // v4.0.4
    }
}
userVoice