Tuesday, May 28, 2013

Template : Twig - Basic

Variables
 {{foo.bar}}
 {{foo['bar']}}


Global Variables
  _self : references the current template;
  _context : references the current context;
 _charset : references the current charset

Setting Variables
 {% set foo = 'foo' %}
 {% set foo = [1,2] %}
 {% set foo = { 'foo' : 'bar' } %}

Filters
  {{ name|striptags|title }}

  {{ list|join(', ') }}
  {% filter upper %}  
         This text becomes uppercase  
  {% endfilter %}

   built-in filter :
   abs / batch / capitalize / convert_encoding / date / date_modify / default /
   escape / first / format / join / json_encode / keys / last / length / lower / nl2br /
   number_format / merge / upper / raw / replace / reverse / slice / sort / split /
   striptags / title / trim / url_encode  


Functions
 {% for i in range(0, 3) %}
        {{ i }},  
 {% endfor %}

  built-in function :
   attribute / block / constant / cycle / date / dump /
   include / parent / random / range / template_from_string

{% for i in range(low=1, high=10, step=2) %}
    {{ i }},
{% endfor %}
 
 {{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}
 
 {{ "now"|date('d/m/Y H:i', timezone="Europe/Paris") }}






Control Structure

<ul>
    {% for user in users %}
        <li>{{ user.username|e }}</li>
    {% endfor %}
</ul>
 
{% for i in 0..10 %}
    * {{ i }}
{% endfor %}
 
{% for letter in 'a'..'z' %}
    * {{ letter }}
{% endfor %} 
 
{% for letter in 'a'|upper..'z'|upper %}
    * {{ letter }}
{% endfor %} 
 
 
   for tags :
 



{% if users|length > 0 %}
    <ul>
        {% for user in users %}
            <li>{{ user.username|e }}</li>
        {% endfor %}
    </ul>
{% endif %}


{% if online == false %}
    <p>Our website is in maintenance mode. Please, come back later.</p>
{% endif %} 
 
 
{% if users %}
    <ul>
        {% for user in users %}
            <li>{{ user.username|e }}</li>
        {% endfor %}
    </ul>
{% endif %}


 
 
 
 
Including other Templates
 
 {% include 'sidebar.html' %} 
 
 {% for box in boxes %}
    {% include "render_box.html" %}
{% endfor %}


 

{% include "sections/articles/sidebar.html" %}



Template Inheritance (block)

base.html (4 block)

<!DOCTYPE html>
<html>
    <head>
        {% block head %}
            <link rel="stylesheet" href="style.css" />
            <title>{% block title %}{% endblock %} - My Webpage</title>
        {% endblock %}
    </head>
    <body>
        <div id="content">{% block content %}{% endblock %}</div>
        <div id="footer">
            {% block footer %}
                &copy; Copyright 2011 by <a href="http://domain.invalid/">you</a>.
            {% endblock %}
        </div>
    </body>
</html>
 
 Child tepmalte :
 
{% extends "base.html" %}

{% block title %}Index{% endblock %}
{% block head %}
    {{ parent() }}
    <style type="text/css">
        .important { color: #336699; }
    </style>
{% endblock %}
{% block content %}
    <h1>Index</h1>
    <p class="important">
        Welcome to my awesome homepage.
    </p>
{% endblock %}
 
 
extends - using parent() function
 
{% block sidebar %}
    <h3>Table Of Contents</h3>
    ...
    {{ parent() }}
{% endblock %} 
 
 


HTML Escaping (using piping)

{{ user.username|escape }} 
{{ user.username|e }}

{{ user.username|e('js') }}
{{ user.username|e('css') }}
{{ user.username|e('url') }}
{{ user.username|e('html_attr') }}

{% autoescape %}
    Everything will be automatically escaped in this block (using the HTML strategy)
{% endautoescape %}
 
{{ '{{' }}

{% macro input(name, value, type, size) %}
    <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
{% endmacro %}

{% import "forms.html" as forms %}
<p>{{ forms.input('username') }}</p>


{% from 'forms.html' import input as input_field %}

<dl>
    <dt>Username</dt>
    <dd>{{ input_field('username') }}</dd>
    <dt>Password</dt>
    <dd>{{ input_field('password', '', 'password') }}</dd>
</dl>


{% macro input(name, value = "", type = "text", size = 20) %}
    <input type="{{ type }}" name="{{ name }}" value="{{ value|e }}" size="{{ size }}" />
{% endmacro %}



Expressions
 operator precedence :
  b-and, b-xor, b-or, or, and, ==, !=, <, >, >=, <=, in, .., +, -, ~, *, /, //, %, is, **, |, [], and .:


{% set greeting = 'Hello' %}
{% set name = 'Fabien' %}

{{ greeting ~ name|lower }}   {# Hello fabien #}

{# use parenthesis to change precedence #}
{{ (greeting ~ name)|lower }} {# hello fabien #}


{# keys as string #}
{ 'foo': 'foo', 'bar': 'bar' }

{# keys as names (equivalent to the previous hash) -- as of Twig 1.5 #}
{ foo: 'foo', bar: 'bar' }

{# keys as integer #}
{ 2: 'foo', 4: 'bar' }

{# keys as expressions (the expression must be enclosed into parentheses) -- as of Twig 1.5 #}
{ (1 + 1): 'foo', (a ~ 'b'): 'bar' }


{% set foo = [1, {"foo": "bar"}] %}

Math

 + : {{ 1 + 1 }} is 2. 
 - : {{ 3 - 2 }} is 1. 
 / : The returned value will be a floating point number. {{ 1 / 2 }} is {{ 0.5 }}. 
 % : {{ 11 % 7 }} is 4. 
 //: Divides and returns the truncated integer result. {{ 20 // 7 }} is 2. 
 * : {{ 2 * 2 }} would return 4. 
 **: power of the right operand. {{ 2 ** 3 }} would return 8.

Logic

 and , or , not , (expr)


Comparisons

==, !=, <, >, >=, and <=



Containment Operator

{# returns true #}
{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}
 
{% if 1 not in [1, 2, 3] %}

{# is equivalent to #}
{% if not (1 in [1, 2, 3]) %}

Test Operator

{# find out if a variable is odd #}
{{ name is odd }}
{% if loop.index is divisibleby(3) %} 
{# is equivalent to #}
{% if not (loop.index is divisibleby(3)) %}


Other Operators
  ..    :  range 
  |    : Applies a filter. 
  ~      : Converts into strings and concat. 
  ., [] : Gets an attribute of an object. 
  ?:    : The ternary operator


{{ foo ? 'yes' : 'no' }}

{# as of Twig 1.12.0 #}
{{ foo ?: 'no' }} == {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} == {{ foo ? 'yes' : '' }}

String Interpolation

{{ "foo #{bar} baz" }}
{{ "foo #{1 + 2} baz" }}

Whitespace Control


{% spaceless %}
    <div>
        <strong>foo</strong>
    </div>
{% endspaceless %}

{# output will be <div><strong>foo</strong></div> #} 
 
{% set value = 'no spaces' %}
{#- No leading/trailing whitespace -#}
{%- if true -%}
    {{- value -}}
{%- endif -%}

{# output 'no spaces' #}
 
{% set value = 'no spaces' %}
<li>    {{- value }}    </li>

{# outputs '<li>no spaces    </li>' #} 
 
 
 









Global Tempalate :

  • app.security - The security context.
  • app.user - The current user object.
  • app.request - The request object.
  • app.session - The session object.
  • app.environment - The current environment (dev, prod, etc).
  • app.debug - True if in debug mode. False otherwise.

Friday, May 24, 2013

Data Fixtures : Untuk insert data dalam table dengan segera.

Tambah vendor bundel

edit composer.json  // nak download yang latest

tambah :

"require": {
    // ...
    "doctrine/doctrine-fixtures-bundle": "dev-master",
    "doctrine/data-fixtures" : "dev-master"
}
 
run : 
 
php composer.phar update 

register bundle dekat

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



Create a fixture file di src/ASF/PembedaBundle/DataFixtures/ORM/SurahFixtures.php

// src/ASF/PembedaBundle/DataFixtures/ORM/SurahFixtures.php

namespace ASF\PembedaBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use ASF\PembedaBundle\Entity\Surah;

//class SurahFixtures implements FixtureInterface
class SurahFixtures extends AbstractFixture implements OrderedFixtureInterface
{
    public function load(ObjectManager $manager)
    {
        $surah1 = new Surah();

       $surah1->setId('001');
       $surah1->setIndex(1);
       $surah1->setBilayat(7);
       $surah1->setMulaayat(0);
       $surah1->setNama("الفاتحة");
       $surah1->setTnama('Al-Faatihah');
       $surah1->setEnama('The Opening');
       $surah1->setMnama('Pembukaaan');
       $surah1->setCategory('Mekah');
       $surah1->setOrder(5);
       $surah1->setRukus(1);
       $surah1->setPengenalan('');
       $surah1->setImage('alquran.jpg');
       $surah1->setTags('jalan, iman, islam');
       $surah1->setCreated(new \DateTime());
       $surah1->setUpdated($surah1->getCreated());
       $manager->persist($surah1);

       $surah2->setId('002');
       $surah2->setIndex(2);
       $surah2->setBilayat(286);
       $surah2->setMulaayat(7);
       $surah2->setNama("البقرة");
       $surah2->setTnama('Al-Baqara');
       $surah2->setEnama('The Cow');
       $surah2->setMnama('Lembu Betina');
       $surah2->setCategory('Madinah');
       $surah2->setOrder(87);
       $surah2->setRukus(40);
       $surah2->setPengenalan('');
       $surah2->setImage('alquran.jpg');
       $surah2->setTags('jalan, iman, islam');
       $surah2->setCreated(new \DateTime());
       $surah2->setUpdated($surah2->getCreated());
       $manager->persist($surah2);
        $manager->flush();

        $this->addReference('surah-1', $surah1);
        $this->addReference('surah-2', $surah2);
}


loading the fixtures to database
php app/console doctrine:fixtures:load

Symfony CLI


 
 
- To create getters & setters from entity 
php app/console doctrine:generate:entities ASF
 
- To create database from app/config/parameters.ini 
php app/console doctrine:database:create 
 
- To create table from entity file
php app/console doctrine:schema:create
 
-To copy asset to production asset
php app/console assets:install web
 
 - To clear cache
php app/console cache:clear --env=prod 
php app/console cache:clear --env=dev 
php app/console cache:clear --env=test
 
 - To update table
php app/console doctrine:schema:update --force
 
 
 - To update fixture
php app/console doctrine:fixtures:load
 

Creating Entity / Table baru


Create fail spt dibawah :

<pre>
// src/Blogger/BlogBundle/Entity/Surah.php
namespace ASF\PembedaBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
 * @ORM\Entity
 * @ORM\Table(name="j3_pembeda_surah")
 */
class Surah
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
    /**
     * @ORM\Column(type="string")
     */
    protected $nama_surah;
    /**
     * @ORM\Column(type="string")
     */
    protected $nama_surah2;
    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $category;
    /**
     * @ORM\Column(type="text")
     */
    protected $pengenalan;

    /**
     * @ORM\Column(type="string", length=20)
     */
    protected $image;

    /**
     * @ORM\Column(type="text")
     */
    protected $tags;

    protected $comments;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $created;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $updated;
   
}
</pre>

run command utk generate getters & setters :

php app/console doctrine:generate:entities ASF

Create databases , klu belum ada lagi
 cek fail nih dulu nama database dia ::
      php app/console doctrine:generate:entities Blogger

php app/console doctrine:database:create


Create table , dari entity fail :

php app/console doctrine:schema:create


Thursday, May 23, 2013

Querying for Objects ( Cara2 nak dapat data objek - 3 cara)

1. Querying for Objects ( Cara2 nak dapat data objek - 3 cara)

    a. Basic (Hok symfony buat doh )
         cth : $repository->find($id);
                 $repository->findOneByName('Foo');

    b. Querying for Objects with DQL ( hampir sama dgn SQL)
        cth :   $em = $this->getDoctrine()->getManager();  
                 $query = $em->createQuery( 'SELECT p FROM AcmeStoreBundle:Product p WHERE p.price > :price ORDER BY p.price ASC' )->setParameter('price', '19.99');
                 $products = $query->getResult();  // return array of result
                 $product = $query->getSingleResult();  // return 1 object

    b. Using Doctrine's Query Builder
         see doctrine manual 
         cth :  $repository = $this->getDoctrine()
                                ->getRepository('AcmeStoreBundle:Product');
                  $query = $repository->createQueryBuilder('p')
                                       ->where('p.price > :price')
                                       ->setParameter('price', '19.99')
                                      ->orderBy('p.price', 'ASC')  
                                      ->getQuery();
                  $products = $query->getResult();
 

macam2 contoh Retrieving Data with Doctrine (Querying for Objects)

Fetching Objects from the Database

 


// src/ASF/PembedaBundle/Controller/QuranController.php

class QuranController extends Controller

{
    public function mainAction($surah=null)
    {
                  
        $em = $this->getDoctrine()->getEntityManager();
        $qayat = $em->getRepository('ASFPembedaBundle:Quran')->findBy(array('id' => '001001'));
         /* note : macam2 contoh Retrieving Data with Doctrine (Querying for Objects)
         *     ->find($id); // query by the primary key (usually "id")
         *     ->findOneByName('Foo'); // dynamic method names to find based on a column value
         *     ->findOneById($id);  // dynamic method names to find based on a column value
         *     ->findAll(); // find *all* products
         *     ->findByPrice(19.99); // find a group of products based on an arbitrary column value
         *     ->findOneBy(array('name' => 'foo', 'price' => 19.99)); // query for one product matching be name and price
         *     ->findBy(array('name' => 'foo'),array('price' => 'ASC')); // query for all products matching the name, ordered by price
         *     $em->getRepository('ASFPembedaBundle:Quran')->find($id);
         */

        return $this->render('ASFPembedaBundle:Quran:qmain.html.twig', array(
            'qayat'      => $qayat,
            'comments'  => 'ssssss'
        ));

    }
}