Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine
This course is archived!

Making Fixtures Awesome with Alice

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.

Tip

A newer version of HauteLookAliceBundle has been released and portions of this tutorial won't apply to that new version.

Fixtures, those nice little bits of data that you can put into your database so that when you're developing locally you actually have something to look at: like products or users or whatever else you want to play with. I hate writing fixtures because I use this bundle (DoctrineFixturesBundle) and it's boring and manual and you end up building really big ugly fixture classes:

// a boring DataFixtures class
// ...

class MyFixtures implements FixtureInterface
{
    public function load(ObjectManager $manager)
    {
        $user1 = new User();
        $user1->setUsername('foo');
        // ...
        $manager->persist($user1);
        // repeat over and over...

        $manager->flush();
    }
}

The reason is that this library just doesn't do anything for you. It's entirely up to you to manage, persist and flush everything that you do.

Introducing Alice + Our Video Game Hero App

So I'm going to show you a better way, in fact a much better way with a library called Alice. I prepared a small Symfony application for us which we'll talk about in a second. And I've already started our built-in PHP Web server:

Tip

Want to code along? Beautiful! Just download the code on this page.

php app/console server:run

And here's our app, it's all about listing our favorite videogame heroes. Right now we're losing because there is nothing in this table. But that's what we're going to fix with Alice.

This table is actually pulling from the Character entity so this is what we actually need to save to the database.

Installing Alice via HauteLookAliceBundle

To install Alice we could do it directly but instead I'm going to use an awesome bundle called HautelookAliceBundle_. Let's grab the composer require command from it's README and paste that into the terminal:

composer require hautelook/alice-bundle

This bundle is a thin layer around the Alice library, which is something that let's us load fixtures with yml files, and the same DoctrineFixturesBundle that we were talking about before. This is a really nice combination because it's going to mean that we can still run our normal php app/console doctrine:fixtures:load. But after that, instead of writing raw PHP code, all of our fixtures are going to be in these really nice yml files.

And if that doesn't sound awesome yet, just hang with me. Alice is a lot more than yml files - it contains tons of goodies.

Next let's activate the bundle. In fact if you head back to its documentation you'll see that you need to initialize both this bundle and the DoctrineFixturesBundle in our AppKernel. So grab both of those lines, open the AppKernel and let's put it there:

// app/AppKernel.php
// ...

if (in_array($this->getEnvironment(), array('dev', 'test'))) {
    // ...

    $bundles[] = new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle();
    $bundles[] = new Hautelook\AliceBundle\HautelookAliceBundle();
}

But since I'm only going to be loading my fixtures when I'm developing, I'm going to go ahead and put these inside of the dev environment block. That way, in production I have just a little bit less in my application.

You do need one fixture class, but we can just copy it from the documentation and put it into our application. I'll create the DataFixtures/ORM directory. By the way this stuff does work with the ODM or other doctrine libraries. And I'll create a file called AppFixtures. Copy the contents in there and don't forget to update your namespace and rename the class:

// src/AppBundle/DataFixtures/ORM/AppFixtures.php
namespace AppBundle\DataFixtures\ORM;

use Hautelook\AliceBundle\Alice\DataFixtureLoader;
use Nelmio\Alice\Fixtures;

class AppFixtures extends DataFixtureLoader
{
    /**
     * {@inheritDoc}
     */
    protected function getFixtures()
    {
        return  array(
            __DIR__ . '/test.yml',
        );
    }
}

The fixtures class is special because it's already wired up to load yml files. Let's call ours characters.yml and then go ahead and create that file:

// src/AppBundle/DataFixtures/ORM/AppFixtures.php
// ...

protected function getFixtures()
{
    return  array(
        __DIR__ . '/characters.yml',
    );
}

Your First Alice yml File

Now, here is how Alice works. Inside the yml file this is now pure Alice code. You start with the full entity namespace. This tells Alice what type of object it's going to create. Below that, we just start inventing keys. These aren't important yet but they will be later when we start linking two entities together. Under that we just give each property a value. Let's create Yoshi:

