Symfony2 Jobeet Day 3: The Data Model

The Relational Model

The user stories from the previous day describe the main objects of our project: jobs, affiliates, and categories. Here is the corresponding entity relationship diagram:

In addition to the columns described in the stories, we have also added created_at and updated_at columns. We will configure Symfony2 to set their value automatically when an object is saved or updated.

The Database

To store the jobs, affiliates and categories in the database, Symfony2 uses Doctrine ORM. To define the database connection parameters you have to edit the app/config/parameters.ini file (for this tutorial we will use MySQL):

;app/config/parameters.ini
[parameters]
    database_driver   = pdo_mysql
    database_host     = localhost
    database_name     = jobeet
    database_user     = root
    database_password = password

Now that Doctrine knows about your database, you can have it create the database for you (if you did not already created it):

php app/console doctrine:database:create

The Schema

To tell Doctrine about our objects, we will create “metadata” files that will describe how our objects will be stored in the database:

# src/Ens/JobeetBundle/Resources/config/doctrine/Category.orm.yml
Ens\JobeetBundle\Entity\Category:
  type: entity
  table: category
  id:
    id:
      type: integer
      generator: { strategy: AUTO }
  fields:
    name:
      type: string
      length: 255
      unique: true
  oneToMany:
    jobs:
      targetEntity: Job
      mappedBy: category
    category_affiliates:
      targetEntity: CategoryAffiliate
      mappedBy: category

 

# src/Ens/JobeetBundle/Resources/config/doctrine/Job.orm.yml
Ens\JobeetBundle\Entity\Job:
  type: entity
  table: job
  id:
    id:
      type: integer
      generator: { strategy: AUTO }
  fields:
    type:
      type: string
      length: 255
      nullable: true
    company:
      type: string
      length: 255
    logo:
      type: string
      length: 255
      nullable: true
    url:
      type: string
      length: 255
      nullable: true
    position:
      type: string
      length: 255
    location:
      type: string
      length: 255
    description:
      type: text
    how_to_apply:
      type: text
    token:
      type: string
      length: 255
      unique: true
    is_public:
      type: boolean
      nullable: true
    is_activated:
      type: boolean
      nullable: true
    email:
      type: string
      length: 255
    expires_at:
      type: datetime
    created_at:
      type: datetime
    updated_at:
      type: datetime
      nullable: true
  manyToOne:
    category:
      targetEntity: Category
      inversedBy: jobs
      joinColumn:
        name: category_id
        referencedColumnName: id
  lifecycleCallbacks:
    prePersist: [ setCreatedAtValue ]
    preUpdate: [ setUpdatedAtValue ]

 

# src/Ens/JobeetBundle/Resources/config/doctrine/Affiliate.orm.yml
Ens\JobeetBundle\Entity\Affiliate:
  type: entity
  table: affiliate
  id:
    id:
      type: integer
      generator: { strategy: AUTO }
  fields:
    url:
      type: string
      length: 255
    email:
      type: string
      length: 255
      unique: true
    token:
      type: string
      length: 255
    created_at:
      type: datetime
  oneToMany:
    category_affiliates:
      targetEntity: CategoryAffiliate
      mappedBy: affiliate
  lifecycleCallbacks:
    prePersist: [ setCreatedAtValue ]

 

# src/Ens/JobeetBundle/Resources/config/doctrine/CategoryAffiliate.orm.yml
Ens\JobeetBundle\Entity\CategoryAffiliate:
  type: entity
  table: category_affiliate
  id:
    id:
      type: integer
      generator: { strategy: AUTO }
  manyToOne:
    category:
      targetEntity: Category
      inversedBy: category_affiliates
      joinColumn:
        name: category_id
        referencedColumnName: id
    affiliate:
      targetEntity: Affiliate
      inversedBy: category_affiliates
      joinColumn:
        name: affiliate_id
        referencedColumnName: id

The ORM

Now Doctrine can generate the classes that define our objects for us with the command:

php app/console doctrine:generate:entities EnsJobeetBundle
Generating entities for bundle "EnsJobeetBundle"
  > backing up Job.php to Job.php~
  > generating Ens\JobeetBundle\Entity\Job
  > backing up Category.php to Category.php~
  > generating Ens\JobeetBundle\Entity\Category
  > backing up CategoryAffiliate.php to CategoryAffiliate.php~
  > generating Ens\JobeetBundle\Entity\CategoryAffiliate
  > backing up Affiliate.php to Affiliate.php~
  > generating Ens\JobeetBundle\Entity\Affiliate

If you look in the Entity directory from EnsJobeetBundle, you will find the newly generated classes in there: Affiliate.php, Category.php, CategoryAffiliate.php and Job.php. Open Job.php and set the created_at and updated_at values as below:

