Symfony2 Create Simple CRUD Application


Sekarang kita akan bikin CRUD sederhana yang mengolah hello worl dari database, mari kita mulai bikin Hello World dari database dengan symfony.

  1. generate entity namanya Shouter (terserah sih mau dinamain apa)

    ./app/console doctrine:generate:entity

  2. habis perintah diatas akan ada prompt lengakapi saja seperti berikut

    Welcome to the Doctrine2 entity generator This command helps you generate Doctrine2 entities.First, you need to give the entity name you want to generate. You must use the shortcut notation like AcmeBlogBundle:Post. The Entity shortcut name: AcmeTestBundle:ShouterDetermine the format to use for the mapping information.

    Configuration format (yml, xml, php, or annotation) [annotation]: annotation

    Instead of starting with a blank entity, you can add some fields now.
    Note that the primary key will be added automatically (named id).

    Available types: array, simple_array, json_array, object,
    boolean, integer, smallint, bigint, string, text, datetime, datetimetz,
    date, time, decimal, float, blob, guid.

    New field name (press <return> to stop adding fields): messages
    Field type [string]:
    Field length [255]:

    New field name (press <return> to stop adding fields): description
    Field type [string]: text

    New field name (press <return> to stop adding fields):

    Do you want to generate an empty repository class [no]? yes
    Summary before generation

    You are going to generate a “AcmeTestBundle:Shouter” Doctrine2 entity
    using the “annotation” format.

    Do you confirm generation [yes]?
    Entity generation

    Generating the entity code: OK
    You can now start using the generated code!

  3. kamu akan memiliki entity seperti Shouter.php ini/var/www/html/learning/learning1/src/Acme/TestBundle/Entity/Shouter.phpYang isinya kurang lebih begini (kalau ada beda tipe data misal aku text kama varchar gpp kok) :

    <?phpnamespace Acme\TestBundle\Entity;

    use Doctrine\ORM\Mapping as ORM;

    /**
    * Shouter
    *
    * @ORM\Table()
    * @ORM\Entity(repositoryClass=”Acme\TestBundle\Entity\ShouterRepository”)
    */
    class Shouter
    {
    /**
    * @var integer
    *
    * @ORM\Column(name=”id”, type=”integer”)
    * @ORM\Id
    * @ORM\GeneratedValue(strategy=”AUTO”)
    */
    private $id;

    /**
    * @var string
    *
    * @ORM\Column(name=”messages”, type=”text”)
    */
    private $messages;

    /**
    * @var string
    *
    * @ORM\Column(name=”description”, type=”text”, nullable=true)
    */
    private $description;

    /**
    * @var \DateTime
    *
    * @ORM\Column(name=”createdAt”, type=”datetime”)
    */
    private $createdAt;

    /**
    * @var \DateTime
    *
    * @ORM\Column(name=”updatedAt”, type=”datetime”)
    */
    private $updatedAt;
    /**
    * Get id
    *
    * @return integer
    */
    public function getId()
    {
    return $this->id;
    }

    /**
    * Set messages
    *
    * @param string $messages
    * @return Shouter
    */
    public function setMessages($messages)
    {
    $this->messages = $messages;

    return $this;
    }

    /**
    * Get messages
    *
    * @return string
    */
    public function getMessages()
    {
    return $this->messages;
    }

    /**
    * Set createdAt
    *
    * @param \DateTime $createdAt
    * @return Shouter
    */
    public function setCreatedAt($createdAt)
    {
    $this->createdAt = $createdAt;

    return $this;
    }

    /**
    * Get createdAt
    *
    * @return \DateTime
    */
    public function getCreatedAt()
    {
    return $this->createdAt;
    }

    /**
    * Set updatedAt
    *
    * @param \DateTime $updatedAt
    * @return Shouter
    */
    public function setUpdatedAt($updatedAt)
    {
    $this->updatedAt = $updatedAt;

    return $this;
    }

    /**
    * Get updatedAt
    *
    * @return \DateTime
    */
    public function getUpdatedAt()
    {
    return $this->updatedAt;
    }
    }

  4. Buat HelloDbController.php (link)di /var/www/html/learning/learning1/src/Acme/TestBundle/Controller/HelloDbController.php

    <?php
    namespace Acme\TestBundle\Controller;
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\HttpFoundation\Request;
    use Acme\TestBundle\Entity\Shouter;
    /**
    * @Route(“/acme”)
    */
    class HelloDbController extends Controller {

    /**
    * @Route(“/insert_db/{msg}”, name=”hai_insert_db”)
    */
    public function insertdbAction($msg = ‘hallo world ‘)
    {

    $shouter = new Shouter();
    $shouter->setMessages($msg);
    $shouter->setDescription(“lorema ipsuma”);
    $shouter->setCreatedAt(new \DateTime(“now”));
    $shouter->setUpdatedAt(new \DateTime(“now”));
    $em = $this->getDoctrine()->getManager();
    $em->persist($shouter);
    $em->flush();

    return new Response(‘Created shouter id ‘.$shouter->getId());
    }

    /**
    * @Route(“/hai_db”, name=”hai_db”)
    */
    public function greatingAction()
    {
    $repository = $this->getDoctrine()->getRepository(‘AcmeTestBundle:Shouter’);
    $shouters = $repository->findAll();

    $html = $this->container
    ->get(‘templating’)
    ->render(
    ‘AcmeTestBundle:Hoi:list.html.twig’,
    array(‘shouters’ => $shouters)
    );
    return new Response($html);
    }

    /**
    *
    * @Route(“/hai_form_db”, name=”hai_form_add_db1″)
    */
    public function formAdd1Action(Request $request) {
    $shouter = new Shouter();

    $form = $this->createFormBuilder($shouter)
    ->add(‘messages’, ‘text’)
    ->add(‘description’, ‘text’)
    ->add(‘createdAt’, ‘datetime’)
    ->add(‘updatedat’, ‘datetime’)
    ->add(‘save’, ‘submit’, array(‘label’ => ‘Create Hello World’))
    ->getForm();

    //handle save
    $form->handleRequest($request);
    if ($form->isValid()) {
    $data = $form->getData();

    $em = $this->getDoctrine()->getManager();
    $em->persist($data);
    $em->flush();
    //return $this->redirect(‘task_success’);
    }

    return $this->render(‘AcmeTestBundle:Hoi:add.html.twig’, array(
    ‘form’ => $form->createView(),
    ));
    }
    }

    lalu view di /var/www/html/learning/learning1/src/Acme/TestBundle/Resources/views/Hoi/add.html.twig

    {% extends ‘base.html.twig’ %}
    {% block body %}
    {{ form_start(form) }}
    {{ form_widget(form) }}
    {{ form_end(form) }}
    {% endblock %}

    /var/www/html/learning/learning1/src/Acme/TestBundle/Resources/views/Hoi/list.html.twig

    {% extends ‘base.html.twig’ %}
    {% block body %}
    <table>
    {% for shouter in shouters %}
    <tr>
    <td>
    Messages : {{shouter.messages}}
    Description : {{shouter.description}}
    </td>
    </tr>
    {% endfor %}
    <table>
    {% endblock %}

  5. kamu punya url berikut sekaranghttp://127.0.0.1:8000/acme/insert_db/HelloWorldBaru

    http://127.0.0.1:8000/acme/hai_db

    http://127.0.0.1:8000/acme/hai_form_db

One thought on “Symfony2 Create Simple CRUD Application

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s