# src/AppBundle/DataFixtures/ORM/characters.yml
AppBundle\Entity\Character:
    character1:
        name: Yoshi
        realName: T. Yoshisaur Munchakoopas
        highScore: 99999
        email: yoshi@nintendo.com
        tagLine: Yoshi!

Let's cheat and look back at the Character entity to see what other fields we want to fill in. We now have a fully functional and armed single-file fixture. So let's try it out.

Loading your Fixtures

As I mentioned earlier, this is a wrapper around the Doctrine fixtures library so we use the same php app/console doctrine:fixtures:load command to run everything. No errors is good so let's try refreshing the page. Yoshi!

Loading A LOT of Test Data (Ranges)

If this is all that Alice gave us I wouldn't be telling you about it. It actually gives us a ton more. So usually in fixtures you want a lot of things. Like five characters or ten characters or 50 blog posts or something like that.

One of the most powerful features of Alice is this range syntax:

# src/AppBundle/DataFixtures/ORM/characters.yml
AppBundle\Entity\Character:
    character1:
        name: Yoshi
        realName: T. Yoshisaur Munchakoopas
        highScore: 99999
        email: yoshi@nintendo.com
        tagLine: Yoshi!
    character{2..10}:
        name: Mario
        realName: Homo Nintendonus
        highScore: 50000
        email: mario@nintendo.com
        tagLine: Let's a go!

So, in this case we're going to be creating characters two through 10. Behind the scenes you can see how this is basically a for loop but the syntax is a lot cleaner. To test that out let's reload our fixtures:

php app/console doctrine:fixtures:load

And now Mario is taking over our database!

So we have 10 characters now but since nine of them are identical they're not very realistic. But this is where Alice gets really interesting. It has this special <> syntax which allows you to call functions that are special to Alice.

For example, when you're inside of a range you can use this syntax to call the <current()> function that's going to give us whatever index were at in that moment:

# src/AppBundle/DataFixtures/ORM/characters.yml
AppBundle\Entity\Character:
    # ...
    character{2..10}:
        name: Mario<current()>
        realName: Homo Nintendonus
        # ...

So let's reload our fixtures again and now we have Mario2, Mario3, Mario4.

Introducing Faker: For all your Fake Data Needs

So this is better but still not very realistic. Behind the scences Alice hooks up with another library called Faker_. And as it's name sounds it's all about creating fake data. Fake names, fake company names, fake addresses, fake e-mails - it supports a ton of stuff. To use Faker we just use that same syntax we saw and use one of the many built-in functions.

For example, one of the functions is called firstName(). Since this is going to return us some pretty normal names, let's put the word Super in front of it so at least it sounds like a superhero:

# src/AppBundle/DataFixtures/ORM/characters.yml
AppBundle\Entity\Character:
    # ...
    character{2..10}:
        name: Super <firstName()>
        realName: Homo Nintendonus
        # ...

Then we're going to use a few others like name(), numberBetween(), email() and sentence which gives us one random sentence:

# src/AppBundle/DataFixtures/ORM/characters.yml
AppBundle\Entity\Character:
    # ...
    character{2..10}:
        name: Super <firstName()>
        realName: <name()>
        highScore: <numberBetween(100, 99999)>
        email: <email()>
        tagLine: <sentence()>

These functions are pretty self-explanatory but if you Google for "Faker PHP" and scroll down on the README just a little bit, they have a huge list_ of all the functions that they support. They're actually called formatters but a lot of them take arguments.

For example you can see our numberBetween, sentence and even some things for creating random names where you can choose which gender you want. So let's check this out. Reload your fixtures, scroll back over refresh the page.

php app/console doctrine:fixtures:load

Now we have ten super friends and no identical data.

Making a Field (sometimes) Blank

If you want to make one of these fields sometimes empty you can do that as well. For example, if tagLine is optional then you may want to see what your set looks like when some of the characters don't have one. To do that create a percentage put a ? after it and then list what value you want:

# src/AppBundle/DataFixtures/ORM/characters.yml
AppBundle\Entity\Character:
    # ...
    character{2..10}:
        # ...
        tagLine: 80%? <sentence()>

So in this case 80% of the time we're going to get a random sentence and 20% of the time we're going to get nothing. So reload the fixtures, and this time you see that about 20% of our characters are missing their tag line.