// src/Ens/JobeetBundle/Entity/Job.php
// ...
public function setCreatedAtValue()
{
  if(!$this->getCreatedAt())
  {
    $this->created_at = new \DateTime();
  }
}
// ...
public function setUpdatedAtValue()
{
  $this->updated_at = new \DateTime();
}

Do the same for created_at value of the Affiliate class:

// src/Ens/JobeetBundle/Entity/Affiliate.php
// ...
public function setCreatedAtValue()
{
  $this->created_at = new \DateTime();
}

This will make Doctrine to set the created_at and updated_at values when saving or updating objects. This behavior was defined in the Job.orm.yml and Affiliate.orm.yml files listed above.

We will also ask Doctrine to create our database tables (or to update them to reflect our setup) with the command:

php app/console doctrine:schema:update --force
Updating database schema...
Database schema updated successfully! "7" queries were executed

This task should only be really used during development. For a more robust method of systematically updating your production database, read about Doctrine migrations.

The Initial Data

The tables have been created in the database but there is no data in them. For any web application, there are three types of data: initial data (this is needed for the application to work, in our case we some initial categories and an admin user), test data (needed for the application to be tested) and user data (created by the users during the normal life of the application).

To populate the database with some initial data we will use DoctrineFixturesBundle. To setup this bundle we have to follow the next steps:

1. Add the following to your deps file:

[doctrine-fixtures]
    git=http://github.com/doctrine/data-fixtures.git

[DoctrineFixturesBundle]
    git=http://github.com/doctrine/DoctrineFixturesBundle.git
    target=/bundles/Symfony/Bundle/DoctrineFixturesBundle
    version=origin/2.0

2. Update the vendor libraries:

php bin/vendors install --reinstall

3. Register the Doctrine\Common\DataFixtures namespace in app/autoload.php before Doctrine\Common:

// ...
$loader->registerNamespaces(array(
    // ...
    'Doctrine\\Common\\DataFixtures' => __DIR__.'/../vendor/doctrine-fixtures/lib',
    'Doctrine\\Common' => __DIR__.'/../vendor/doctrine-common/lib',
    // ...
));

4. Register the Bundle DoctrineFixturesBundle in app/AppKernel.php:

// ...
public function registerBundles()
{
    $bundles = array(
        // ...
        new Symfony\Bundle\DoctrineFixturesBundle\DoctrineFixturesBundle(),
        // ...
    );
    // ...
}

Now that everything is set up we will create some new classes to load data in a new folder in our bundle: src/Ens/JobeetBundle/DataFixtures/ORM.

// src/Ens/JobeetBundle/DataFixtures/ORM/LoadCategoryData.php
namespace Ens\JobeetBundle\DataFixtures\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Ens\JobeetBundle\Entity\Category;

class LoadCategoryData extends AbstractFixture implements OrderedFixtureInterface
{
  public function load(ObjectManager $em)
  {
    $design = new Category();
    $design->setName('Design');

    $programming = new Category();
    $programming->setName('Programming');

    $manager = new Category();
    $manager->setName('Manager');

    $administrator = new Category();
    $administrator->setName('Administrator');

    $em->persist($design);
    $em->persist($programming);
    $em->persist($manager);
    $em->persist($administrator);

    $em->flush();

    $this->addReference('category-design', $design);
    $this->addReference('category-programming', $programming);
    $this->addReference('category-manager', $manager);
    $this->addReference('category-administrator', $administrator);
  }

  public function getOrder()
  {
    return 1; // the order in which fixtures will be loaded
  }
}

 

// src/Ens/JobeetBundle/DataFixtures/ORM/LoadJobData.php
namespace Ens\JobeetBundle\DataFixtures\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Ens\JobeetBundle\Entity\Job;

