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!

  • 2020-07-01 Krzysztof Kujawski

    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.

  • 2020-05-25 Diego Aguiar

    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!

  • 2020-05-24 Alexander Steenbrugge

    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

  • 2020-04-24 weaverryan

    Hey Krzysztof Kujawski!

    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!

  • 2020-04-21 Krzysztof Kujawski

    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.

  • 2020-03-05 weaverryan

    Hey Krzysztof Kujawski!

    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...

    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!

  • 2020-03-03 Krzysztof Kujawski

    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...

  • 2020-02-24 Victor Bocharsky

    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!

  • 2020-02-24 Kutay Deril

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

  • 2020-01-08 weaverryan

    Hey Mike!

    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!

  • 2020-01-07 Mike

    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)

  • 2019-08-26 Diego Aguiar

    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!

  • 2019-08-26 AXAstudillo

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

  • 2019-07-17 Diego Aguiar

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

  • 2019-07-17 Avraham Markov

    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!!!

  • 2019-07-16 Diego Aguiar

    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!

  • 2019-07-14 Avraham Markov

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

  • 2019-07-12 Diego Aguiar

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

    Cheers!

  • 2019-07-12 Avraham Markov

    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!

  • 2019-07-11 Diego Aguiar

    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!

  • 2019-07-11 Avraham Markov

    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.

  • 2019-07-11 Avraham Markov

    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.

  • 2019-07-10 Diego Aguiar

    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/cur...

    Cheers!

  • 2019-07-10 Avraham Markov

    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

  • 2019-07-09 Diego Aguiar

    Hey Avraham Markov

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

    Cheers!

  • 2019-07-09 Diego Aguiar

    Hey Avraham Markov

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


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

    Cheers!

  • 2019-07-09 Avraham Markov

    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?

  • 2019-07-09 Avraham Markov

    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?

  • 2019-04-03 Usuri

    Thx

  • 2019-04-03 Victor Bocharsky

    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!

  • 2019-04-03 Usuri

    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.

  • 2019-01-28 Diego Aguiar

    Hey 00001111zz

    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!

  • 2019-01-25 00001111zz

    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

  • 2019-01-10 Deuklyoung Ko

    Thank you so much!!

  • 2019-01-10 weaverryan

    Hey there!

    You already did almost all of the steps. There is no command to automatic remove everything. So, delete the class in Entity, make a migration to drop the table (both you already did) and then manually delete the class in Repository. There is nothing else to remove :).

    Cheers!

  • 2019-01-10 Deuklyoung Ko

    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.

  • 2018-12-07 Usuri

    Thx. Works now.

  • 2018-12-06 Vladimir Sadicov

    Hey Usuri

    It's caused by outdated maker-bundle. I'll duplicate my recommendation to solve this issue

    composer update symfony/maker-bundle

    Cheers!

  • 2018-12-06 Usuri

    Why in my project when write in console class name for new entity and hit enter then script is finished with message "Success" and I can't add fields?

  • 2018-12-03 Victor Bocharsky

    Hey Hassan,

    Unfortunately, MakerBundle does not cover this case, because this bundle is meant to be a generator that generates code in for your *project*, not for your third-party bundles. So, you have 2 options - create that entity manually in the proper directory in your bundle, or cheat a bit and generate an entity with MakerBundle that will put this into your project, from where you can move that file into the bundle. And of course, you will need to fix namespaces in it, but that's probably it.

    I hope this helps.

    Cheers!

  • 2018-12-02 Hassan Shuvo

    How to make entity in custom bundle directory.please Help?

  • 2018-09-28 Diego Aguiar

    Hey Maxim Mandrik

    Yep, you are right, some times subtitles interfere with important parts of the video, we'll discuss internally what can be done

    Cheers!

  • 2018-09-28 Diego Aguiar

    Hey Maxim Mandrik

    Thanks for highlighting that typo - I'm about to fix it.

    Cheers!

  • 2018-09-28 Maxim Mandrik

    Subtitles make it difficult to see an important part of the screen. Yes, they can be hidden and displayed again, but this is not convenient.
    It would be nice to be able to move them.

  • 2018-09-28 Maxim Mandrik

    I think I found a typo in the text and subtitles:
    "and setter for methods for each one"
    And should be:
    "and setter methods for each one".

  • 2018-08-20 Victor Bocharsky

    Hey IordanisGR ,

    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!

  • 2018-08-20 IordanisGR

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

  • 2018-08-20 Victor Bocharsky

    Hey IordanisGR ,

    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!

  • 2018-08-19 IordanisGR

    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

  • 2018-08-17 weaverryan

    Hey Nikeev!

    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!

  • 2018-08-17 Nikeev

    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 :)

  • 2018-08-16 weaverryan

    Hey Nikeev!

    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!

  • 2018-08-16 Nikeev

    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!

  • 2018-06-25 Diego Aguiar

    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!

  • 2018-06-25 Matthieu Lagarde

    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 :) ?

  • 2018-05-07 Victor Bocharsky

    Hey Yeison,

    Yeah, you're right. But this tutorial is the third one based on this "Stellar" project and we've already installed this MakerBundle in previous tutorial, see: https://knpuniversity.com/s... . So if you're with us from the beginning of the Symfony 4 track - you should have this bundle installed already :)

    But thanks for this tip for others, it may be useful.

    Cheers!

  • 2018-05-06 Yeison J. Espinoza

    Hi, i think there is a missing part:
    when you use ".bin/console make:entity", you need to install that "make" to be able to run "make" :D