Creating your Own Faker Formatter (Function)

So I love the random data, I love how easy this is. But one thing I don't like is that our names just aren't that realistic. We're dealing with video game heroes here and none of our names are actually of real video game heroes.

To fix this let's create our own formatter called characterName:

# src/AppBundle/DataFixtures/ORM/characters.yml
AppBundle\Entity\Character:
    # ...
    character{2..10}:
        name: <characterName()>
        realName: <name()>
        highScore: <numberBetween(100, 99999)>
        email: <email()>
        tagLine: <sentence()>

Now if you try this out you are going to get the error that the formatteris missing:

Unknown formatter "characterName"

So how do we create it? With the bundle it's super easy. Just go back to your fixtures class, AppFixtures and create a function called characterName. And in this function we just need to return a character name. I'll paste in a few of my favorites and then at the bottom we'll use the :phpfunction:array_rand function to return a random character each time Alice calls this:

// src/AppBundle/DataFixtures/ORM/AppFixtures.php
// ...

class AppFixtures extends DataFixtureLoader
{
    // ...

    public function characterName()
    {
        $names = array(
            'Mario',
            'Luigi',
            'Sonic',
            'Pikachu',
            'Link',
            'Lara Croft',
            'Trogdor',
            'Pac-Man',
        );

        return $names[array_rand($names)];
    }
}

I love when things are this simple!

php app/console doctrine:fixtures:load

Flip back to the browser and when you refresh this time, real video game heroes!

True Love with Relationships

So there's one more complication that I want to introduce, and that's relationships. I have an entity called Universe as in "Nintendo Universe" or "Sega Universe".

First, let's go into our yml file and create a few of these. We'll start just like before by putting the namespace and creating a few entries under that. So I'll have one for Nintendo, one for Sega and one for classic arcade:

# src/AppBundle/DataFixtures/ORM/characters.yml
AppBundle\Entity\Character:
    # ...

AppBundle\Entity\Universe:
    universe_nintendo:
        name: Nintendo
    universe_sega:
        name: Sega
    universe_arcade:
        name: Classic Arcade

The Character entity already has a ManyToOne_ relationship to universe on a universe property:

// src/AppBundle/Entity/Character.php
// ...

class Character
{
    // ...

    /**
     * @var Universe
     * @ORM\ManyToOne(targetEntity="Universe")
     */
    private $universe;
}

So our goal is to take these Universe objects and set them on the charcter property.

To reference another object, just use the @ symbol and then the internal key to that object. So we'll link Mario to the Nintendo universe and everyone else, for now, to the Sega Universe:

# src/AppBundle/DataFixtures/ORM/characters.yml
AppBundle\Entity\Character:
    character1:
        name: Yoshi
        # ...
        universe: @universe_nintendo

    character{2..10}:
        name: <characterName()>
        # ...
        universe: @universe_sega

AppBundle\Entity\Universe:
    universe_nintendo:
        name: Nintendo
    universe_sega:
        name: Sega
    universe_arcade:
        name: Classic Arcade
php app/console doctrine:fixtures:load

When we check it out now, sure enough we see Nintendo on top followed by 9 Segas. So I know you're thinking, "can we somehow randomly assign random universes to the characters?" And absolutely! In fact, the syntax is ridiculously straight forward. Just get rid of the sega part and put a star:

# src/AppBundle/DataFixtures/ORM/characters.yml
AppBundle\Entity\Character:
    # ...

    character{2..10}:
        # ...
        universe: @universe_*

AppBundle\Entity\Universe:
    universe_nintendo:
        name: Nintendo
    universe_sega:
        name: Sega
    universe_arcade:
        name: Classic Arcade

Now, Alice is going to find any keys that start with universe_ and randomly assign them to the characters. Reload things again and now we have a nice assortment of universes:

php app/console doctrine:fixtures:load

Using Multiple yml Files

Because our project is pretty small I've kept everything in a single file, which I recommend that you do until it gets just too big. Once it does, feel free to separate into multiple yml files.

In our case I'll create a universe.yml file and put the universe stuff in it:

# src/AppBundle/DataFixtures/ORM/universe.yml
# these have been removed from characters.yml
AppBundle\Entity\Universe:
    universe_nintendo:
        name: Nintendo
    universe_sega:
        name: Sega
    universe_arcade:
        name: Classic Arcade

Of course when you do this it's not going to work because it's only loading the characters.yml file right now. So we get a missing reference error:

Reference universe_nintendo is not defined

There are actually a few ways to load the two yml files but the easiest is to go back into your AppFixtures class and just add it to the array:

// src/AppBundle/DataFixtures/ORM/AppFixtures.php
// ...

protected function getFixtures()
{
    return  array(
        __DIR__ . '/universe.yml',
        __DIR__ . '/characters.yml',
    );
}

Unfortunately, order is important here. So since we're referencing the universes from within the characters.yml we need to load the universe.yml file first. Let's reload things to make sure they're working.

php app/console doctrine:fixtures:load

And they are!

Joyful Fixtures

To back up, after we installed the bundle we only really touched two things. The AppFixtures class, which has almost nothing in it, and our yml files which are very very small and straight forward. This is awesome! This puts the joy back into writing fixtures files for me and I absolutely love it.

There are a few topics that we haven't talked about like processors and templates but I'll cover those in a future lesson.

See you guys!

Leave a comment!

71
Login or Register to join the conversation
Default user avatar
Default user avatar Tael Kim | posted 5 years ago

DONT PANIC for old version
and see https://knpuniversity.com/s...
have fun!

2 Reply

Hey Tael,

Good cross reference, thanks!

Reply
Default user avatar
Default user avatar isomoar | posted 5 years ago

Awesome!

1 Reply
Default user avatar
Default user avatar Grzegorz Szaliński | posted 5 years ago | edited

In case someone runs into the same problem...
Since I'm taking this screencast after 2 years from its release, I had a lot of dependencies errors while loading composer repositories with


composer require hautelook/alice-bundle

I updated it with the particular version that was valid at that time (0.1.5), and it worked:


composer require hautelook/alice-bundle 0.1.5
1 Reply

Yep, good call! There is a new version of the library - and it's great - but it's *totally* different now :). This tutorial covers 0.1.5.

1 Reply
Default user avatar

hello ? I think I've been using a different thing ? Didn't have a problem with it yet , the nelmio/Alice one ?
Are they related ??
Another question I'm having , was looking through the documentation and not sure is it possible to select a random relationship like this ?

AppBundle\Entity\Conference:
conference{1..5}:
startat: <datetimethisdecade()>
comment: <realtext(420)>
place: @place_*

AppBundle\Entity\Place:
place_{1..10}
name: <city()>
address: <streetaddress()>
website: <domainname()>

Reply
Victor Avatar Victor | SFCASTS | rddro | posted 5 years ago | edited

Hey, rddro !

hautelook/alice-bundle is a bundle for standalone nelmio/alice library, which ports this lib and another one (fzaninotto/Faker) for the Symfony applications. If you see its dependencies - you will find nelmio/alice. So if you're on a Symfony app, you probably want to use this bundle instead of standalone library.

And yes, it's still possible to use random relationships (using wildcard ) in new version 2.x. Do you have any errors using it? Try to wrap it with quotes like `place: '@place_'`.

Cheers!

1 Reply
Default user avatar

Hello , yes it works with and without quotes but noticed something strange.
While running the fixtures multiple times, only the id of the place is regenerated everything else stays the same?
Only way to create something new after the first fixture load is to drop the database and recreate it.
Edit: Fixed , it seems it's running the fixtures in the order defined in the YML , so you'd have to put the relationship childrens before the parent.

Reply

Your "Edit" sounds right - iirc, the authors of the AliceBundle are working to address some "ordering" problems.

1 Reply
Marwen Avatar
Marwen Avatar Marwen | posted 8 months ago | edited