class LoadJobData extends AbstractFixture implements OrderedFixtureInterface
{
  public function load(ObjectManager $em)
  {
    $job_sensio_labs = new Job();
    $job_sensio_labs->setCategory($em->merge($this->getReference('category-programming')));
    $job_sensio_labs->setType('full-time');
    $job_sensio_labs->setCompany('Sensio Labs');
    $job_sensio_labs->setLogo('sensio-labs.gif');
    $job_sensio_labs->setUrl('http://www.sensiolabs.com/');
    $job_sensio_labs->setPosition('Web Developer');
    $job_sensio_labs->setLocation('Paris, France');
    $job_sensio_labs->setDescription('You\'ve already developed websites with symfony and you want to work with Open-Source technologies. You have a minimum of 3 years experience in web development with PHP or Java and you wish to participate to development of Web 2.0 sites using the best frameworks available.');
    $job_sensio_labs->setHowToApply('Send your resume to fabien.potencier [at] sensio.com');
    $job_sensio_labs->setIsPublic(true);
    $job_sensio_labs->setIsActivated(true);
    $job_sensio_labs->setToken('job_sensio_labs');
    $job_sensio_labs->setEmail('job@example.com');
    $job_sensio_labs->setExpiresAt(new \DateTime('2012-10-10'));

    $job_extreme_sensio = new Job();
    $job_extreme_sensio->setCategory($em->merge($this->getReference('category-design')));
    $job_extreme_sensio->setType('part-time');
    $job_extreme_sensio->setCompany('Extreme Sensio');
    $job_extreme_sensio->setLogo('extreme-sensio.gif');
    $job_extreme_sensio->setUrl('http://www.extreme-sensio.com/');
    $job_extreme_sensio->setPosition('Web Designer');
    $job_extreme_sensio->setLocation('Paris, France');
    $job_extreme_sensio->setDescription('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in.');
    $job_extreme_sensio->setHowToApply('Send your resume to fabien.potencier [at] sensio.com');
    $job_extreme_sensio->setIsPublic(true);
    $job_extreme_sensio->setIsActivated(true);
    $job_extreme_sensio->setToken('job_extreme_sensio');
    $job_extreme_sensio->setEmail('job@example.com');
    $job_extreme_sensio->setExpiresAt(new \DateTime('2012-10-10'));

    $em->persist($job_sensio_labs);
    $em->persist($job_extreme_sensio);

    $em->flush();
  }

  public function getOrder()
  {
    return 2; // the order in which fixtures will be loaded
  }
}

Once your fixtures have been written, you can load them via the command line by using the doctrine:fixtures:load command:

php app/console doctrine:fixtures:load

Now check your database, you should see the data loaded into tables.

