Pages

Monday, June 24, 2013

Creating forms in Symfony2 Part II

We have created blog user level form, Now we have to create User. user has 'name', 'display name','e mail', 'image id' and 'blog user level id'. According to our ERD one user has one blog user level, one user level has many Users. To create the user form let's begin with creating entity by running
$ php app/console generate:doctrine:entity
and create 
'name', 'display name','e mail', 'image id' files.  Now we have to create 'blog user level id' field. I still couldn't find a way to create relations in command prompt. But i found a way to do it by editing entity configuration file. open the 'BlogUser.orm.xml' file and add fallowing

    <many-to-one field="bloguserlevel" target-entity="Acme\UserBundle\Entity\BlogUserLevel">
        <join-column name="blog_user_level_id" referenced-column-name="id"/>
    </many-to-one> 


final file looks like this

<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="Acme\UserBundle\Entity\BlogUser">
    <id name="id" type="integer" column="id">
      <generator strategy="AUTO"/>
    </id>
    <field name="name" type="string" column="name" length="255"/>
    <field name="displayName" type="string" column="display_name" length="255"/>
    <field name="email" type="string" column="email" length="255"/>
    <field name="image" type="integer" column="image"/>
    <many-to-one field="bloguserlevel" target-entity="Acme\UserBundle\Entity\BlogUserLevel">
        <join-column name="blog_user_level_id" referenced-column-name="id"/>
    </many-to-one>      
  </entity>
</doctrine-mapping>


then create entity by executing
$ php app/console generate:doctrine:entities AcmeUserBundle




update the database
$ php app/console doctrine:schema:update --force

Create CRUD operations
$ php app/console generate:doctrine:crud

We have a drop down(blog_user_level_id) in this form. To load the user levels open the
Acme/UserBundle/Form/BlogUserType.php for and update buildForm() method. the method will be looks like as fallows

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('displayName')
            ->add('email')
            ->add('image')
            ->add('bloguserlevel','entity',array(
                    'class' => 'AcmeUserBundle:BlogUserLevel',
                    'property' => 'name',
            ))
        ;
    }


thats it. goto http://localhost:8000/bloguser/ in check the form is working..







No comments:

Post a Comment