good day everyone
is there option for OneToOne persist, I tried this but doesn't work:
`
App\Entity\User:

user_{2..10}:
    email (unique): <email()>
    username (unique): <username()>
    roles: <randomElements(['ROLE_ENGINEER','ROLE_CLIENT'], 1)>
    password: <password()>

App\Entity\Engineer:

engineer_{2..5}:
    firstName: <firstName()>
    lastname: <lastName()>
    userRef (unique): '@user_<numberBetween(2, 10)>

<br />the error is: <br />
duplicate key value violates unique constraint Key (email)=(heath58@harris.org) already exists.
`

Reply

Hey Marwen,

Have you tried this?

engineer_{2..5}:
    userRef: '@user_<current>'

you can find more information about working with relationships here https://github.com/nelmio/alice/blob/master/doc/relations-handling.md

Cheers!

Reply
Marwen Avatar

yes but it doesn't make sense, example I want to make 10 User, 4 of them are Engineer and 6 are Client
so when using current() client_1 and engineer_1 will have the same user

Reply

Perhaps you'll have to create your users in two sections. One for creating users with the role engineer, and another one with the role client, then you can reference them as mentioned here in the docs https://github.com/nelmio/alice/blob/master/doc/complete-reference.md#handling-unique-constraints
If that doesn't help, I think you'll have to create a custom factory

Reply
Marwen Avatar

Note: I tried also userRef (unique): '@user_*' but no chance

Reply
Lionel-F Avatar
Lionel-F Avatar Lionel-F | posted 2 years ago

Hi guys, I know it's an old tutorial but when I click on the new version of tutorial there is nothing ... link is broken https://symfonycasts.com/sc...

Reply

Hey Lionel F.

Thanks for pointing it out, the problem is we do not have a newer version of this course yet. My apologies for any inconveniences

Reply
Default user avatar

Hello, great tutorial!

Is there any way to put this dependency (hautelook/alice-bundle) in my composer.json project file and only load it for development environment ?

Reply

Hi Sergio!

Good question! If you want, you can add it to the `require-dev` part of your `composer.json`: https://getcomposer.org/doc..., though at best, that simply means that it won't be downloaded to your disk in an environment, and disk space is cheap.

What you *really* want is to add it to AppKernel in the spot where it's only loaded in the `dev` environment: https://github.com/symfony/.... There's no downside to this, and it'll give you a very minor performance boost in the `prod` environment.

Cheers!

Reply
Default user avatar
Default user avatar Larry Garfield | posted 5 years ago

11:40... If you want to import your fixtures from scratch, you must first create the test universe.

Reply
Default user avatar

Is there a way to add image url(s) as well via this bundle? Maybe a field in db points to an image URL.

Reply

Hey Nick!

I *think* I know what you're asking, and I'm planning on covering it in one upcoming screencast. If I have a field that normally holds a value like "foo.png", and that's populated by uploading a file, then I would use processors: https://github.com/nelmio/a... to look for that file in some pre-configured directory and move it into some "uploads" directory (wherever your files normally upload to - you could even move to S3).

As far as the URL to the image, now that you have "foo.png" stored in your database and the file actually lives in the correct upload spot, it's up to you in your template to link to it correctly. Btw, I recommend using VichUploaderBundle to handle uploads and link to them.

Let me know if I hit on your question!

Reply
Default user avatar

Thanks for reply! Yes VichUploaderBundle is very good for Uploads. Also that's exactly what I mean!

Reply
Default user avatar
Default user avatar toioski | posted 5 years ago

Hi! Great tutorial!

I have only one question: is there any way to make a relation with data which already exist in the database?

E.g.
I want to generate fixtures for the entity Conversation which as 3 attributes:
- name
- creationDate
- creator -> this is ManyToOne with the entity User

Is it possible to say to the 'creator' attribute to take a random User from the database and not from another .yml file?

UPDATE:
I solved creating a custom function for Alice (like the one created in the screencast for super heroes names) which return a casual user id from the ones present in the database.

Reply

Great solution! Nothing is built in to do this, so I think you solved this perfectly!

Reply
Default user avatar
Default user avatar aguidis | posted 5 years ago

Hello, thanks for this tutorial I didn't know this cool library !

I tried to use it in my project but I always have this error in the console :

[Symfony\Component\Debug\Exception\ContextErrorException]

Notice: Array to string conversion