The job fixtures file references two images. You can download them (http://www.ens.ro/downloads/sensio-labs.gif, http://www.ens.ro/downloads/extreme-sensio.gif) and put them under the web/uploads/jobs/ directory.

See it in Action in the Browser

Now let’s use some magic! Run at the command prompt:

php app/console doctrine:generate:crud --entity=EnsJobeetBundle:Job --route-prefix=ens_job --with-write --format=yml

This will create a new controller src/Ens/JobeetBundle/Controllers/JobController.php with actions for listing, creating, editing and deleting jobs (and their corresponding templates, form and routes). To view this in the browser we must import the new routes that were created in src/Ens/JobeetBundle/Recources/config/routing/job.yml into our bundle main routing file:

# src/Ens/JobeetBundle/Resources/config/routing.yml
EnsJobeetBundle_job:
    resource: "@EnsJobeetBundle/Resources/config/routing/job.yml"
    prefix: /job

EnsJobeetBundle_homepage:
    pattern:  /hello/{name}
    defaults: { _controller: EnsJobeetBundle:Default:index }

We will also need to add a __toString() method to our Category class to be used by the Category drop down from the edit job form:

// src/Ens/JobeetBundle/Entity/Category.php
// ...
public function __toString()
{
  return $this->getName();
}

Clear the cache:

php app/console cache:clear --env=prod
php app/console cache:clear --env=dev

You can now test the job controller in a browser: http://jobeet.local/job/ or, in development environment, http://jobeet.local/app_dev.php/job/

You can now create and edit jobs. Try to leave a required field blank, or try to enter an invalid date. That’s right, Symfony has created basic validation rules by introspecting the database schema.

Final Thoughts

That’s all. Today, we have barely written PHP code but we have a working web module for the job model, ready to be tweaked and customized. Remember, no PHP code also means no bugs!

Symfony2 Jobeet Day 4: The Controller and the View

Symfony2 Jobeet Day 2: The Project

77 thoughts on “Symfony2 Jobeet Day 3: The Data Model

  1. Really useful tutorial.

    One question.

    In the Jobs DataFixture I’m just wondering if the $em->merge(…) on the referenced Category Entity is necessary for the manyToOne relationship to be correctly persisted…

    Only the category_id needs to be persisted in the Job Entity, so the Category Entity doesn’t actually change, so I’m not sure if you need to add the Category Entity to the Managed Objects to be persisted by this Entity Manager… Or am I missing something ?

  2. Hi
    Thanx for your tutorial series.

    I have a problem with genertating entity classes, I get this error:
    [RuntimeException]
    Namespace “Ens” does not contai
    n any mapped entities.
    doctrine:generate:entities [--path="..."] [--no-backup] name

    Please can you help?

    • Hi Bruno,

      Have you used the same name for your bundle (Ens/JobeetBundle)?

      Have you created the metadata files in src/Ens/JobeetBundle/Resources/config/doctrine directory (Category.orm.yml, Job.orm.yml, Affiliate.orm.yml and CategoryAffiliate.orm.yml)?

      And, in the end, have you run the exact doctrine command, php app/console doctrine:generate:entities EnsJobeetBundle?

      • Hi Dragos,

        After followed up all name conventions, I am getting the same error.

        [RuntimeException]
        Namespace “Ens” does not contai
        n any mapped entities.
        doctrine:generate:entities [--path="..."] [--no-backup] name

        Regards
        Sudeep Jain

  3. Hi Dragos

    Thanx for the reply, and sorry I made a mistake on the bundle name.
    Now it is fine.
    I continue your tutorials.

  4. When I click create new entry get 500 error

    Catchable Fatal Error: Argument 1 passed to Symfony\Component\Form\Extension\Core\ChoiceList\MonthChoiceList::__construct() must be an instance of IntlDateFormatter, null given, called in D:\wamp\www\cpm-new\vendor\symfony\src\Symfony\Component\Form\Extension\Core\Type\DateType.php on line 88 and defined in D:\wamp\www\cpm-new\vendor\symfony\src\Symfony\Component\Form\Extension\Core\ChoiceList\MonthChoiceList.php line 24

    • I have this error also. My play time is up for today so I will be continuing tomorrow and if I address it I will update here. If you fix it also, can you post your solution for my benefit please?

    • Hi Shamsh,

      After some looking at the code mentioned by the exception I ended up on StackOverflow where php_intl was mentioned. I turned this on in my php.ini and set a default locale (en_utf8 for me) in the same file and it works now. On to day 4 for me :)

      Thank you so much Dragos for putting this set together. I went through Jobeet 1 a couple of years ago but drifted into Microsoft world but now I’m back in PHP it made more sense to start again with Symfony2 any yours is a great translation of the original tutorials.

  5. when i am trying to run the following command

    “php app/console doctrine:fixtures:load”

    i am getting this error msg.

    > purging database
    > loading [2] Ens\JobeetBundle\DataFixtures\ORM\LoadJobData
    ‘stty’ is not recognized as an internal or external command,
    operable program or batch file.

    can some plz help me to sort with this….

      • this is the page
        https://github.com/symfony/symfony/commit/417130506798627a70d5a82df51a91326d2738e0

        @@ -838,7 +838,7 @@ protected function getTerminalWidth()

        838 838

        return preg_replace(‘{^(\d+)x.*$}’, ‘$1′, $ansicon);

        839 839

        }

        840 840

        841

        - if (preg_match(“{rows.(\d+);.columns.(\d+);}i”, exec(‘stty -a | grep columns’), $match)) {

        841

        + if (preg_match(“{rows.(\d+);.columns.(\d+);}i”, $this->getSttyColumns(), $match)) {

        842 842

        return $match[1];

        843 843

        }

        844 844

        }

        … …

        @@ -854,7 +854,7 @@ protected function getTerminalHeight()

        854 854

        return preg_replace(‘{^\d+x\d+ \(\d+x(\d+)\)$}’, ‘$1′, trim($ansicon));

        855 855

        }

        856 856

        857

        - if (preg_match(“{rows.(\d+);.columns.(\d+);}i”, exec(‘stty -a | grep columns’), $match)) {

        857

        + if (preg_match(“{rows.(\d+);.columns.(\d+);}i”, $this->getSttyColumns(), $match)) {

        858 858

        return $match[2];

        859 859

        }

        860 860

        }

        … …

        @@ -915,6 +915,25 @@ protected function getDefaultHelperSet()

        915 915

        }

        916 916

        917 917

        /**

        918

        + * Runs and parses stty -a if it’s available, suppressing any error output

        919

        + *

        920

        + * @return string

        921

        + */

        922

        + private function getSttyColumns()

        923

        + {

        924

        + $descriptorspec = array(1 => array(‘pipe’, ‘w’), 2 => array(‘pipe’, ‘w’));

        925

        + $process = proc_open(‘stty -a | grep columns’, $descriptorspec, $pipes, null, null, array(‘suppress_errors’ => true));

        926

        + if (is_resource($process)) {

        927

        + $info = stream_get_contents($pipes[1]);

        928

        + fclose($pipes[1]);

        929

        + fclose($pipes[2]);

        930

        + proc_close($process);

        931

        +

        932

        + return $info;

        933

        + }

        934

        + }

  6. Hi Holban,
    I am new to Symfony2 and following this tutorial keenly.I have created the database and created the doctrine folder manually, but can not be able to generate the entities.this is what am getting.
    /*************************************************************
    [root@localhost ngigi]# php app/console doctrine:generate:entities EnsJobeetBundle
    Generating entities for bundle “EnsJobeetBundle”
    PHP Fatal error: Uncaught exception ‘ErrorException’ with message ‘Warning: exec() has been disabled for security reasons in /home/sfprojects/ngigi/vendor/symfony/src/Symfony/Component/Console/Application.php line 803′ in /home/sfprojects/ngigi/vendor/symfony/src/Symfony/Component/HttpKernel/Debug/ErrorHandler.php:67
    Stack trace:
    #0 [internal function]: Symfony\Component\HttpKernel\Debug\ErrorHandler->handle(2, ‘exec() has been…’, ‘/home/sfproject…’, 803, Array)
    #1 /home/sfprojects/ngigi/vendor/symfony/src/Symfony/Component/Console/Application.php(803): exec(‘stty -a | grep …’)
    #2 /home/sfprojects/ngigi/vendor/symfony/src/Symfony/Component/Console/Application.php(736): Symfony\Component\Console\Application->getTerminalWidth()
    #3 /home/sfprojects/ngigi/vendor/symfony/src/Symfony/Component/Console/Application.php(124): Symfony\Component\Console\Application->renderException(Object(Doctrine\ORM\Mapping\MappingException), Object(Symfony\Component\Console\Output\ConsoleOutput))
    #4 /home/sfprojects/ngigi/app/console(22): Symfo in /home/sfprojects/ngigi/vendor/symfony/src/Symfony/Component/HttpKernel/Debug/ErrorHandler.php on line 67

    Fatal error: Uncaught exception ‘ErrorException’ with message ‘Warning: exec() has been disabled for security reasons in /home/sfprojects/ngigi/vendor/symfony/src/Symfony/Component/Console/Application.php line 803′ in /home/sfprojects/ngigi/vendor/symfony/src/Symfony/Component/HttpKernel/Debug/ErrorHandler.php:67
    Stack trace:
    #0 [internal function]: Symfony\Component\HttpKernel\Debug\ErrorHandler->handle(2, ‘exec() has been…’, ‘/home/sfproject…’, 803, Array)
    #1 /home/sfprojects/ngigi/vendor/symfony/src/Symfony/Component/Console/Application.php(803): exec(‘stty -a | grep …’)
    #2 /home/sfprojects/ngigi/vendor/symfony/src/Symfony/Component/Console/Application.php(736): Symfony\Component\Console\Application->getTerminalWidth()
    #3 /home/sfprojects/ngigi/vendor/symfony/src/Symfony/Component/Console/Application.php(124): Symfony\Component\Console\Application->renderException(Object(Doctrine\ORM\Mapping\MappingException), Object(Symfony\Component\Console\Output\ConsoleOutput))
    #4 /home/sfprojects/ngigi/app/console(22): Symfo in /home/sfprojects/ngigi/vendor/symfony/src/Symfony/Component/HttpKernel/Debug/ErrorHandler.php on line 67
    /****************************************************************************************/
    Kindly help with this, I need to learn this framework.
    Thanks in advance.

  7. Thank you for the tutorial. I am learning a lot!

    I am not able to create the database. Any help would be most appreciated. Following is boring details.

    Bessie

    Details: I am working on Windows 7 64 bit, xampp 1.7.7 with PHP 5.3.8 and Symfony2 2.0.14.

    When I try to create the database with this command:

    php app/console doctrine:database:create

    I get this friendly error message:

    Could not create database for connection named jobeet
    SQLSTATE[28000] [1045] Access denied for user ‘root’@'localhost’ (using Password : YES)

    My parameters.ini file looks like this:

    [parameters]
    database_driver=”pdo_mysql”
    database_host=”localhost”
    database_port=”"
    database_name=”jobeet”
    database_user=”root”
    database_password=”password”
    mailer_transport=”smtp”
    mailer_host=”localhost”
    mailer_user=”"
    mailer_password=”"
    locale=”en”
    secret=”33114c6a61845b23d572d2826269d373″

    • Check to see what port your MySQL is running. Default is 3306.

      Update your parameters.ini file appropriately and see how that works.

      • I changed the parameters.ini to specifically say:

        database_port=”3306″

        When I start SQL Server (XAMPP control panel application)

        I get a message MySql started [Port 3306]

        From the command line, I can start the MySql and create a database. Do I need to include a password root @ localhost??

  8. hello
    I am new to Symfony2 and following this tutorial .I have created the database and created the doctrine folder , but can not be able to generate the entities with the command php app/console doctrine:generate:entities EnsJobeetBundle. I have an error.

    please can I have an idea of what can be the poblem ?

    thanks

  9. The code needs to be updated, as noted in the Symfony Documentation.

    In the deps file, just append version=origin/2.0 to the end, like so:
    [DoctrineFixturesBundle]
    git=http://github.com/symfony/DoctrineFixturesBundle.git
    target=/bundles/Symfony/Bundle/DoctrineFixturesBundle

    to this:
    [DoctrineFixturesBundle]
    git=http://github.com/doctrine/DoctrineFixturesBundle.git
    target=/bundles/Symfony/Bundle/DoctrineFixturesBundle
    version=origin/2.0

    • Hello ,

      I encounter a problem when I try to type
      Symfony]# php app/console doctrine:fixtures:load
      PHP Fatal error: Class ‘Symfony\Bundle\DoctrineFixturesBundle\DoctrineFixturesBundle’ not found in /var/www/html/Symfony/app/AppKernel.php on line 17

      Fatal error: Class ‘Symfony\Bundle\DoctrineFixturesBundle\DoctrineFixturesBundle’ not found in /var/www/html/Symfony/app/AppKernel.php on line

      AppKernel.php Source:

      registerNamespaces(array(
      ‘Symfony’ => array(__DIR__.’/../vendor/symfony/src’, __DIR__.’/../vendor/bundles’),
      ‘Sensio’ => __DIR__.’/../vendor/bundles’,
      ‘JMS’ => __DIR__.’/../vendor/bundles’,
      ‘Doctrine\\Common\\DataFixtures’ => __DIR__.’/../vendor/doctrine-fixtures/lib’,
      ‘Doctrine\\Common’ => __DIR__.’/../vendor/doctrine-common/lib’,

      All the things are there but it still getting that error.
      After some searching on the web I found that the Symfony\Bundle it’s replice by Doctrine\Bundle.

      • I as wrote in the first part of this tutorial, the Symfony version used is 2.0.11, that was the current version when I began writing it. You probably started with a newer version and that’s why some things are different.

        • Problem lies in deps file. Now the proper setting for DoctrineFixtures bundle is (last line is NEW):

          [doctrine-fixtures]
          git=http://github.com/doctrine/data-fixtures.git

          [DoctrineFixturesBundle]
          git=http://github.com/doctrine/DoctrineFixturesBundle.git
          target=/bundles/Symfony/Bundle/DoctrineFixturesBundle
          version=origin/2.0

          • I add the version 2.0 , did the php restart command and encounter the same problem.

  10. Hello

    When I ran $ php app/console doctrine:generate:entities SfTutsJobeetBundle

    I got this error

    [ErrorException]
    Notice: Undefined index: SfTuts\JobeetBundle\Entity\SfTuts\JobeetBundle\Ent
    ity\Category in /var/www/Symfony/vendor/doctrine/lib/Doctrine/ORM/Mapping/D
    river/AbstractFileDriver.php line 121

    • Check again if you did everything like I wrote. You must have done something different and that’s why you get the error…

  11. Hi thanks for the wonderful tutorial i have followed step by step the tutorial at the end when i am trying to update a record or edit the current record it shows me the following exception
    The Symfony\Component\Locale\Stub\StubIntlDateFormatter::setLenient() is not implemented. Please install the ‘intl’ extension for full localization capabilities.
    500 Internal Server Error – MethodNotImplementedException

  12. For any one who gets the error:
    [InvalidArgumentException]
    Could not find any fixtures to load in:

    when running:
    php app/console doctrine:fixtures:load

    Make sure you put in opening <?php tag at
    the top of the LoadCategoryData.php and
    LoadJobData.php
    ie

    <?php
    // src/Ens/JobeetBundle/DataFixtures/ORM/LoadJobData.php
    namespace Ens\JobeetBundle\DataFixtures\ORM;

    Took me long enough to work out, hope it helps.

  13. I want use Annotation instead YAML
    Do you know how can i create and entity via console with field with foreign key?

  14. When trying to clear the cache using:

    php app/console cache:clear –env=prod

    I get:

    [Symfony\Component\Config\Exception\FileLoaderLoadException]
    Cannot import resource “@EnsJobeetBundle/Resources/config/routing/job.yml”
    from “/var/www/Symfony/src/Ens/JobeetBundle/Resources/config/routing.yml”.
    Make sure the “EnsJobeetBundle” bundle is correctly registered and loaded i
    n the application kernel class.

    • In Day 1 we created the bundle using this symfony command:
      php app/console generate:bundle –namespace=Ens/JobeetBundle –format=yml

      That should register the bundle in app/AppKernel.php file:

      $bundles = array(
          // ...
          new Ens\JobeetBundle\EnsJobeetBundle(),
          // ...
      );
      

      Please check this.

      • Thanks for the quick reply, this was already in the app/AppKernel.php file. I get the following when I go to http://jobeet.local/app_dev.php/job/:
        Cannot import resource “/var/www/Symfony/src/Ens/JobeetBundle/Resources/config/doctrine/Job.orm.yml” from “/var/www/Symfony/src/Ens/JobeetBundle/Resources/config/routing.yml”.
        [2/2] FileLoaderLoadException: Cannot import resource “/var/www/Symfony/src/Ens/JobeetBundle/Resources/config/doctrine/Job.orm.yml” from “/var/www/Symfony/src/Ens/JobeetBundle/Resources/config/routing.yml”.
        [1/2] InvalidArgumentException: Yaml routing loader does not support given key: “table”. Expected one of the (type, resource, prefix, pattern, options, defaults, requirements).

        • Sorry no it states Cannot import resource “@EnsJobeetBundle/Resources/config/routing/job.yml” from “/var/www/Symfony/src/Ens/JobeetBundle/Resources/config/routing.yml”. Make sure the “EnsJobeetBundle” bundle is correctly registered and loaded in the application kernel class.
          500 Internal Server Error – FileLoaderLoadException
          1 linked Exception: InvalidArgumentException »

          • Please ignore/delete I was generating the controller as one line instead of using the wizard

  15. When I execute:

    php app/console doctrine:generate:entities EnsJobeetBundle

    I receive the error:

    [Doctrine\ORM\Mapping\MappingException]
    Class Ens\JobeetBundle\Entity\Affiliate is not a valid entity or mapped super class.

    Any suggestions to troubleshoot this?

    • That is because you copy-pasted .orm.yml files above. They contain some invalid characters which look like spaces.
      Run this command to replace them with actual spaces:
      LANG=C sed -i ‘s/[\x80-\xFF]/ /g’ src/Ens/JobeetBundle/Resources/config/doctrine/*

      • hi, i’m getting the same error so i used your command but i’m getting error too.
        ‘LANG’ is not recognized as an internal or external command,
        operable program or batch file.
        in cmd Windows
        can you help?

  16. As of today, it work well.maybe you could correct little miss typo.

    for fixtures :
    _ (indeed) add a top line with ” src/Ens/JobeetBundle

    good job anyway. ty

  17. things went well until when creating database tables.

    $ php app/console doctrine:schema:update –force

    [Doctrine\ORM\Mapping\MappingException]
    No mapping file found named ‘/home/administrator/workspace/tut/src/Tut/Jobe
    etBundle/Resources/config/doctrine/category.orm.yml’ for class ‘Tut\JobeetB
    undle\Entity\category’.

  18. Hi,

    I followed everything from the tutorial. Metadata files is in \src\Ens\JobeetBundle\Resources\config\doctrine and the command that I ran is php app\console doctrine:generate:entities EnsJobeetBundle. And getting the following error:

    Generating entities for bundle “EnsJobeetBundle”
    ‘stty’ is not recognized as an internal or external command,
    operable program or batch file.

    [RuntimeException]
    Bundle “EnsJobeetBundle” does not contain any mapped entities.

    doctrine:generate:entities [--path="..."] [--no-backup] name

  19. the deps file is no longer used in Symfony 2.1. I believe you have to download composer.phar, run it with php to read the composer.json file located in the root of your symfony project. google Symfony2+composer+deps for more info.

  20. i have error
    Entity “Acme\JobeetBundle\Entity\Category” passed to the choice field must have a “__toString()” method defined (or you can also override the “property” option).

    plz can help me

  21. Does anyone know how to configure composer.json file in symfony2.1 to manage the deps? I am having trouble finding any clear documentation on it.

    Thanks

    [doctrine-fixtures]
    git=http://github.com/doctrine/data-fixtures.git

    [DoctrineFixturesBundle]
    git=http://github.com/doctrine/DoctrineFixturesBundle.git
    target=/bundles/Symfony/Bundle/DoctrineFixturesBundle
    version=origin/2.0

    • in composer.json add the following to the require section of the array

      {
      “require”: {
      “doctrine/doctrine-fixtures-bundle”: “dev-master”
      }
      }

      then update the vendor library:

      $ php composer.phar update

      • Step 3 can then be skipped if using composer.

        Step 4 changes to:

        // …
        public function registerBundles()
        {
        $bundles = array(
        // …
        new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
        // …
        );
        // …
        }

        • I’m completely new to symfony and composer.
          I’ve downloaded Symfony 2.1.7 and after trying to run update it fails to install doctrine fixtures bundle. It requires data-fixtures but when I add this, the message says that git was not found for data-fixtures. My composer.json in require section:
          “doctrine/data-fixtures”: “dev-master”,
          “doctrine/doctrine-fixtures-bundle”: “dev-master”,

  22. [ERROR]
    ” PDO Exception
    can not find driver”
    Therefore database could not be created by using above mentioned command,
    what is the correct procedure to create and update database?

  23. Hey,

    as we pass the 10.10.2012, you have to replace the date from the
    // src/Ens/JobeetBundle/DataFixtures/ORM/LoadJobData.php file


    $job_sensio_labs->setExpiresAt(new \DateTime(’2012-10-10′));

    $job_extreme_sensio->setExpiresAt(new \DateTime(’2012-10-10′));

    so the jobs won’t be expired.(It may work either way for now)

    Cheerz!

  24. Hi there..
    I am new in symfony2. Everything is fine in that tutorial. But I have problem with data upload. Please tell me where I will get deps file.

  25. Cerated
    $this->created_at = new \DateTime();
    $d=$this->created_at->date;

    Getting error
    Notice: Undefined property: DateTime::$date in D:\xampp\htdocs\mysf\src\Acme\adBundle\Controller\adController.php line 343

  26. I followed with care the tutorial, but then when I want to generate the entities, it said:

    Warning: Illegal offset type in isset or empty in C:\wamp\www\jobeet\vendor\doctrine\dbal\lib\Doctrine\DBAL\Types\T
    ype.php line 182

  27. Hello guys !
    I am a beginner for Symfony 2
    How can I install this Symfony 2.0.11 version with vendor file ?
    Because I was trying to build Jobeet with 2.2.1 version but from now , getting some error .
    Any help appreciated , thank you

  28. Thank you for this excellent tutorial.

    A couple things I needed to get this working with symfony 2.2

    Change all the orm files to have the id in the fields section:
    change the bundle for fixtures to use composer update.

    Hope this helps some people.

  29. Warning: require_once(D:\xampp\htdocs\Jobeet\app/../vendor/symfony/src/Symfony/Component/Locale/Resources/stubs/functions.php): failed to open stream: No such file or directory in D:\xampp\htdocs\Jobeet\app\autoload.php on line 29

    Fatal error: require_once(): Failed opening required ‘D:\xampp\htdocs\Jobeet\app/../vendor/symfony/src/Symfony/Component/Locale/Resources/stubs/functions.php’ (include_path=’.;D:\xampp\php\PEAR’) in D:\xampp\htdocs\Jobeet\app\autoload.php on line 29

    I can not fix this error, help me with !!!

  30. Would the author or someone experienced update the section on the Initial Data for the latest version of Symfony2, seeing that there are no “deps” anymore.

    I followed this tutorial with the one on http://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html

    However, when I run
    php app/console doctrine:fixtures:load

    I get the following error:

    Could not find any fixtures to load in:
    – /Users/user/Sites/jobeet/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/DataFixtures/ORM
    – /Users/user/Sites/jobeet/vendor/symfony/symfony/src/Symfony/Bundle/SecurityBundle/DataFixtures/ORM
    – /Users/user/Sites/jobeet/vendor/symfony/symfony/src/Symfony/Bundle/TwigBundle/DataFixtures/ORM

    Thank you!

  31. When I execute:

    php app/console doctrine:generate:entities EnsJobeetBundle

    I receive the error:

    [Symfony\Component\Yaml\Exception\ParseException]
    Unable to parse in “C:\\wamp\\www\\project\\src\\Ens\\JobeetBundle\\Resources\\config\\doctrine\/Affiliate.orm.yml”
    at line 1 (near “я╗┐#src/Ens/JobeetBundle/Resources/config/doctrine/Affiliate.orm.yml”).
    doctrine:generate:entities [--path="..."] [--no-backup] name

    Any suggestions to troubleshoot this?

  32. for creating database tables when i am using this command,
    php app/console doctrine:schema:update –force

    I am getting error :

    [UnexpectedValueException]
    The stream or file “/var/www/Symfony/app/logs/dev.log” could not be opened:
    failed to open stream: Permission denied

    Please tell the solution.

    Regards
    Sudeep Jain

  33. When i Run this on the console:
    php app/console doctrine:schema:update –force

    I get this error:
    [Doctrine\DBAL\DBALException]
    Unknown column type “json” requested. Any Doctrine type that you use has to
    be registered with \Doctrine\DBAL\Types\Type::addType(). You can get a lis
    t of all the known types with \Doctrine\DBAL\Types\Type::getTypeMap(). If t
    his error occurs during database introspection then you might have forgot t
    o register all database types for a Doctrine Type. Use AbstractPlatform#reg
    isterDoctrineTypeMapping() or have your custom types implement Type#getMapp
    edDatabaseTypes(). If the type name is empty you might have a problem with
    the cache or forgot some mapping information.

    How can i fix this?

Leave a Reply

Your email address will not be published. Required fields are marked *


9 × six =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>