<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Magento Design and Development &#187; development</title>
	<atom:link href="http://inchoo.net/tag/development/feed/" rel="self" type="application/rss+xml" />
	<link>http://inchoo.net</link>
	<description>Magento Design and Magento Development Professionals - Inchoo</description>
	<lastBuildDate>Wed, 23 May 2012 06:32:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Inchoo Demostore extension</title>
		<link>http://inchoo.net/ecommerce/magento/inchoo-demostore-extension/</link>
		<comments>http://inchoo.net/ecommerce/magento/inchoo-demostore-extension/#comments</comments>
		<pubDate>Tue, 08 May 2012 07:22:44 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[demo]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=13715</guid>
		<description><![CDATA[In my last project, during development of API extension for Mageboard application, when started to develope Apple Push Notifications Services integration, one problem came out that took me too much &#8230;]]></description>
			<content:encoded><![CDATA[<p>In my last project, during development of API extension for <a title="Mageboard - your mobile dashboard" href="http://mageboard.inchoo.net/" target="_blank">Mageboard application</a>, when started to develope Apple Push Notifications Services integration, one problem came out that took me too much time each day to solve: Push notifications are supposed to be active only if some new order and/or customer is made on site.</p>
<p>So if there are no constant new orders and/or new customers, I can not test my APNS integration.<span id="more-13715"></span></p>
<p>At first I started to enter orders and customers manually on dev server, but it took much time, so I decided to do something to solve it.<br />
After some searching, i didn&#8217;t find the suitable extension to solve automatic creation of customers and orders as I need, so that&#8217;s the reason a new extension was made.</p>
<p>So let me list the features that I needed in new extension:</p>
<ul>
<li>Automatic creation of random customers with fully random names and addresses, e-mail adresses and other random personal data.</li>
<li>Automatic creation of orders with random order items in basket.</li>
<li>Automatic shipment</li>
<li>Automatic invoice</li>
<li>Make all of this features random</li>
<li>Work with cron job, so generation is happening periodically (every minute, or depends how my Magento cron is set).</li>
</ul>
<p>One interesting thing that I found when searching inside Magento core source code is a class Mage_Adminhtml_Model_Sales_Order_Random.</p>
<p>When I looked in code, it was obvious for me that this class was made for some purpose, but when trying to find where this class is used, I didn&#8217;t find nothing. Anyway, I decided to try this class to see if it works well, but this class has some serious issues in code that have to be rewritten in order to make it work.</p>
<p>So, here is my new order creation source code:</p>
<pre class="brush: php; title: ; notranslate">

&lt;!--?php &lt;br ?--&gt;
/*
 * @category Inchoo
 * @package Inchoo_Demostore
 * @author Darko Goleš
 * @copyright Inchoo
 * @license http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

class Inchoo_Demostore_Model_Sales_Order_Random {

    protected $_quote;
    protected $_order;
    protected $_store;
    protected $_customer;
    protected $_productCollection;
    protected static $_storeCollection;
    protected static $_customerCollection;

    public function __construct() {
        $this-&gt;_quote = Mage::getModel('sales/quote')-&gt;save();
        $this-&gt;_order = Mage::getModel('sales/order');
    }

    protected function _getStores() {
        if (!self::$_storeCollection) {
            self::$_storeCollection = Mage::getResourceModel('core/store_collection')
                    -&gt;load();
        }
        return self::$_storeCollection-&gt;getItems();
    }

    protected function _getCustomers() {
        if (!self::$_customerCollection) {
            self::$_customerCollection = Mage::getResourceModel('customer/customer_collection')
                    -&gt;addAttributeToSelect('*')
                    -&gt;joinAttribute('billing_country_id', 'customer_address/country_id', 'default_billing', null, 'inner')
                    -&gt;joinAttribute('shipping_country_id', 'customer_address/country_id', 'default_shipping', null, 'inner')
                    -&gt;load();
        }

        return self::$_customerCollection-&gt;getItems();
    }

    protected function _getProducts() {
        if (!$this-&gt;_productCollection) {
            $this-&gt;_productCollection = Mage::getResourceModel('catalog/product_collection');
            Mage::getSingleton('catalog/product_status')-&gt;addVisibleFilterToCollection($this-&gt;_productCollection);
            $this-&gt;_productCollection-&gt;addAttributeToSelect('name')
                    -&gt;addAttributeToSelect('sku')
                    -&gt;addAttributeToFilter('type_id', Mage_Catalog_Model_Product_Type::TYPE_SIMPLE)
                    -&gt;load();
        }

        return $this-&gt;_productCollection-&gt;getItems();
    }

    protected function _getCustomer() {
        if (!$this-&gt;_customer) {
            $items = $this-&gt;_getCustomers();
            $randKey = array_rand($items);
            $this-&gt;_customer = $items[$randKey];
        }
        return $this-&gt;_customer;
    }

    protected function _getRandomProduct() {
        $items = $this-&gt;_getProducts();
        $randKey = array_rand($items);
        return isset($items[$randKey]) ? $items[$randKey] : false;
    }

    protected function _getStore() {
        if (!$this-&gt;_store) {
            $items = $this-&gt;_getStores();
            $randKey = array_rand($items);
            $this-&gt;_store = $items[$randKey];
        }
        return $this-&gt;_store;
    }

    public function createOrder() {
        $customer = $this-&gt;_getCustomer();

        $this-&gt;_quote-&gt;setStore($this-&gt;_getStore())
                -&gt;setCustomer($customer)-&gt;setCustomerIsGuest(0);
        $this-&gt;_quote-&gt;getBillingAddress()-&gt;importCustomerAddress($customer-&gt;getDefaultBillingAddress());
        $this-&gt;_quote-&gt;getShippingAddress()-&gt;importCustomerAddress($customer-&gt;getDefaultShippingAddress());

        $productCount = rand(3, 10);
        for ($i = 0; $i &lt; $productCount; $i++) {             $product = $this-&gt;_getRandomProduct();
            if ($product) {
                $product-&gt;setQuoteQty(1);

                $stockData = $product-&gt;getStockData();
                if (!$stockData) {
                    $product = $product-&gt;load($product-&gt;getId());
                    $stockData = array(
                        'manage_stock' =&gt; 1,
                        'is_in_stock' =&gt; 1,
                        'qty' =&gt; 1
                    );

                    $product-&gt;setStockData($stockData);
                    $product-&gt;save();
                }
                $this-&gt;_quote-&gt;addProduct($product);
            }
        }

        $this-&gt;_quote-&gt;getPayment()-&gt;setMethod('checkmo');
        $this-&gt;_quote-&gt;getShippingAddress()-&gt;setShippingMethod('flatrate_flatrate'); //-&gt;collectTotals()-&gt;save();
        $this-&gt;_quote-&gt;getShippingAddress()-&gt;setCollectShippingRates(true);
        $this-&gt;_quote-&gt;collectTotals()
                -&gt;save();
        $this-&gt;_quote-&gt;save();

        $service = Mage::getModel('sales/service_quote', $this-&gt;_quote);
        $service-&gt;submitAll();

        $order = $service-&gt;getOrder();
        $rand = rand(1, 4);

        switch ($rand) {
            case 1:
                $this-&gt;invoiceOrder($order);
                break;
            case 2:
                $this-&gt;shipOrder($order);
                break;
            case 3:
                $this-&gt;invoiceOrder($order);
                $this-&gt;shipOrder($order);
                break;
            default:
                break;
        }

        return $this;
    }

    protected function invoiceOrder($order) {

        try {

            if (!$order-&gt;canInvoice()) {
                $order-&gt;addStatusHistoryComment('Inchoo_Invoicer: Order cannot be invoiced.', false);
                $order-&gt;save();
            }

            $invoice = Mage::getModel('sales/service_order', $order)-&gt;prepareInvoice();

            $invoice-&gt;setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
            $invoice-&gt;register();

            $invoice-&gt;getOrder()-&gt;setCustomerNoteNotify(false);
            $invoice-&gt;getOrder()-&gt;setIsInProcess(true);
            $order-&gt;addStatusHistoryComment('Automatically INVOICED by Inchoo_Invoicer.', false);

            $transactionSave = Mage::getModel('core/resource_transaction')
                    -&gt;addObject($invoice)
                    -&gt;addObject($invoice-&gt;getOrder());

            $transactionSave-&gt;save();
        } catch (Exception $e) {
            Mage::logException($e);
        }
    }

    protected function shipOrder($order) {

        try {
            $shipment = $order-&gt;prepareShipment();
            $shipment-&gt;register();

            $order-&gt;setIsInProcess(true);
            $order-&gt;addStatusHistoryComment('Automatically SHIPPED by Inchoo_Invoicer.', false);

            $transactionSave = Mage::getModel('core/resource_transaction')
                    -&gt;addObject($shipment)
                    -&gt;addObject($shipment-&gt;getOrder())
                    -&gt;save();
        } catch (Exception $e) {
            Mage::logException($e);
        }
    }

}
</pre>
<p>As you can see from source code, invoice and shipment will not be generated every time, but random sometimes shipment, sometimes order, sometimes both and sometimes nothing.</p>
<pre class="brush: php; title: ; notranslate">

       $order = $service-&gt;getOrder();
        $rand = rand(1, 4);

        switch ($rand) {
            case 1:
                $this-&gt;invoiceOrder($order);
                break;
            case 2:
                $this-&gt;shipOrder($order);
                break;
            case 3:
                $this-&gt;invoiceOrder($order);
                $this-&gt;shipOrder($order);
                break;
            default:
                break;
        }
</pre>
<p>There are bunch of articles here on inchoo.net about programatically creating orders and/or customers, so this article is not about how to do it, but rather to inform the community that the extension that I am talking about is available on Magento Connect under name: Inchoo Demostore, so, Dear developers, if you need to save some time, feel free to install it to dynamically &#8211; periodically create new customers and orders on your development or some demo server.</p>
<p>I am aware that this extension can be improved with possible configuration options added, maybe on admin side, adding additional features for creating orders, random quantities for order items, but, hey &#8211; this extension is made for developers to save their time, and I don&#8217;t see a problem if someone wants to improve it. For me, it it enough to give fresh data to demo store for <a title="Mageboard" href="http://mageboard.inchoo.net/" target="_blank">Mageboard Application</a>.</p>
<p>Cheers.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/ecommerce/magento/inchoo-demostore-extension/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Magento with xDebug, web services API and testUnit</title>
		<link>http://inchoo.net/ecommerce/magento/magento-xdebug/</link>
		<comments>http://inchoo.net/ecommerce/magento/magento-xdebug/#comments</comments>
		<pubDate>Tue, 20 Mar 2012 07:56:43 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[xdebug]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=12676</guid>
		<description><![CDATA[Using xDebug from NetBeans is pretty straightforward and after installing xDebug from their website does not require some special configuration in order to make it work. If you visit the &#8230;]]></description>
			<content:encoded><![CDATA[<p>Using xDebug from NetBeans is pretty straightforward and after installing <a title="xDebug" href="http://xdebug.org/find-binary.php" target="_blank">xDebug from their websit</a>e does not require some special configuration in order to make it work.<br />
If you visit the link above, you will notice that it&#8217;s enough to paste the source code of your phpinfo() and you will get directions what xDebug binary to download and how to set it.<span id="more-12676"></span></p>
<p>Assuming you did it already, let&#8217;s make it work in our NetBeans IDE.<br />
Open NetBeans and go to &#8216;Tools/Options&#8217; and click on &#8216;PHP&#8217; tab.<br />
On &#8216;General&#8217; tab inside, you will find options for xDebug configuration inside Netbeans. I just left all values predefined.</p>
<p>You have few options there to choose, and choose what you like, but make sure that port in which xDebug is set to run in php.ini is the same entered here.</p>
<p>Now, let&#8217;s test if xDebug is working. Assuming that you already have your Magento project opened in editor, just hit &#8216;Ctrl+F5&#8242; to start debugging session. What should happen is that your browser window should be opened wit URL like this:</p>
<p><strong>http://yourLocalMagentoUrl/index.php?XDEBUG_SESSION_START=netbeans-xdebug</strong></p>
<p>you can notice XDEBUG_SESSION START parameter inside URL.<br />
If you did all like I wrote and noting like this happens, then try to reconfigure your xDebug and/or NetBeans to make it work properly.</p>
<p>If you read my last article, you will find some example how to call Magento V2 Soap web services from test unit with SoapClient.</p>
<p><strong>So, what&#8217;s the current problem?</strong></p>
<p>If you set some breakpoints inside your code that will be executed, debugger will stop there and you can debug your or Magento/&#8217;s source code, look at variables window etc, but what will happen if we need to debug server- side of Magento&#8217;s web services or our extension to API V2 and all that from out test unit where SoapClient calls are implemented.</p>
<p><strong>How to tell to debugger to start the session and handle web service calls on server – side?</strong></p>
<p>To do so, the easier way I found is:</p>
<p>1. Start debugging with &#8216;Ctrl+F5&#8242; and browser window opens &#8230;<br />
2. Leave that browser window open and add XDEBUG_SESSION cookie to your soap client inside your unit test:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

require_once 'PHPUnit/Autoload.php';
require_once '../app/Mage.php';

class customerCustomerTest extends PHPUnit_Framework_TestCase {

    private $local_url_v2 = &quot;http://192.168.1.91/api/v2_soap/?wsdl=1&quot;;

    private $api_url_v1;
    private $api_url_v2;

    public function setUp() {
        Mage::app('default');

        $this-&gt;setApiUrlV2($this-&gt;local_url_v2);

    }

    public function getApiUrlV2() {
        return $this-&gt;api_url_v2;
    }

    public function setApiUrlV2($api_url_v2) {
        $this-&gt;api_url_v2 = $api_url_v2;
    }

    public function testLogin() {
        $cli = new SoapClient($this-&gt;api_url_v2);

        $username = 'mobile';
        $password = 'mobile123';
        $result = $cli-&gt;login($username, $password);
        $session_id = isset($result) ? $result : null;

        $this-&gt;assertNotNull($session_id);
        return $session_id;
    }

    public function testCoreCustomerList_V2() {

        $session_id = $this-&gt;testLogin();
        $cli = new SoapClient($this-&gt;api_url_v2);
        $cli-&gt;__setCookie('XDEBUG_SESSION', 'netbeans-xdebug');
        $result = $cli-&gt;customerCustomerList($session_id);

        $this-&gt;assertTrue(is_array($result));
        foreach ($result as $res) {
            $this-&gt;assertObjectHasAttribute('customer_id', $res);
        }
    }
</pre>
<p>Now set the breakpoints inside reachable code and run your tests with &#8216;Alt+F6&#8242;.</p>
<p>Your debugger will stop at your and debugging can start ….. <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/ecommerce/magento/magento-xdebug/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Magento API V2 Soap unit testing</title>
		<link>http://inchoo.net/ecommerce/magento/magento-api-v2-soap-unit-testing/</link>
		<comments>http://inchoo.net/ecommerce/magento/magento-api-v2-soap-unit-testing/#comments</comments>
		<pubDate>Thu, 15 Mar 2012 12:22:00 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Debugging]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[web services]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=12621</guid>
		<description><![CDATA[In previous article, I wrote about setting up environment for Magento unit testing. Let&#8217;s expand our tests to test some Magento&#8217;s API calls with soap. Let&#8217;s add first tests in &#8230;]]></description>
			<content:encoded><![CDATA[<p>In previous article, I wrote about setting up environment for Magento unit testing. Let&#8217;s expand our tests to test some Magento&#8217;s API calls with soap.<span id="more-12621"></span></p>
<p>Let&#8217;s add first tests in our Tests/customerCustomerTest.php</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

require_once 'PHPUnit/Autoload.php';
require_once '../app/Mage.php';

class customerCustomerTest extends PHPUnit_Framework_TestCase {

private $local_url_v1 = &quot;http://192.168.1.91/api/soap/?wsdl=1&quot;;
private $local_url_v2 = &quot;http://192.168.1.91/api/v2_soap/?wsdl=1&quot;;
private $api_url_v1;
private $api_url_v2;

public function setUp() {
    Mage::app('default');
    $this-&gt;setApiUrlV2($this-&gt;local_url_v2);
}

public function getApiUrlV2() {
    return $this-&gt;api_url_v2;
}

public function setApiUrlV2($api_url_v2) {
    $this-&gt;api_url_v2 = $api_url_v2;
}

public function testLogin() {

   $cli = new SoapClient($this-&gt;api_url_v2);

   $username = 'mobile';
   $password = 'mobile123';

   $result = $cli-&gt;login($username, $password);
   $session_id = isset($result) ? $result : null;

   $this-&gt;assertNotNull($session_id);
   return $session_id;
}

public function testCoreCustomerList_V2() {

   $session_id = $this-&gt;testLogin();
   $cli = new SoapClient($this-&gt;api_url_v2);
   $result = $cli-&gt;customerCustomerList($session_id);

   $this-&gt;assertTrue(is_array($result));
   foreach ($result as $res) {
      $this-&gt;assertObjectHasAttribute('customer_id', $res);
   }
 }

}
</pre>
<p>Here we added two test methods: first one id login and it&#8217;s neccesary to return session Id for using in other API calls. Also it is neccesary to add mobile user with appropiate roles in administration of your Magento installation.</p>
<p>Hope that this article was useful to you.</p>
<p>Cheers.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/ecommerce/magento/magento-api-v2-soap-unit-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Magento learning – developer&#8217;s first touch</title>
		<link>http://inchoo.net/ecommerce/magento/magento-first-touch/</link>
		<comments>http://inchoo.net/ecommerce/magento/magento-first-touch/#comments</comments>
		<pubDate>Sat, 25 Feb 2012 15:17:48 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[resources]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=12575</guid>
		<description><![CDATA[Hello everybody! Hello whole Magento community! Until now i wrote articles most about Symfony2 and some about Android platform. Someone somewhere said: “man has got to do what men has &#8230;]]></description>
			<content:encoded><![CDATA[<p><strong>Hello everybody! Hello whole Magento community!</strong></p>
<p>Until now i wrote articles most about Symfony2 and some about Android platform. Someone somewhere said: “<em>man has got to do what men has got to do &#8230;</em> “ and of course, the time for me to swim in Magento&#8217;s waters has came too … <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> <span id="more-12575"></span></p>
<p>Since I am the <span style="text-decoration: underline;">PROUD</span> member of Inchoo&#8217;s mobile team, guess what?<br />
From early beginning in Inchoo I am struggling most the time with all different kinds of web services &#8211; from custom made REST API to rpc web services. Of course this time with Magento is almost the same, but from now I am deep inside SOAP web service waters ….</p>
<p>On our blog, there are already bunch of Magento&#8217;s articles, but I promise that I will do my best to make mine somehow also interesting and usable for you.</p>
<p>Most of my colleagues are deep in Magento&#8217;s waters already (lucky for me), while I am going to have a few hard months to &#8216;override&#8217; beginner&#8217;s mistakes and problems while developing on Magento&#8217;s platform. But from other perspective – I think it&#8217;s good to share my experience in learning Magento with you – at least for visitors that are starting to learn Magento like I did.</p>
<p>Let me give a few tips for early beginners to make this start learning process easier:</p>
<ol>
<li><strong> Before installing Magento, prepare your database and install <a title="New Magento Sample Data" href="http://inchoo.net/ecommerce/magento/magento-sample-data/" target="_blank">New Magento Sample Data</a>  (thanks to <a title="Ivan Weiler" href="http://inchoo.net/author/weiler/" target="_blank">Ivan Weiler</a>)</strong></li>
<li><strong> Install Magento on your localhost (of course) – I am using 1.6.2 community version</strong></li>
<li><strong> Log in inside admin area and get to know better what Magento can do. You may wish to go to read official Wiki pages and to Google for official &#8216;Magento user guide&#8217; for that …</strong></li>
<li><strong> Go to frontend and make some test – shopping to see how it works</strong></li>
<li><strong> Install <a title="xDebug" href="http://xdebug.org/docs/install" target="_blank">xDebug</a>  on your system and make it works with your favorite IDE – trust me – it WILL make your life easier when trying to figure out what is going on with your code …</strong></li>
<li><strong> If you are care about your code, don&#8217;t regret to install phpUnit and from early beginning development &#8211; start to write unit tests about what you are doing …</strong></li>
<li><strong>Folow <a title="Configuring Magento for development" href="http://inchoo.net/ecommerce/magento/configuring-magento-for-development/" target="_blank">this  article</a> (thanks to <a title="Branko Ajzele" href="http://inchoo.net/author/branko/" target="_blank">Branko Ajzele</a>)  to set-up your Magento installation for development</strong></li>
<li><strong>Start learning development on Magento</strong></li>
</ol>
<p>Knowing that learning development on Magento&#8217;s platform from scratch can be hard times even for experienced developer I strongly suggest you to go to official Magento&#8217;s page and find <strong><a title="Magento training" href="http://www.magentocommerce.com/training/on-demand" target="_blank">Magento&#8217;s &#8216;On-Demand: Online Courses</a>&#8216;</strong> that have currently (while I am writing this post) absolutely free &#8216;<strong>Fundamentals of Magento development</strong>&#8216; video courses that WILL help you a lot in learning process.<br />
My suggestion is to see all of those videos first, and then to start with other learning resources. Trust me It&#8217;s worth your time ….</p>
<p>Of course don&#8217;t forget to go through <a title="Alan Storm" href="http://www.magentocommerce.com/knowledge-base/categories/category/development" target="_blank">Alan Storm&#8217;s articles.</a>..</p>
<p>After all, if you are already reading this article, you are already on our official blog, so take your time and go thorough <a title="Inchoo" href="http://inchoo.net/category/ecommerce/magento/" target="_blank"><em>Inchoo&#8217;s articles about Magento development</em></a>&#8230;</p>
<p>As I told before, I will mostly write about Magento&#8217;s API, so if you are interested in that part of development, stay tuned … <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/ecommerce/magento/magento-first-touch/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Android &#8211; playing with separate threads</title>
		<link>http://inchoo.net/mobile-development/android-development/android-threads/</link>
		<comments>http://inchoo.net/mobile-development/android-development/android-threads/#comments</comments>
		<pubDate>Mon, 20 Feb 2012 08:11:19 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Android development]]></category>
		<category><![CDATA[Android]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[Thread]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=12330</guid>
		<description><![CDATA[This time, I played a little with Threads and I tried to implement somekind of simple-test separate thread and start it inside main activity and also return results from separate &#8230;]]></description>
			<content:encoded><![CDATA[<p>This time, I played a little with Threads and I tried to implement somekind of simple-test separate thread and start it inside main activity and also return results from separate Thread so it can be used to update UI for example.<span id="more-12330"></span></p>
<p>As you probably know, I am not officialy android nor java developer so, please don&#8217;t take this post bad if something is maybe not explained as you expected to be. I am still playing with android source code and trying to transfer my own understanding and opinion here on this blog that will maybe help someone&#8230;</p>
<p>This is how my activity looks like:</p>
<pre class="brush: php; title: ; notranslate">

package com.inchoo.tutorial;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

public class AndroidservicetutorialActivity extends Activity {

	final Handler mHandler = new Handler();

	private String mResult;

	// Create runnable for posting
	final Runnable mUpdateResults = new Runnable() {
		public void run() {
			Log.d(&quot;Inchoo tutorial&quot;, mResult);
		}
	};

	protected void startTestThread() {
		Thread t = new Thread() {
			public void run() {

				Log.d(&quot;Inchoo tutorial&quot;, &quot;My thread is running&quot;);
				mResult = &quot;This is my new result&quot;;
				mHandler.post(mUpdateResults);
			}
		};

		t.start();
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		startTestThread();
	}

}
</pre>
<p>Let me try to explain this code.</p>
<p>When out activity starts (onCreate), we are starting a new thread with function startTestThread.<br />
That function should execute something and get some results.<br />
When we have results, we are starting our defined mUpdateResults runnable by posting it to message queue of main (activity&#8217;s thread). It gets value of mResult variable in order to update something with given data.<br />
This is a simple example of running different threads and comunicating between them.<br />
I hop this post will help someone to better understand given logic.</p>
<p>Cheers. <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/mobile-development/android-development/android-threads/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Configuring Magento for development</title>
		<link>http://inchoo.net/ecommerce/magento/configuring-magento-for-development/</link>
		<comments>http://inchoo.net/ecommerce/magento/configuring-magento-for-development/#comments</comments>
		<pubDate>Thu, 20 Oct 2011 06:41:22 +0000</pubDate>
		<dc:creator>Branko Ajzele</dc:creator>
				<category><![CDATA[Magento]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Starting up]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[development]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=11033</guid>
		<description><![CDATA[New to the Magento or just used to doing things one way? Here are few tips for configuring Magento for development, in case you overlooked them. Please note, the more &#8230;]]></description>
			<content:encoded><![CDATA[<p>New to the Magento or just used to doing things one way? Here are few tips for configuring Magento for development, in case you overlooked them. Please note, the more proper title of this article would be something like: Configuring Magento for development on local machine (after installation config). Meaning the tips outlined here only apply after the Magento is already installed.<span id="more-11033"></span></p>
<p>Here are the steps that you should do in order to set your Magento more suited for development:</p>
<ul>
<li>System > Cache Management > Disable All</li>
<li>System > Configuration > Advanced > Developer > Log Settings > Enabled => Yes</li>
<li>System > Configuration > Web > Search Engine Optimization > Use Wbe Server Rewrites => Yes</li>
<li>System > Index Management > Reindex All</li>
<li>Open .htaccess and set: SetEnv MAGE_IS_DEVELOPER_MODE &#8220;true&#8221; at the end of the file</li>
<li>Open .htaccess and set: php_value display_errors On somewhere within &#60;IfModule mod_php5.c&#62;</li>
<li>Rename /errors/local.xml.sample to /errors/local.xml</li>
<li>Create one sample customer with full valid American address (for example use US/California, city Alamo with ZIP 94507), and one with full valid non American address (other country) to test payment and shipping gateways properly</li>
<li>Compensate for the possible lack of email server by doing something like explained in <a href="http://inchoo.net/ecommerce/magento/magento-l-e-s-s/">this article</a></li>
</ul>
<p>Hope it helps.</p>
<p>Cheers.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/ecommerce/magento/configuring-magento-for-development/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Creating simple Symfony2 service</title>
		<link>http://inchoo.net/tools-frameworks/symfony2-service/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony2-service/#comments</comments>
		<pubDate>Sat, 10 Sep 2011 07:10:09 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[services]]></category>
		<category><![CDATA[Symfony 2]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=10698</guid>
		<description><![CDATA[I am not talking about web services, but I am talking about symfony2 service container and the way of basic creating services inside Symfony2 project that are accessible from all &#8230;]]></description>
			<content:encoded><![CDATA[<p>I am not talking about web services, but I am talking about symfony2 service container and the way of basic creating services inside Symfony2 project that are accessible from all other bundles via service container.</p>
<p>Why do I need to make some part of code like service inside Symfony2 anyway?</p>
<p>There is one possible problem:<span id="more-10698"></span></p>
<p>When I started my project, I started with administrator area of application for handling CRUD operations. But this bundle is just for administrators of application. On the other side, I have to provide REST web service API that will be consumed by various devices (iPhone, Android, …).<br />
I don&#8217;t want to put together my code for administrators and web services API code. So, after AdminBundle was finished, I decided to make another bundle inside project that will be &#8216;public&#8217; side bundle and called it: ApiBundle. Inside this I will provide data that is entered and organized inside Admin area of application with REST based API .</p>
<p>For API, I also need same Entities used inside Admin Bundle that will handle database layer for web services too.</p>
<p>If I try to use  my entities that currently are inside AdminBundle from API bundle it doesn&#8217;t sounds logically to me. What if I want to separate API bundle from Admin Bundle in the future. How will I then use my entities in both? Duplicate them? I don&#8217;t think so!</p>
<p>For purposes like this, it&#8217;s better to create one more, separate Bundle that I called &#8216;CoreBundle&#8217; that will hold all shared classes and also my entity classes for both: AdminBundle and ApiBundle.</p>
<p>Accessing those classes from AdminBundle and also ApiBundle I want to be via service container, so all of these methods are separated and public available for using in other bundles.</p>
<p>Because of that, I want to build simple Symfony2 services: one for AdminBundle and second for ApiBundle – to separate application logic.</p>
<p>Inside CoreBundle, I made folder called &#8216;Services&#8217; and inside I put two files: Admin.php and Api.php.</p>
<p>Inside CoreBundle\Resources\config I made some changes to the file called &#8216;services.xml&#8217;:</p>
<pre class="brush: php; title: ; notranslate">

&lt;?xml version=&quot;1.0&quot; ?&gt;

&lt;container xmlns=&quot;http://symfony.com/schema/dic/services&quot;
  xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
  xsi:schemaLocation=&quot;http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd&quot;&gt;

  &lt;parameters&gt;
     &lt;parameter key=&quot;surgeworks_core.admin.class&quot;&gt;Surgeworks\CoreBundle\Services\Admin&lt;/parameter&gt;
     &lt;parameter key=&quot;surgeworks_core.api.class&quot;&gt;Surgeworks\CoreBundle\Services\Api&lt;/parameter&gt;
  &lt;/parameters&gt;

  &lt;services&gt;
     &lt;service id=&quot;surgeworks_core.admin&quot;&gt;
        &lt;argument type=&quot;service&quot; id=&quot;service_container&quot; /&gt;
     &lt;/service&gt;
     &lt;service id=&quot;surgeworks_core.api&quot;&gt;
        &lt;argument type=&quot;service&quot; id=&quot;service_container&quot; /&gt;
     &lt;/service&gt;
  &lt;/services&gt;
&lt;/container&gt;
</pre>
<pre class="brush: php; title: ; notranslate">

//...

&lt;?php
// Surgeworks\CoreBundle\DependencyInjection\Configuration.php
namespace Surgeworks\CoreBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
 {
   $treeBuilder = new TreeBuilder();
   $rootNode = $treeBuilder-&gt;root('surgeworks_core');

// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.

   return $treeBuilder;
 }
}

//...
</pre>
<p>I just have to write my own functions inside mentioned Admin.php and Api.php and call them via service container from amy bundle&#8217;s controller:</p>
<pre class="brush: php; title: ; notranslate">

//some controller
public function testAction()
{
   $statusesCount = $this-&gt;get('surgeworks_core.admin')-&gt; Statuses_getCount();
}
</pre>
<p>And function inside Admin.php:</p>
<pre class="brush: php; title: ; notranslate">

public function Statuses_getCount() {
   $repository = $this-&gt;getEm()-&gt;getRepository('Surgeworks\CoreBundle\Entity\Status');
   $statusesCount = $repository-&gt;getStatusesCount();
   return $statusesCount;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony2-service/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Creating your own web shop &#8211; Part 1: Where to start</title>
		<link>http://inchoo.net/ecommerce/creating-your-own-web-shop-part-1-where-to-start/</link>
		<comments>http://inchoo.net/ecommerce/creating-your-own-web-shop-part-1-where-to-start/#comments</comments>
		<pubDate>Sun, 07 Aug 2011 09:56:48 +0000</pubDate>
		<dc:creator>Branko Ajzele</dc:creator>
				<category><![CDATA[E-Commerce]]></category>
		<category><![CDATA[custom]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Magento]]></category>
		<category><![CDATA[web shop]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=10576</guid>
		<description><![CDATA[Creating your own web shop can be a tedious task, both technically and time consuming. Not to mention there are tens of quality PHP based web shop systems out there &#8230;]]></description>
			<content:encoded><![CDATA[<p>Creating your own web shop can be a tedious task, both technically and time consuming. Not to mention there are tens of quality PHP based web shop systems out there available for free. One of the best if you ask me is Magento, which exceeds the term web shop system by even bigger term &#8220;platform&#8221;. However, regardless of how some much a given system/platform is feature rich there are always those special clients with special requests which exceed the possibilities of even the mightiest eCommerce systems/platforms out there.<span id="more-10576"></span></p>
<p>In my experience, usually these type of clients are either big enterprise level clients or &#8220;small first time running a web shop&#8221; client. Big enterprise level clients usually know very well what they want as they outgrown the features even the most feature rich platforms can give them out of the box.</p>
<p>Before I go any further, I would just like to clarify one thing. This article is by no means advice or suggestion you should consider building your own web shop solution over choosing Magento CE, PE, or EE or possibly some other professional/enterprise web shop platform. In my opinion doing so would only be justified in situations where desired feature list massively exceeds the features offered by any of Magento versions, or if your budget and delivery date are of no or little importance.</p>
<p>Seems like building your own web shop system these days comes down to (1) satisfying your personal needs as a developer (meaning you got some time on your hand and you wish to play with building something out of the scratch just so see if you can do it), (2) You really have a special feature list you need to implement in your own web shop while at the same time you do not need all or any of the features offered by powerful web shops that are already there. Everything else seems just like reinventing a wheel, because all it takes is to develop extensions/modules for existing systems/platforms and save yourself both money and time.</p>
<p>OK, enough for the introduction. Let&#8221;s get down to it. Where to start when creating your own shop? I would say there are five major topic that need to be outlined: </p>
<ul>
<li>Feature list (<i>in a broader term this should come with proper software requirements, as noted by <a href="http://inchoo.net/ecommerce/creating-your-own-web-shop-part-1-where-to-start/#comment-22233">beeplogic</a> below in comments</i>),</li>
<li>Development platform selection,</li>
<li>Overall budget</li>
<li>Available resources</li>
<li>Expected date of delivery</li>
</ul>
<p><strong>Feature list</strong> should cover a full list of requested features, like: Customer Single Sign On (Facebook, Twitter), One Step Checkout, Implementation of XYZ payment gateway, Product Review/Comments System, Multi-language, Multi-currency, Email Notifications System, Product types (standard, downloadable, bundle), etc.</p>
<p><strong>Development platform selection</strong> should evaluate possibly several different platforms that might be interested for our project. For example, usage of Zend Framework over Symfony over CodeIgniter over cakePHP etc., if we are talking about PHP platforms.</p>
<p><strong>Overall budget</strong> is pretty clear. Probably the most important thing here to note is that you should never plan your project on &#8220;how to spent entire budget&#8221; but more like &#8220;how to deliver all or most of the features by expected delivery date not exceeding the overall budget&#8221; concept. Sometimes clients need reality check, and they need to be forced to either prioritize or dismiss certain features if the budget is low.</p>
<p><strong>Available resources</strong> are all those people (developers, designers, project manager) in your team which you know will be working on a given project.</p>
<p><strong>Expected date of delivery</strong> is extremely important in the big picture as it represents the link between feature list, overall budget and available resources. For example, imagine someone gives you a budget of $500K, in order to deliver a system with 50 outlined features with a team of 7 experienced people working on it within 3 months. Let&#8221;s assume you take $120/hour for development services. It comes down to $120/hour * 8h/day * 5days/week * 4weeks/month = $ 19.200,00 per month per developer. Which is around $134.400,00 per month for entire 7 people team. In 3 months time this turns out to be $403.200,00 meaning you are not able to spent all of the budget available. Biggest mistake for a project and people on it you can do here is to throw in a few newbies just to fill in the gap for reaching the budget limit. This disrupts the workflow of the rest of the team for two reasons: (a) newbie developers need significant time to get to the level of senior developers thus not being nearly productive as other team members, (b) each team expansion requires extra management input or even change in management philosophy.</p>
<p>What I outlined above usually makes sense in business environment where entire team is working on a new system/platform. Things are significantly different if you alone are trying to create something in your own time (usually as a hobby). In that case we are usually focused on first two topics: (1) Feature list and (2) Development platform selection. Meaning we have no budged to look at, no expected delivery date to worry about.</p>
<p>In my next articles under this topic I will focus strictly on development platform selection and the actual development of web shop from ground up. Until then, I&#8221;ll give you a hint&#8230; Symfony + Zend Framework + Ext JS <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Cheers.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/ecommerce/creating-your-own-web-shop-part-1-where-to-start/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Doctrine DBAL with Symfony2</title>
		<link>http://inchoo.net/tools-frameworks/doctrine-dbal-with-symfony2/</link>
		<comments>http://inchoo.net/tools-frameworks/doctrine-dbal-with-symfony2/#comments</comments>
		<pubDate>Sun, 31 Jul 2011 10:15:36 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Symfony 2]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=10489</guid>
		<description><![CDATA[I regularly use Doctrine ORM for database operations in my Symfony2 project, but there was one situation that I had to write database importer from SQLITE database into projects Mysql &#8230;]]></description>
			<content:encoded><![CDATA[<p>I regularly use Doctrine ORM for database operations in my Symfony2 project, but there was one situation that I had to write database importer from SQLITE database into projects Mysql database. Importer should run only once and I didn&#8217;t want to make new entity classes for importer, but just make code to work while import is not finished.<span id="more-10489"></span><br />
That case I used Doctrine DBAL  (database abstraction layer).<br />
What we need to use DBAL in Symfony2?</p>
<p>Let&#8217;s start from our main configuration file:</p>
<pre class="brush: php; title: ; notranslate">
#config.yml

#...

# Doctrine Configuration
doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                charset:  UTF8
                driver:   %database_driver%
                host:     %database_host%
                dbname:   %database_name%
                user:     %database_user%
                password: %database_password%
            sqlite:
                driver:  %sqlite_driver%
                path:    %sqlite_path%
    orm:
        auto_generate_proxy_classes: %kernel.debug%
        #auto_mapping: true
        default_entity_manager: default
        entity_managers:
            default:
                connection: default
                mappings:
                   SurgeworksAdminBundle: { type: annotation, dir: Entity/ }

#...
</pre>
<p>For Sqlite is necessary just to specify driver and path to database file. I put the database file inside &#8216;app&#8217; folder. My parameters.ini file looks like that:</p>
<pre class="brush: php; title: ; notranslate">
[parameters]
    database_driver=&quot;pdo_mysql&quot;
    database_host=&quot;localhost&quot;
    database_name=&quot;databasename&quot;
    database_user=&quot;someuser&quot;
    database_password=&quot;somepassword&quot;
    mailer_transport=&quot;smtp&quot;
    mailer_host=&quot;localhost&quot;
    mailer_user=&quot;&quot;
    mailer_password=&quot;&quot;
    locale=&quot;en&quot;
    secret=&quot;somesecret&quot;
    sqlite_driver=pdo_sqlite
    sqlite_path=%kernel.root_dir%/sqlite_database_name.db
</pre>
<p>That&#8217;s it from configuration side. Let&#8217;s show how to use it:</p>
<pre class="brush: php; title: ; notranslate">
//...
//Get DBAL connection
//Notice: sqlite_connection is in form: name_connection  - where
//name is connection name defined in config file.
$conn = $this-&gt;getContainer()-&gt;get('doctrine.dbal.sqlite_connection');
$some_array = $conn-&gt;fetchAll('SELECT * FROM yourtablename');
//...
</pre>
<p>And basically, that&#8217;s it.<br />
I always didn&#8217;t wand dealing much with insert strings in sql when you need to add some dynamically created data inside query:</p>
<pre class="brush: php; title: ; notranslate">
// ...
$conn-&gt;exec(“INSERT INTO  sometable (somecolumn ) VALUES (“ . $somevalue . ”)”);
// …
</pre>
<p>What I found very interesting with Doctrine2 DBAL is much cleaner way to do this:</p>
<pre class="brush: php; title: ; notranslate">
            $sql = 'INSERT INTO attributes (
                date_created,
                date_modified
                ) VALUES (?,?)';
            $stmt = $conn_backup-&gt;prepare($sql);
            $stmt-&gt;bindValue(1, $datecreated);
            $stmt-&gt;bindValue(2, $datemodified);
            $stmt-&gt;execute();
</pre>
<p>Of course there is more:</p>
<pre class="brush: php; title: ; notranslate">
 // ..
$conn-&gt;insert('attributes', array('date_created' =&gt; $datecreated));
//..
</pre>
<p>You just have to choose method you like more &#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/doctrine-dbal-with-symfony2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Symfony2 writing data-fixtures</title>
		<link>http://inchoo.net/tools-frameworks/symfony2-data-fixtures-part2/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony2-data-fixtures-part2/#comments</comments>
		<pubDate>Sat, 30 Jul 2011 10:00:21 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Symfony 2]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=10471</guid>
		<description><![CDATA[In last article about fixtures I wrote about manual setup for using data-fixtures with your Symfony2 project. Now it&#8217;s time to write first data fixture. Inside your bundle, create folder &#8230;]]></description>
			<content:encoded><![CDATA[<p>In last article about fixtures I wrote about manual setup for using data-fixtures with your Symfony2 project.<br />
Now it&#8217;s time to write first data fixture.<span id="more-10471"></span></p>
<p>Inside your bundle, create folder called: DataFixtures.</p>
<p>We are going to use Doctrine ORM with that so create folder inside called &#8216;ORM&#8217;.</p>
<p>Inside that folder create new file called: FixtureLoader.php</p>
<pre class="brush: php; title: ; notranslate">

&lt;?php
//Surgeworks\AdminBundle\DataFixtures\ORM\FixtureLoader.php

namespace Surgeworks\AdminBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Surgeworks\AdminBundle\Entity\User;
use Surgeworks\AdminBundle\Entity\Role;
use Surgeworks\AdminBundle\Entity\AttributeType;
use Symfony\Component\Security\Core\Encoder\MessageDigestPasswordEncoder;

class FixtureLoader implements FixtureInterface {

public function load($manager) {
   $roleSA = new Role();
   $roleSA-&gt;setName('ROLE_SUPER_ADMINISTRATOR');
   $manager-&gt;persist($roleSA);
   $encoder = new MessageDigestPasswordEncoder('sha512', true, 10);

   $user = new User();
   $user-&gt;setFirstName('Darko');
   $user-&gt;setLastName('Goleš');
   $user-&gt;setEmail('darko.goles@surgeworks.com');
   $user-&gt;setUsername('darko.goles');
   $user-&gt;setSalt(md5(time()));
   $password = $encoder-&gt;encodePassword(
       'dont_want_to_tell_you', $user-&gt;getSalt());
   $user-&gt;setPassword($password);
   $user-&gt;getUserRoles()-&gt;add($roleSA);
   $manager-&gt;persist($user);

   $manager-&gt;flush();

}

}
</pre>
<p>Fire up the console, cd to app folder of you project and write:</p>
<pre class="brush: php; title: ; notranslate">

php console doctrine:fixtures:load
</pre>
<p>Command purges the database and inserts fixtures inside.<br />
That&#8217;s it for now,  Cheers <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony2-data-fixtures-part2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Symfony2 CLI</title>
		<link>http://inchoo.net/tools-frameworks/symfony2-cli/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony2-cli/#comments</comments>
		<pubDate>Thu, 28 Jul 2011 07:13:49 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Symfony 2]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=10452</guid>
		<description><![CDATA[As someone of you know there is pretty good feature made in Symfony2 that is worth to mention: Console interface with commands that make our life easier to generate different &#8230;]]></description>
			<content:encoded><![CDATA[<p>As someone of you know there is pretty good feature made in Symfony2 that is worth to mention: Console interface with commands that make our life easier to generate different sort of things in our Symfony2 application and execute many useful commands with Doctrine etc.<span id="more-10452"></span></p>
<p>If you want to make some custom feature in your project and that feature is not supposed to be inside your project&#8217;s user interface, than the console commands are right thing for you.</p>
<p>For example, I build some importers from another database to main project&#8217;s database.</p>
<p>It was logically to me that I should use console for importing and not UI where every user can mess up with importer.</p>
<p>To make custom command for Symfony2 CLI, first make new folder inside your bundle called &#8216;command&#8217;.</p>
<p>Inside of that folder we will be creating for each command one php class.<br />
Basic command looks like this:</p>
<pre class="brush: php; title: ; notranslate">
&lt; ?php
namespace Surgeworks\AdminBundle\Command;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ImportCommand extends ContainerAwareCommand {

protected function configure() {

 $this-&gt;setName('importer:import')
      -&gt;setDescription('Import sqllite database into main DOH database')
      -&gt;addArgument('application', InputArgument::REQUIRED, 'What application database you want to import? prayer');
    }

protected function execute(InputInterface $input, OutputInterface $output) {
        $app = $input-&gt;getArgument('application');

        $dialog = $this-&gt;getHelperSet()-&gt;get('dialog');
        $name = $dialog-&gt;ask($output, 'Enter admin username for importing:', '');
        if ($name != 'admin') {
            die('You are not admin! Can\'t let you ruin the database! Sorry...' . &quot;\n&quot;);
        }

        switch ($app) {
            case 'prayers':
                $output-&gt;writeln('Importing &gt;&gt; prayers database ...');
                $this-&gt;ImportPrayers($input, $output);
                break;

            default:
                $output-&gt;writeln('Unknown application name. Please insert one of applications for import');
                break;
        }

    }
</pre>
<p>It is not complicated to make own custom command and make it work.<br />
You just have to write methods what you want to do. Without worry, you can work with database from inside class this way:</p>
<pre class="brush: php; title: ; notranslate">
        //..
        //get em for new tables and entities
        //We may have more entity managers defined in configuration file, so,
        //when calling entity manager write parameter with connection name to get right connection
        $em = $this-&gt;getContainer()-&gt;get('doctrine')-&gt;getEntityManager('default');
        //get connection with sqlite database
        $conn = $this-&gt;getContainer()-&gt;get('doctrine.dbal.sqlite_connection');
        //..
</pre>
<p>After that you just have to open you console and run command from there … <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony2-cli/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>TWIG with WordPress part1</title>
		<link>http://inchoo.net/wordpress/twig-with-wordpress-part1/</link>
		<comments>http://inchoo.net/wordpress/twig-with-wordpress-part1/#comments</comments>
		<pubDate>Tue, 28 Jun 2011 08:33:22 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Tools]]></category>
		<category><![CDATA[Wordpress]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[extension]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[template]]></category>
		<category><![CDATA[theme]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[twig]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9949</guid>
		<description><![CDATA[Making TWIG autoload from WP plugin Maybe someone will say: this is a crazy idea. Why would someone want to do that? Maybe it really is crazy, but I would &#8230;]]></description>
			<content:encoded><![CDATA[<p><strong>Making TWIG autoload from WP plugin</strong></p>
<p><em>Maybe someone will say: this is a crazy idea. Why would someone want to do that?<br />
Maybe it really is crazy, but I would say: why not?<span id="more-9949"></span></em></p>
<p>What is TWIG? TWIG is new generation php templating engine made by Sensio Labs. It is used in their new project Symfony2 as main templating engine provided with framework.<br />
As <a title="TWIG project" href="http://www.twig-project.org/" target="_blank">official page </a> says:</p>
<p><em><strong>Fast:</strong> Twig compiles templates down to plain optimized PHP code. The overhead compared to regular PHP code was reduced to the very minimum.</em><br />
<em> <strong>Secure:</strong> Twig has a sandbox mode to evaluate untrusted template code. This allows Twig to be used as a template language for applications where users may modify the template design.</em><br />
<em> <strong>Flexible:</strong> Twig is powered by a flexible lexer and parser. This allows the developer to define its own custom tags and filters, and create its own DSL.</em><br />
It is not necessary to explain in detail why will someone (me) want to use that as wordpress templating engine, but one of the main reasons is that I want to rewrite some messed up php template for WP to better code organized one, and at the and I want it to be with cleaner code as possible.<br />
I don&#8217;t like very much when is necessary to mix up php tags and functions inside HTML code to make it work.<br />
After some thinking about TWIG and how to implement it in my WP installation I got idea:<br />
I will make plug in for WP that will provide all necessary stuff to start using TWIG with WP.</p>
<p>First I created the plugin folder named wp_twig_engine.I put folder named &#8216;<em>lib</em>&#8216; downloaded from<a title="TWIG project site" href="http://www.twig-project.org/" target="_blank"> twig-project site </a> in there. So I had the twig library almost prepared for using.<br />
Now I had to find some appropriate wordpress hook to inject my code into wordpress application logic. After some investigating and testing, I found that it will be possible to use the &#8216;<em>init</em>&#8216; hook and register autoloaders for TWIG library and my custom class in the same function, so I can reach my code from inside template folder later.</p>
<p>Main plugin file: wp-twig.php</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

/*
  Plugin Name: WordPress Twig templating engine
  Version: 1.0
  Plugin URI: http://inchoo.net
  Description: Engine for creating twig templates for wordpress
  Author: Darko Goleš
  Author URI: http://inchoo.net/author/darko.goles/
 */
//Main twig library autoloader file
require_once dirname(__FILE__) . '/lib/Twig/Autoloader.php';
//My custom class made, I also want it to be autoloaded
require_once dirname(__FILE__) . '/Wp_TwigEngine.php';

function twigAutoLoad() {

    Twig_Autoloader::register();
    Wp_TwigEngine_Autoloader::register();
}

add_action('init', 'twigAutoLoad');
?&gt;
</pre>
<p>Just to show you how to autoload my custom class with that (of course I got idea from original twig autoloader and just changed the code to fit my needs:</p>
<pre class="brush: php; title: ; notranslate">

&lt;?php
/*
Wp_TwigEngine.php
  Author: Darko Goleš
  Author URI: http://inchoo.net/author/darko.goles/
*/
class Wp_TwigEngine_Autoloader {

    static public function register() {
        ini_set('unserialize_callback_func', 'spl_autoload_call');
        spl_autoload_register(array(new self, 'autoload'));
    }

    static public function autoload($class) {
        if (0 !== strpos($class, 'Wp_TwigEngine')) {
            return;
        }

        if (file_exists($file = dirname(__FILE__) . '/../' . str_replace(array('_', &quot;&#92;&#48;&quot;), array('/', ''), $class) . '.php')) {
            echo($file);
            exit;
            require $file;
        }
    }

}
</pre>
<p>And that&#8217;s it from the plugin side for now. Just have to implement it in the template folder. That is additional theme for another article. <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/wordpress/twig-with-wordpress-part1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Symfony2 &#8211; Internal server error 500</title>
		<link>http://inchoo.net/tools-frameworks/symfony2-error-500/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony2-error-500/#comments</comments>
		<pubDate>Tue, 28 Jun 2011 08:04:15 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Symfony 2]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9929</guid>
		<description><![CDATA[Did you ever had problems with Internal server error 500 with symfony2? I did few days ago. When I open my web application in development mode (http://mysymfony2url/app_dev.php/something) It works OK, &#8230;]]></description>
			<content:encoded><![CDATA[<p>Did you ever had problems with Internal server error 500 with symfony2? I did few days ago. When I open my web application in development mode (http://mysymfony2url/app_dev.php/something) It works OK, but when I tried to open it in &#8216;production&#8217;  mode I always got &#8216;Internal server error 500&#8242; response, so I decided to look at error.log inside my localhost to see what is happening.<br />
Here is what I saw there:<span id="more-9929"></span></p>
<pre class="brush: php; title: ; notranslate">
[Wed Jun 15 15:22:44 2011] [error] [client 127.0.0.1] client denied by server configuration: C:/WampDeveloper/Websites/cea.local/webroot/app/
[Wed Jun 15 15:22:44 2011] [error] [client 127.0.0.1] client denied by server configuration: C:/WampDeveloper/Websites/cea.local/webroot/bin/
[Wed Jun 15 15:22:44 2011] [error] [client 127.0.0.1] client denied by server configuration: C:/WampDeveloper/Websites/cea.local/webroot/src/
[Thu Jun 16 08:11:56 2011] [error] [client 127.0.0.1] client denied by server configuration: C:/WampDeveloper/Websites/cea.local/webroot/app/
[Thu Jun 16 08:11:56 2011] [error] [client 127.0.0.1] client denied by server configuration: C:/WampDeveloper/Websites/cea.local/webroot/bin/
[Thu Jun 16 08:11:56 2011] [error] [client 127.0.0.1] client denied by server configuration: C:/WampDeveloper/Websites/cea.local/webroot/src/
</pre>
<p>There was not enough informations for me to figure out what is wrong with my application.<br />
In development mode it is working just fine, but when I start it in regular (production) mode it returns  an error. I tried to delete cache, refresh page, looked in my config files, but I found nothing.</p>
<p>Then I remembered that recently I upgraded to Symfony2 beta4 version and whole my files except configuration files was overwritten with new ones.</p>
<p><strong>Solution: DO NOT forget to register your bundle namespace inside &#8216;autoload.php&#8217; like I did, otherwise, you can spend few hours to find what is going on without practical solution.<br />
</strong><br />
When I added my namespace inside &#8216;autoload.php&#8217; then  everything was OK.</p>
<pre class="brush: php; title: ; notranslate">

&lt;!--?php use Symfony\Component\ClassLoader\UniversalClassLoader; $loader = new UniversalClassLoader(); $loader---&gt;registerNamespaces(array(
'Symfony'          =&gt; array(__DIR__.'/../vendor/symfony/src', __DIR__.'/../vendor/bundles'),
'Sensio'           =&gt; __DIR__.'/../vendor/bundles',
'JMS'              =&gt; __DIR__.'/../vendor/bundles',
'Doctrine\\Common' =&gt; __DIR__.'/../vendor/doctrine-common/lib',
'Doctrine\\DBAL'   =&gt; __DIR__.'/../vendor/doctrine-dbal/lib',
'Doctrine'         =&gt; __DIR__.'/../vendor/doctrine/lib',
'Monolog'          =&gt; __DIR__.'/../vendor/monolog/src',
'Assetic'          =&gt; __DIR__.'/../vendor/assetic/src',
'Metadata'         =&gt; __DIR__.'/../vendor/metadata/src',
'Surgeworks'         =&gt; __DIR__.'/../src',
));
//...
</pre>
<p>I hope that this post will be helpful to someone with the same problems. <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony2-error-500/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Symfony2 Doctrine2 transactions</title>
		<link>http://inchoo.net/tools-frameworks/doctrine2-symfony2-transactions/</link>
		<comments>http://inchoo.net/tools-frameworks/doctrine2-symfony2-transactions/#comments</comments>
		<pubDate>Tue, 31 May 2011 08:38:40 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[Database transactions]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Doctrine2]]></category>
		<category><![CDATA[Doctrine2 transactions]]></category>
		<category><![CDATA[Symfony 2]]></category>
		<category><![CDATA[symfony2]]></category>
		<category><![CDATA[Transactions]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9687</guid>
		<description><![CDATA[Like everything else, using transactions in Symfony2 is easy task. I had a case that I had to use transactions to make sure that everything or none is saved to &#8230;]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">Like everything else, using transactions in Symfony2 is easy task.<br />
I had a case that I had to use transactions to make sure that everything or none is saved to database, because I didn&#8217;t wand anything to break at the half way and leave data unsaved.<span id="more-9687"></span>There are two basic different ways to use transactions with Doctrine 2. In official documentation there is one approach suggested for transactions, but if you find necessary like I did, use second one. The important thing is not to forget rollback in your code if you are using approach that is not suggested.</p>
<p style="text-align: justify;">Example from Doctrine2 official documentation:</p>
<pre class="brush: php; title: ; notranslate">

&lt;?php
// $em instanceof EntityManager
$em-&gt;transactional(function($em) {
    //... do some work
    $user = new User;
    $user-&gt;setName('George');
    $em-&gt;persist($user);
});
</pre>
<p style="text-align: justify;">I found this approach inconvenient for my code because variables defined outside transactional function are not accessible directly and I had many variables defined in my controller action and didn&#8217;t want to refractor all the code. Because of that I used the second possibility in my code:</p>
<pre class="brush: php; title: ; notranslate">

    /**
     * @Route(&quot;/admin/tags/ajax_save_new_tag&quot;, name=&quot;_admin_tags_ajax_save_new_tag&quot;)
     */
    public function ajaxSaveNewTagAction() {

        $request = $this-&gt;get('request');
        $isAjax = $request-&gt;isXmlHttpRequest();

        /* BEGIN If is ajax call... */
        if ($isAjax == true) {

            $em = $this-&gt;get('doctrine.orm.entity_manager');
            $user = $this-&gt;container-&gt;get('security.context')-&gt;getToken()-&gt;getUser();
            $userId = $user-&gt;getId();
            $localizations = '';
            $tagname = '';

            if (isset($_POST['localization']))
                $localizations = $_POST['localization'];

            if (isset($_POST['tag']['tag_name']))
                $tagname = $_POST['tag']['tag_name'];

            $tag = new \Surgeworks\AdminBundle\Entity\Tag();
            $tag-&gt;setTagName($tagname);

            $tag-&gt;setUserId($userId);

            $q = $em-&gt;createQuery(&quot;select max(a.sort_order) from Surgeworks\AdminBundle\Entity\Tag a&quot;);
            $maxorder = $q-&gt;getSingleScalarResult();

            if (null === $maxorder) {
                $maxorder = 0;
            }
            $tmp = $maxorder - ($maxorder % 10);
            $tag-&gt;setSortOrder($tmp + 10);

            $validator = $this-&gt;container-&gt;get('validator');
            $errorList = $validator-&gt;validate($tag);

            $msg = &quot;&quot;;
            if (count($errorList) &gt; 0) {
                foreach ($errorList as $err) {
                    $msg.= $err-&gt;getMessage() . &quot;\n&quot;;
                }
                return new Response($msg, '400');
            }

            /*             * ******** BEGIN TRANSACTION ******** */
            $em-&gt;getConnection()-&gt;beginTransaction();
            try {

                $em-&gt;persist($tag);
                $em-&gt;flush();

                if (!empty($localizations)) {
                    foreach ($localizations as $langsymbol =&gt; $tagname) {

                        $loc = new \Surgeworks\AdminBundle\Entity\TagLocalization();
                        $loc-&gt;setTagId($tag-&gt;getId());
                        $loc-&gt;setLanguageSymbol($langsymbol);
                        $loc-&gt;setTagTitle($tagname[0]);
                        $loc-&gt;setUserId($userId);

                        $errorList = $validator-&gt;validate($loc);

                        $msg = &quot;&quot;;
                        if (count($errorList) &gt; 0) {
                            foreach ($errorList as $err) {
                                $msg.= $err-&gt;getMessage() . &quot;\n&quot;;
                            }
                            return new Response($msg, '400');
                        }

                        $em-&gt;persist($loc);
                        $em-&gt;flush();
                    }
                }

                $em-&gt;getConnection()-&gt;commit();
                $msg = &quot;Tag saved successfully!&quot;;
                $code = &quot;OK&quot;;
            } catch (\Exception $e) {

                $em-&gt;getConnection()-&gt;rollback();
                $em-&gt;close();
                throw $e;
            }

            //get languages list for select box
            $languages = $em-&gt;getRepository('Surgeworks\AdminBundle\Entity\Language')-&gt;findAll();

            $langsarr = array();

            foreach ($languages as $val) {

                array_push($langsarr, array('langsymbol' =&gt; $val-&gt;getLanguageSymbol(), 'langname' =&gt; $val-&gt;getLanguageName()));
            }

            $response = new Response(json_encode(array('langlist' =&gt; $langsarr)), '200');
            $response-&gt;headers-&gt;set('Content-Type', 'application/json');

            return $response;
        }
        //If not ajax call
        return new Response('Silence is golden');
    }
</pre>
<p>As I sad: don&#8217;t forget to write rollback when you are using this approach. <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/doctrine2-symfony2-transactions/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Symfony2 Forms &#8211; Entity field type</title>
		<link>http://inchoo.net/tools-frameworks/symfony2-entity-field-type/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony2-entity-field-type/#comments</comments>
		<pubDate>Tue, 31 May 2011 06:59:32 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Entity type]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[Forms]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Symfony 2]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9674</guid>
		<description><![CDATA[NOTE: Tested on Symfony2 Beta3. Might not work on later releases! Symfony2 offers many prebuilt field types for using when creating forms. The one of them I found interesting is &#8230;]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;"><strong>NOTE: Tested on Symfony2 Beta3. Might not work on later releases!</strong></p>
<p style="text-align: justify;">Symfony2 offers many prebuilt field types for using when creating forms. The one of them I found interesting is &#8216;EntityType&#8217;. <a title="Entity field type" href="http://symfony.com/doc/current/reference/forms/types/entity.html" target="_blank">There are just basic documentation about that</a>.</p>
<p style="text-align: justify;">I had one case recently that I had to use Entity field type for creating form, but except using it in simple way like documented I wanted to use it on little more advanced way.<span id="more-9674"></span>I have table in database called statuses that have basic filelds like:</p>
<p style="text-align: justify;">id (int11), status_name (varchar 50), status_type (varchar 20). I defined 3 basic statuses that will be used for all items I have to describe their state:</p>
<p style="text-align: justify;"><em>draft, live, deleted</em></p>
<p style="text-align: justify;">but, also I have more statuses defined that is for other purposes.</p>
<p style="text-align: justify;">Because of that I defined these three types to have status type &#8216;<em>basic</em>&#8216; and I wanted to create form with select box, but only <em>filter and show these three statuses and ignore others</em>.</p>
<p style="text-align: justify;">For that purpose, I used &#8216;<em>Entity</em>&#8216; field type, but I don&#8217;t want to pull all statuses from database, but only those three that have defined status_type: &#8216;<em>basic</em>&#8216;.</p>
<p>Here is the code:</p>
<pre class="brush: php; title: ; notranslate">

&lt;?php
//Surgeworks/AdminBundle/Forms/ItemForm.php
namespace Surgeworks\AdminBundle\Forms;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class Itemform extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {

        $builder-&gt;add('item_type','entity', array('class'=&gt;'Surgeworks\AdminBundle\Entity\ItemType', 'property'=&gt;'item_type_name', ));
        $builder-&gt;add('item_status','entity', array('class'=&gt;'Surgeworks\AdminBundle\Entity\Status', 'property'=&gt;'status_name',
            'query_builder' =&gt; function (\Surgeworks\AdminBundle\Entity\StatusRepository $repository)
            {return $repository-&gt;createQueryBuilder('s')-&gt;where('s.status_type = ?1')-&gt;setParameter(1, 'basic')-&gt;add('orderBy', 's.sort_order ASC');} ));
        $builder-&gt;add('item_name');

    }
    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' =&gt; 'Surgeworks\AdminBundle\Entity\Item',
        );
    }
}
</pre>
<p>when we ignore rest of the code here is how to use it inside function:</p>
<pre class="brush: php; title: ; notranslate">
        $builder-&gt;add('item_status',
                      'entity',
                       array(
                             'class'=&gt;'Surgeworks\AdminBundle\Entity\Status',
                             'property'=&gt;'status_name',
                             'query_builder' =&gt; function (\Surgeworks\AdminBundle\Entity\StatusRepository $repository)
                             {
                                 return $repository-&gt;createQueryBuilder('s')
                                        -&gt;where('s.status_type = ?1')
                                        -&gt;setParameter(1, 'basic')
                                        -&gt;add('orderBy', 's.sort_order ASC');
                             }
                            )
                      );
</pre>
<p>This is basic example how to use query_builder option with entity field type for creating forms.I hope you enjoyed the post and found it helpful.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony2-entity-field-type/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Symfony2 from beta1 to beta2</title>
		<link>http://inchoo.net/tools-frameworks/symfony2-beta1-beta2/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony2-beta1-beta2/#comments</comments>
		<pubDate>Tue, 24 May 2011 11:20:03 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Symfony 2]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9399</guid>
		<description><![CDATA[Today I had to migrate existing project from Symfony2 Beta 1 version to Beta2. First I looked at the difference between my config files and new one provided with Beta2.After &#8230;]]></description>
			<content:encoded><![CDATA[<p>Today I had to migrate existing project from Symfony2 Beta 1 version to Beta2.<br />
First I looked at the difference between my config files and new one provided with Beta2.<span id="more-9399"></span>After some minor changes to config files, when I tried to start project in browser to see possible errors, I see not so happy surprise:</p>
<p>Annotation syntax in controllers and models are no longer working for me this way.<br />
After some digging into code and official Symfony2 documentation here is what I found:</p>
<p>1. In controllers, instead of:</p>
<pre class="brush: php; title: ; notranslate">

    /**
     * @extra:Route(&quot;/admin/applications&quot;, name=&quot;_admin_applications&quot;)
     * @extra:Template()
     */
</pre>
<p>It has to be written like that:</p>
<pre class="brush: php; title: ; notranslate">

    /**
     * @Route(&quot;/admin/applications&quot;, name=&quot;_admin_applications&quot;)
     * @Template()
     */
</pre>
<p>2. Don&#8217;t forget to add these two lines on the top of each controller:</p>
<pre class="brush: php; title: ; notranslate">

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
</pre>
<p>3. In entities, instead of:</p>
<pre class="brush: php; title: ; notranslate">

/**
 * @orm:Entity(repositoryClass=&quot;Surgeworks\AdminBundle\Entity\AttributeTypeRepository&quot;)
 * @orm:Table(name=&quot;attribute_types&quot;)
 */
class AttributeType {

    /**
     * @orm:Id
     * @orm:Column(type=&quot;integer&quot;)
     * @orm:GeneratedValue(strategy=&quot;AUTO&quot;)
     */
    protected $id;
</pre>
<p>It should be like:</p>
<pre class="brush: php; title: ; notranslate">

/**
 * @ORM\Entity(repositoryClass=&quot;Surgeworks\AdminBundle\Entity\AttributeTypeRepository&quot;)
 * @ORM\Table(name=&quot;attribute_types&quot;)
 */
class AttributeType {

    /**
     * @ORM\Id
     * @ORM\Column(type=&quot;integer&quot;)
     * @ORM\GeneratedValue(strategy=&quot;AUTO&quot;)
     */
    protected $id;
</pre>
<p>4. Don&#8217;t forget to add this line on the top of each entity:</p>
<pre class="brush: php; title: ; notranslate">

use Doctrine\ORM\Mapping as ORM;
</pre>
<p>Also I used some annotations like this in my entity:</p>
<pre class="brush: php; title: ; notranslate">

     * @assert:Type(type=&quot;Surgeworks\AdminBundle\Entity\Status&quot;)

    protected $item_status;
</pre>
<p>but, this also is not working anymore, and instead of this it shoul be like this:</p>
<pre class="brush: php; title: ; notranslate">

     * @Assert\Type(type=&quot;Surgeworks\AdminBundle\Entity\Status&quot;)
</pre>
<p>Of course, we should add one more line on the top to get all the thing work:</p>
<pre class="brush: php; title: ; notranslate">

use Symfony\Component\Validator\Constraints as Assert;
</pre>
<p>That was just short tutorial for fast migration from Symfony2 beta1 version to Symfony2 Beta 2 version.</p>
<p>I hope in the future they will not add so many changes in the core framework, because every time new version is out, I have to loose few hours to upgrade. <img src='http://inchoo.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>PS. Don&#8217;t forget to clear all cache before testing.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony2-beta1-beta2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Symfony2 – validation part 1</title>
		<link>http://inchoo.net/tools-frameworks/symfony2-validation-part-1/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony2-validation-part-1/#comments</comments>
		<pubDate>Fri, 20 May 2011 07:59:30 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Symfony 2]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9331</guid>
		<description><![CDATA[NOTE: Tested on Symfony2 Beta1. Might not work on later releases! Few days ago I tried to find validation method for duplicate items in database because I have a table &#8230;]]></description>
			<content:encoded><![CDATA[<p><strong>NOTE: Tested on Symfony2 Beta1. Might not work on later releases!</strong></p>
<p>Few days ago I tried to find validation method for duplicate items in database because I have a table named &#8216;languages&#8217; and need &#8216;language_symbol&#8217; field to be unique.</p>
<p><span id="more-9331"></span></p>
<p>In my entity named Language.php it is written like this:</p>
<pre class="brush: php; title: ; notranslate">
    /**
     * @orm:Column(type=&quot;string&quot;, length=&quot;10&quot;, unique=true)
     */
    protected $language_symbol;

//..
</pre>
<p>I also have a form with field &#8216;language_symbol&#8217; and need to validate for duplicated entry.<br />
Except I can do it with the AJAX, I didn&#8217;t want to and tried to validate with native Symfony2 validation.<br />
Here is how I did this:<br />
I added a validation function inside Entity: &#8216;Language.php&#8217;:</p>
<pre class="brush: php; title: ; notranslate">
//Surgeworks/AdminBundle/Entity/Language.php
//..
    public function isSymbolDuplicated()
    {
$q = $this-&gt;em-&gt;createQuery(&quot;SELECT count(l.id) FROM Surgeworks\AdminBundle\Entity\Language l WHERE (l.language_symbol='&quot; . $this-&gt;language_symbol . &quot;' AND l.id &lt;&gt; '&quot;.$this-&gt;id.&quot;')&quot;);
        $result = $q-&gt;getSingleScalarResult();
        return $result==1?true:false;
    }
//..
</pre>
<p>Also, I have to put variable to pass entity manager reference to my &#8216;Language.php&#8217; class so I could make database calls. <em>I know that it was not maybe the best way to implement that, but it was the fastest way to get it work.</em></p>
<pre class="brush: php; title: ; notranslate">
/**
 * @orm:Entity(repositoryClass=&quot;Surgeworks\AdminBundle\Entity\LanguageRepository&quot;)
 * @orm:Table(name=&quot;languages&quot;)
 */
class Language{

    /**
     * @orm:Id
     * @orm:Column(type=&quot;integer&quot;)
     * @orm:GeneratedValue(strategy=&quot;AUTO&quot;)
     */
      protected $id;
      protected $em;

    public function setEm($em) {
        $this-&gt;em = $em;
    }
//..
</pre>
<p>After that, in my controller I put this:</p>
<pre class="brush: php; title: ; notranslate">
/**
     * @extra:Route(&quot;/admin/languages/add_new&quot;, name=&quot;_admin_languages_add&quot;)
     * @extra:Template
     */
    public function addAction() {

        $em = $this-&gt;get('doctrine.orm.entity_manager');
        $language = new \Surgeworks\AdminBundle\Entity\Language();
	 //Sst reference to entity manager so it can be used in entity class directly for validation purposes
        $language-&gt;setEm($em);
</pre>
<p>And, here is how my &#8216;validation.yml&#8217; looks like:</p>
<pre class="brush: php; title: ; notranslate">
Surgeworks\AdminBundle\Entity\Language:
    properties:
        language_name:
            - NotBlank: { message: &quot;Language name field can not be empty!&quot; }
            #- NotBlank: ~
        language_symbol:
            - NotBlank: { message: &quot;Language symbol field can not be empty!&quot; }
    getters:
        SymbolDuplicated:
            - 'False': { message: &quot;Language symbol must be unique.You entered symbol that already exist in database!&quot; }
</pre>
<p><em><strong>Just one important note: If you look in Symfony2 documentation about true , false validation Constraints you will see that in above source I put the word true in single quotes. If you do not it will generate error, so I thing that it should be properly written in official Symfony2 documentation page which is not the case now.</strong></em><br />
That&#8217;s it about validation for now. I am sure that I will make more posts about it in the near future.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony2-validation-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Symfony 2 paginator &#8211; improved version</title>
		<link>http://inchoo.net/tools-frameworks/paginator-symfony2-beta/</link>
		<comments>http://inchoo.net/tools-frameworks/paginator-symfony2-beta/#comments</comments>
		<pubDate>Fri, 20 May 2011 07:03:17 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[extension]]></category>
		<category><![CDATA[pagination]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[symfony2]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9313</guid>
		<description><![CDATA[NOTE: Tested on Symfony2 Beta3. Might not work on later releases! After some comments on forums about my earlier post: “Custom Pagination in Symfony 2” that was made on Symfony2 &#8230;]]></description>
			<content:encoded><![CDATA[<p><strong>NOTE: Tested on Symfony2 Beta3. Might not work on later releases! </strong></p>
<p>After some comments on forums about my earlier post:<br />
<a href="http://inchoo.net/tools-frameworks/symfony-2-pagination/">“Custom Pagination in Symfony 2”</a> that was made on Symfony2 version: PR 12,<br />
I decided to make some changes in the source code and give it available for download.</p>
<p>Basic structure of paginator is similar to latest post, but improvements are made by removing HTML stuff from controller, so paginator is rendered by twig template and not  inside class on the fly.<span id="more-9313"></span>There are some more things that could be improved, for example:<br />
I didn&#8217;t add some forward – backward arrow – links into displayed paginator and also didn&#8217;t limit number of links that will be shown, and I do not intend to.</p>
<p><em>If anybody  thinks that it has to be improved more, fixed or something else, feel free to do it yourself.</em></p>
<p>Let&#8217;s show how to use it:</p>
<p>First, put class Paginator.php somewhere inside your Bundle. I put it into Helpers folder. Just rename namespace defined inside class to your own.</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
/**
 * Paginator.php
 * Class to generate pagination for items
 *
 * @author Darko Goleš
 * @www.inchoo.net
 */
//Here replace namespace, depends where you put yours :
namespace Surgeworks\AdminBundle\Helpers;
class Paginator {
//..
</pre>
<p>Before using it, just to take a look into the constructor for a moment:</p>
<pre class="brush: php; title: ; notranslate">
//..
    function __construct($itemscount, $currenturl, $options=array(10,20,30,50,100,500)) {
        //set total items count from controller
        $this-&gt;itemscount = $itemscount;
        //get params from request URL
        $this-&gt;getParamsFromRequest();
        //Calculate number of pages total
        $this-&gt;getInternalNumPages();
        //Calculate first shown item on current page
        $this-&gt;calculateOffset();

        $this-&gt;currentUrl = $currenturl;

        $this-&gt;options = $options;
    }
//..&lt;/pre&gt;
&lt;pre&gt;</pre>
<p>Why we looked into the constructor now? To see that there is third, optional argument that takes array of numbers with some predefined values. That is for: “how many items to show” list purpose.<br />
In controller, when you use it, you can define custom values that will be shown in the select list (10, 20, 500). Also, <strong>you may not define &#8216;show All&#8217;</strong> because that is already predefined in the twig template, so as this parameter, <strong>use only array of number</strong>s.</p>
<p>Let&#8217;s take a look how to use it in the controller:</p>
<pre class="brush: php; title: ; notranslate">
    /**
     * @extra:Route(&quot;/admin/languages&quot;, name=&quot;_admin_languages&quot;)
     * @extra:Template()
     */
    public function indexAction() {

        //order of items from database
        $order_by = array();
        //get Entity manager instance
        $em = $this-&gt;get('doctrine.orm.entity_manager');
        //get repository for class 'Language' : LanguageRepository.php
        $repository = $em-&gt;getRepository('Surgeworks\AdminBundle\Entity\Language');
        //get count of languages for using with Paginator class
        //Using custom made database query function in LanguageRepository class
        $languagesCount = $repository-&gt;getLanguagesCount();
        //When creating new paginator object it takes care for pages and items
        //organization based on numbers of items from database and limit variable in $_GET
        $paginator = new Paginator($languagesCount, $this-&gt;generateUrl('_admin_languages'));
        //If we have POST variable defined, than it is defined order of items
        //from inside form (clicking on sorting column for example)
        if ('POST' === $this-&gt;get('request')-&gt;getMethod()) {
            $order_by = array($_POST['filter_order'] =&gt; $_POST['filter_order_Dir']);
            $sort_direction = $_POST['filter_order_Dir'] == 'asc' ? 'desc' : 'asc';

            $this-&gt;get('session')-&gt;set('lang_list_order_by', $order_by);
            $this-&gt;get('session')-&gt;set('lang_list_sort_dir', $sort_direction);
        } else {

            if ($this-&gt;get('session')-&gt;get('lang_list_order_by') != null) {
                $order_by = $this-&gt;get('session')-&gt;get('lang_list_order_by');
            } else {
                $order_by = array('sort_order' =&gt; 'asc', 'id' =&gt; 'asc');
            }
            if ($this-&gt;get('session')-&gt;get('lang_list_sort_dir') != null) {
                $sort_direction = $this-&gt;get('session')-&gt;get('lang_list_sort_dir');
            } else {
                $sort_direction = 'desc';
            }
        }
        //To fill $languages for forwarding it to the template, we first call database function
        //with $offset and $limit to get items we wanted
        $languages = $repository-&gt;getLanguagesListWithPagination($order_by, $paginator-&gt;getOffset(), $paginator-&gt;getLimit());
        //Finally - return array to templating engine for displaying data.
        return array('languages' =&gt; $languages, 'sort_dir' =&gt; $sort_direction, 'paginator' =&gt; $paginator);
    }
</pre>
<p>Of course, you need to make some function in LanguagesRepository  to get count of items for paginator.</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

namespace Surgeworks\AdminBundle\Entity;

use Doctrine\ORM\EntityRepository;

class LanguageRepository extends EntityRepository {

    public function getLanguagesListWithPagination($order_by = array(), $offset = 0, $limit = 0) {
        //Create query builder for languages table
        $qb = $this-&gt;createQueryBuilder('l');

        //Show all if offset and limit not set, also show all when limit is 0
        if ((isset($offset)) &amp;&amp; (isset($limit))) {
            if ($limit &gt; 0) {
                $qb-&gt;setFirstResult($offset);
                $qb-&gt;setMaxResults($limit);
            }
            //else we want to display all items on one page
        }
        //Adding defined sorting parameters from variable into query
        foreach ($order_by as $key =&gt; $value) {
            $qb-&gt;add('orderBy', 'l.' . $key . ' ' . $value);
        }
        //Get our query
        $q = $qb-&gt;getQuery();
        //Return result
        return $q-&gt;getResult();
    }

    public function getLanguagesCount() {
        //Create query builder for languages table
        $qb = $this-&gt;createQueryBuilder('l');
        //Add Count expression to query
        $qb-&gt;add('select', $qb-&gt;expr()-&gt;count('l'));
        //Get our query
        $q = $qb-&gt;getQuery();
        //Return number of items
        return $q-&gt;getSingleScalarResult();
    }
//..
</pre>
<p>Don&#8217;t forget to add this repository class to Entity class:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

namespace Surgeworks\AdminBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @orm:Entity(repositoryClass=&quot;Surgeworks\AdminBundle\Entity\LanguageRepository&quot;)
 * @orm:Table(name=&quot;languages&quot;)
 */
class Language{
//..
</pre>
<p>After all of that is done, put paginator.html.twig inside Resources/views/Somewhere  (I put in Resources/views/Global/ folder).<br />
Let&#8217;s render it in twig template:</p>
<pre class="brush: php; title: ; notranslate">
 {% include 'SurgeworksAdminBundle:Global:paginator.html.twig' %}
</pre>
<p>That&#8217;s all about paginator for now. <a href="http://inchoo.net/wp-content/uploads/2011/05/Paginator.zip">Here you can download Symfony2 paginator files</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/paginator-symfony2-beta/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Symfony 2 forms validation</title>
		<link>http://inchoo.net/tools-frameworks/symfony2-validation-forms/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony2-validation-forms/#comments</comments>
		<pubDate>Thu, 28 Apr 2011 07:31:38 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Forms]]></category>
		<category><![CDATA[project]]></category>
		<category><![CDATA[Symfony 2]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9172</guid>
		<description><![CDATA[NOTE: Tested on Symfony2 PR12. Might not work on later releases! To continue previous article when writing about forms in Symfony 2, now it&#8217;s time to write something about forms &#8230;]]></description>
			<content:encoded><![CDATA[<p><strong>NOTE: Tested on Symfony2 PR12. Might not work on later releases!</strong></p>
<p>To continue previous article when writing about forms in Symfony 2, now it&#8217;s time to write something about forms validation.<span id="more-9172"></span></p>
<p>In <a href="http://inchoo.net/tools/symfony-2-forms/">the previous article</a>, we created a form like this:</p>
<pre class="brush: php; title: ; notranslate">
&amp;lt;?php
//Surgeworks/AdminBundle/Forms/LanguageForm.php

namespace Surgeworks\AdminBundle\Forms;

use Symfony\Component\Form\Form;
use Symfony\Component\Form\TextField;
use Symfony\Component\Form\HiddenField;

//form for Create and update information about languages
class LanguageForm extends Form{

    protected function configure() {
        $this-&amp;gt;add(new TextField('language_name',  array('max_length'=&amp;gt;50, 'required' =&amp;gt; true)));
        $this-&amp;gt;add(new TextField('language_symbol',  array('max_length'=&amp;gt;10, 'required' =&amp;gt; true)));
        $this-&amp;gt;addOption('name', 'adminForm');
    }
}
</pre>
<p>Now we need to validate these two fields for entering new record into database when form is submitted. This is done by creating new file called &#8216;validation.yml&#8217;. Of course you have more possibility to create that file like the other configuration files either in xml or plain php. But for purposes of article let&#8217;s make it in yaml.</p>
<pre class="brush: php; title: ; notranslate">
//Surgeworks/AdminBundle/Resources/config/validation.yml
Surgeworks\AdminBundle\Entity\Language:  //enter name of your entity to validate against
    properties:
        language_name:
            - NotBlank: { message: &amp;quot;Language name field can not be empty!&amp;quot; }
        language_symbol:
            - NotBlank: { message: &amp;quot;Language symbol field can not be empty!&amp;quot; }
</pre>
<p>After all &#8216;hard work&#8217; is done, let&#8217;s tell to our controller action to validate that form:<br />
(Using same controller from last article)</p>
<pre class="brush: php; title: ; notranslate">
//…
    public function addAction() {
	//Creating form's instance
        $form = LanguageForm::create($this-&amp;gt;get('form.context'), 'adminForm');
//...

//Binding form to entity...
$form-&amp;gt;bind($request, $language);

//...

	//If our form passes validation
            if ($form-&amp;gt;isValid()) {

	    //We already made bind to entity, just need to save data into database
                $em-&amp;gt;persist($language);
                $em-&amp;gt;flush();
	 //Now it's time to redirect to some url when data is saved...
                return new RedirectResponse($this-&amp;gt;generateUrl('_admin_languages'));
}

//...
</pre>
<p>Of course, until now, I didn&#8217;t mention:<br />
what about AJAX?<br />
If we send form&#8217;s data in some AJAX form, can we validate this way?</p>
<p>There is also solution for AJAX too:</p>
<p>First we need to determine type of request received in our controller:</p>
<pre class="brush: php; title: ; notranslate">
//...

$request = $this-&amp;gt;get('Request');
            $isAjax = $request-&amp;gt;isXmlHttpRequest();//if true – then AJAX is used

//..
</pre>
<p>Now when we know is that AJAX request we could write AJAX validation handling part:</p>
<pre class="brush: php; title: ; notranslate">
//Our controller file

/* BEGIN If is ajax call... */
            if ($isAjax == true) {

                $validator = $this-&amp;gt;container-&amp;gt;get('validator');
                $errorList = $validator-&amp;gt;validate($language);

                $msg = &amp;quot;&amp;quot;;
                if (count($errorList) &amp;gt; 0) {
                    foreach ($errorList as $err) {
                        $msg.= $err-&amp;gt;getMessage() . &amp;quot;\n&amp;quot;;
                    }
                    $code = &amp;quot;ERR&amp;quot;;
                } else {
                    $em-&amp;gt;persist($language);
                    $em-&amp;gt;flush();
                    $msg = &amp;quot;Language saved successfully!&amp;quot;;
                    $code = &amp;quot;OK&amp;quot;;
                }
                $response = new Response(json_encode(array('code' =&amp;gt; $code, 'msg' =&amp;gt; $msg)));
                $response-&amp;gt;headers-&amp;gt;set('Content-Type', 'application/json');

                return $response;
            }
</pre>
<p>Let me explain what I did here: First of all, we get validator service, and then get list of errors if any by validating our Entity instance with validator service. (variable &#8216;$language&#8217; is our entity instance).</p>
<p>Then we loop through possible errors and adding error message to variable $msg.  Also, I predefined two possible response messages for AJAX response: “ERR” and “OK” and I am handling it in my AJAX function on the client side. So, when return $code and $message are defined depends if we have errors or not, let&#8217;s just return response to our AJAX function in JSON form for easy processing with our Javascript on client side. (We shouldn&#8217;t forget to set response headers to application/json).</p>
<p>To all of these get work, we need to do one more thing:</p>
<pre class="brush: php; title: ; notranslate">
framework:
    validation:    { enabled: true, annotations: false }
</pre>
<p>Add, or check if exists this into your main config.yml file of application and also make sure if you are using validation this way, that annotations are false. If you are using annotations for validation, don&#8217;t forget to set it to true here.</p>
<p>This is all for now. BTW, yesterday I looked in official documentation and find out that will be some new ways, let&#8217;s say different ways for using forms in project in first beta release of Symfony 2, and when that release is available to me, I will write more about forms in new way of handling it.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony2-validation-forms/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Symfony 2 Form</title>
		<link>http://inchoo.net/tools-frameworks/symfony-2-forms/</link>
		<comments>http://inchoo.net/tools-frameworks/symfony-2-forms/#comments</comments>
		<pubDate>Fri, 22 Apr 2011 13:24:07 +0000</pubDate>
		<dc:creator>Darko Goles</dc:creator>
				<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tools & Frameworks]]></category>
		<category><![CDATA[cms]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[Symfony 2]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://inchoo.net/?p=9153</guid>
		<description><![CDATA[NOTE: Tested on Symfony2 PR12. Might not work on later releases! If you want to use forms in Symfony 2 project there is already prepared system for that. First in &#8230;]]></description>
			<content:encoded><![CDATA[<p><strong>NOTE: Tested on Symfony2 PR12. Might not work on later releases!</strong></p>
<p>If you want to use forms in Symfony 2 project there is already prepared system for that.</p>
<p>First in &#8216;Yourname/SomethingBundle/Forms&#8217; folder create class like this:<span id="more-9153"></span></p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

namespace Surgeworks\AdminBundle\Forms;

use Symfony\Component\Form\Form;
use Symfony\Component\Form\TextField;
use Symfony\Component\Form\HiddenField;

//form for Create and update information about languages
class LanguageForm extends Form{

    protected function configure() {
        $this-&gt;add(new TextField('language_name',  array('max_length'=&gt;50, 'required' =&gt; true)));
        $this-&gt;add(new TextField('language_symbol',  array('max_length'=&gt;10, 'required' =&gt; true)));
        $this-&gt;addOption('name', 'adminForm');
    }
}
</pre>
<p>then the form is ready for using inside controller:</p>
<pre class="brush: php; title: ; notranslate">
    /**
     * @extra:Route(&quot;/admin/languages/add_new&quot;, name=&quot;_admin_languages_add&quot;)
     * @extra:Template
     */
    public function addAction() {

        $form = LanguageForm::create($this-&gt;get('form.context'), 'adminForm');
</pre>
<p>After that in the same controller action bind form to your existing Entity:</p>
<pre class="brush: php; title: ; notranslate">
$request = $this-&gt;get('Request');
            $form-&gt;bind($request, $language);
</pre>
<p>Attention:  make sure that form field names is same like your Entity properties names!</p>
<p>One little tip: When field names in Entity class contain _ (underscore) character, make sure to remove that character in setter and getter function names, for example:</p>
<pre class="brush: php; title: ; notranslate">
//contains underscore character like fieldname in database
protected $status_id;
//theese methods must be without that character
    public function getStatusId() {
        return $this-&gt;status_id;
    }
    public function setStatusId($status_id) {
        $this-&gt;status_id = $status_id;
    }
</pre>
<p>For displaying form in the template there are several ways, end one of them is:</p>
<pre class="brush: php; title: ; notranslate">
        &lt;form action=&quot;#&quot; method=&quot;post&quot; id=&quot;adminForm&quot; enctype=&quot;application/x-www-form-urlencoded&quot;&gt;
    {{ form_errors(form) }}
    {% for field in form %}
        {% if not field.ishidden %}
            &lt;div class=&quot;formitem&quot;&gt;
            {{ form_errors(field) }}
            {{ form_label(field) }}
            {{ form_field(field) }}
            &lt;/div&gt;
        {% endif %}
    {% endfor %}
{{ form_hidden(form) }}
                &lt;input type=&quot;submit&quot; value=&quot;submit&quot;/&gt;
        &lt;/form&gt;
</pre>
<p>In the next article of Symfony 2 series I will write about validating form&#8217;s data in Symfony 2.</p>
]]></content:encoded>
			<wfw:commentRss>http://inchoo.net/tools-frameworks/symfony-2-forms/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