I don't have other information for debugging. I tried to remove some fields in my fixture yml file and when I run the doctrine:fixtures:load I have a SQL error like "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'registration_details' cannot be null". It means that Alice is trying to insert data right ?

Reply

Hey there!

Ok coo. So, I *probably* know what your issue is :). Somehow, you probably have some Alice code that is setting an array of data on a field that is mapped as a string on the database. I could be wrong, but Doctrine is probably trying to convert an array (that was set on an entity by Alice) into a string while saving. I would remove the alice lines one-by-one until this error goes away (like you were doing). When you finally don't have an error - or have the above error about a null constraint - it means the saving is happening, and probably the last line you removed is the problem. You could also open the core Doctrine code where the error is being thrown, and do a little var_dump() of the value right before the error. Then you can see what array value is trying to be turned into a string, which might help debugging.

I hope that helps!

Reply
Default user avatar

Thanks a lot Ryan you were right. In my last field (a string one) I used a function that returns an array (paragraphs()) Shame on me !

I'll no longer make this error ^^ Thank you for your advices

Reply

:thumbsup: nice work!

Reply

Hi, thanks for this screencast!
I also found typo in the text. I think you wanted to write "characters.yml" instead of "test.yml" in second code block (after sentence "Let’s call ours characters.yml and then go ahead and create that file:").

Reply

You're right - good catch! I just updated it :) https://github.com/knpunive...

Tanks!

Reply

Very quickly! :)
I didn't know that code was available on GitHub, it would be better to create a pull request.
Thanks for quick fix

Reply

It's a poorly-publicized fact - I hope to make that more obvious soon :). Thanks again!

1 Reply
Default user avatar
Default user avatar Martin Bittner | posted 5 years ago

Does this work for Symfony 3.2.8? it seems to be for symfony2 only?
When I look at the packagist.org, the description of hautelook bundle is "Symfony2 Bundle to manage fixtures with Alice and Faker.".

I tried following instruction multiple times, from here or from their respective github documentation, and I can't make it work with my symfony installation. Always having error when using date() faker.

Reply

Hey Martin Bittner!

This bundle works for Symfony 3 also, but *this* specific tutorial uses an old version of the bundle. But if you're following their GitHub documentation, yep, it should work! What's the date you have with the date() faker function?

Cheers!

Reply
Default user avatar
Default user avatar Paweł Montwiłł | posted 5 years ago

Great tut!

It would be nice to update it with the latest changes to Alice (at least in the text below):
1. Using Hautelook\AliceBundle\Doctrine\DataFixtures\AbstractLoader instead of DataFixtureLoader
2. Launching update with hautelook_alice:doctrine:fixtures:load (or h:d:f:l) instead of doctrine:fixtures:load.

Reply

Yea, I've been thinking about this! I haven't used it much, but the new version of the bundle looks harder to use. Recently, I used Alice + DoctrineFixturesBundle directly (with no other bundle) and was very happy.

1 Reply
Default user avatar
Default user avatar Paweł Montwiłł | weaverryan | posted 5 years ago

Thanks for a quick reply. Can you please drop a few lines how you use it?

BTW brilliant tutorials :)

Reply

Ah, thank you! It'll be covered in the new Doctrine tutorial (near the end) which will start coming out this week: http://knpuniversity.com/sc.... Here's a preview on the script (https://github.com/knpunive... (if that helps) - the actual code blocks will be at the first link soon. Cheers!

Reply
Default user avatar

When i try to load the fixtures i get this error:

[InvalidArgumentException]
Could not find any fixtures to load in:
- /Applications/MAMP/htdocs/starwarsevent/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBund
.... and more

Help please

Reply

Hey Oscar!

The bundle looks in the DataFixtures/ORM directory of each of your bundles for fixture classes. If it doesn't find *any*, you'll get this error. So double check that you have the fixture class in DataFixtures/ORM. But also, this tutorial covers an older version of the bundle - so this could be from a difference with the new version! In the next few days, we'll have an updated section about using Alice for fixtures in our Doctrine tutorial: http://knpuniversity.com/sc....

Cheers!

Reply
Default user avatar

Hello o/ Anyone have some clue how to add the user role ? Tried to set it like roles: 'a:1:{i:0;s:10:"ROLE_ADMIN";}' but it didn't work properly.

Reply
Default user avatar
Default user avatar rddro | rddro | posted 5 years ago | edited

Update : it would seem you can echo them like so
roles:


$role= ['ROLE_ADMIN', 'ROLE_USER', 'ROLE_SUPER_ADMIN', 'ROLE_CLIENT'];
echo '['.$names[array_rand($role)].']';

but I think there might be a better way

Reply

Hey rddro!

Basically, you want to set an array onto roles (since roles is an array field). To do that in YAML, use this syntax:


users_{1..10}:
    username: # ...
    # ...
    roles: [ROLE_USER, ROLE_ADMIN]

    # ... or, if you want something random, it should be something like this
    roles: <randomElements(['ROLE_USER', 'ROLE_ADIMN', 'ROLE_CLIENT'])>

Cheers!

Reply
Default user avatar

Hello , seems it doesn't like it if i define it as an array not sure why.
If i put [] in the fixture for the role it will generate an array of array
a:1:{i:0;a:1:{i:0;s:10:"ROLE_ADMIN";}} instead of a:1:{i:0;s:10:"ROLE_ADMIN";}
If I leave it as a string like roles : ROLE_ADMIN it will generate the good array.
Maybe it had something to do with the setRoles() annotation in the entity. Cheers

Reply

Hmm - yea it definitely looks like we're ending up with an array of arrays - array(array('ROLE_ADMIN')) instead of just array('ROLE_ADMIN').

I would double-check your setRoles() method - make sure you're not accidentally wrapping the array in another array before setting it. For example, this would be a problem:


public function setRoles($roles)
{
    $this->roles = array($roles); // this is bad, you'd end up with 2 arrays
}

If this isn't the problem, then I would dump the $roles argument in setRoles() to see what is being passed to you:


public function setRoles($roles)
{
    dump($roles);die;
}

Cheers!

Reply
Default user avatar

😂😂😂

$this->roles = array($roles); Indeed this was the case all good. Don't remember why I changed this was testing something and forgot to change it back >.<
Thanks

Reply

Hello Ryan! I just installed the bundle latest version and found out the class you extend doesn't exist any longer, nonetheless in the documentation they extend the class AbstractLoader. I ran the usual command fixutures:load and my class is there but no data added to the data base. How can I debug a command? Because I thing the problem is the route where I placed the yaml file. Tried var_dump to no avail. Thanks

Reply

Found the solution. I was previously using regular Doctrine Fixtures, so having a look at this excerpt https://github.com/hauteloo... found that running php app/console h:d:f:l or hautelook_alice:doctrine:fixtures:load will load only alice fixtures. The confusing part is that when running the regular doctrine:fixtures:load I see that the alice fixtures are alse executed. Thanks any way

Reply

It looks like the bundle got a nice new facelift - I'll take a look at what's been updated :).

Reply

Yeah, it is more in line with symfony's way of doing things. The processors need to be defined as services with arguments and stuff. One question, how would I load alice's fixtures on my tests? I tried this $fixtures = $container->get('hautelook_alice.doctrine.command.load_command'); but didn't work. Thanks

Reply
Cat in space

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

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": ">=5.3.3",
        "symfony/symfony": "2.5.*", // v2.5.5
        "doctrine/orm": "~2.2,>=2.2.3", // v2.4.6
        "doctrine/doctrine-bundle": "~1.2", // v1.2.0
        "twig/extensions": "~1.0", // v1.1.0
        "symfony/assetic-bundle": "~2.3", // v2.5.0
        "symfony/swiftmailer-bundle": "~2.3", // v2.3.7
        "symfony/monolog-bundle": "~2.4", // v2.6.1
        "sensio/distribution-bundle": "~3.0", // v3.0.6
        "sensio/framework-extra-bundle": "~3.0", // v3.0.2
        "incenteev/composer-parameter-handler": "~2.0", // v2.1.0
        "hautelook/alice-bundle": "~0.1" // 0.1.5
    },
    "require-dev": {
        "sensio/generator-bundle": "~2.3" // v2.4.0
    }
}
userVoice