<?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>Alexander Schnitzler</title>
	<atom:link href="http://www.alexanderschnitzler.de/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.alexanderschnitzler.de</link>
	<description>passionate web developer</description>
	<lastBuildDate>Sun, 29 Jan 2012 14:09:34 +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>Building frontend URIs in backend modules with Extbase</title>
		<link>http://www.alexanderschnitzler.de/2012/01/building-frontend-uris-in-backend-modules-with-extbase/</link>
		<comments>http://www.alexanderschnitzler.de/2012/01/building-frontend-uris-in-backend-modules-with-extbase/#comments</comments>
		<pubDate>Sun, 29 Jan 2012 14:09:34 +0000</pubDate>
		<dc:creator>Alexander</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.alexanderschnitzler.de/?p=354</guid>
		<description><![CDATA[Hey guys, quite a few month ago I had a very nice project where I needed to create frontend urls in a TYPO3 backend module. And I can tell you it&#8217;s not possible using the standard tools extbase comes with. &#8230; <a href="http://www.alexanderschnitzler.de/2012/01/building-frontend-uris-in-backend-modules-with-extbase/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Hey guys,<br />
quite a few month ago I had a very nice project where I needed to create frontend urls in a TYPO3 backend module. And I can tell you it&#8217;s not possible using the standard tools extbase comes with. But there&#8217;s hope because extbase brings the right tools we just have to change a little bit. Wait, you want to change Extbase itself? No, let&#8217;s say we just adopt a feature, put it into an abstract backend module controller and that&#8217;s it. And here we go with the code for it.</p>
<pre class="brush:php">
// Classes/Controller/AbstractModController.php

require_once(PATH_tslib . 'class.tslib_fe.php');
require_once(PATH_t3lib . 'class.t3lib_userauth.php');
require_once(PATH_tslib . 'class.tslib_feuserauth.php');
require_once(PATH_t3lib . 'class.t3lib_cs.php');
require_once(PATH_tslib . 'class.tslib_content.php');
require_once(PATH_t3lib . 'class.t3lib_tstemplate.php');
require_once(PATH_t3lib . 'class.t3lib_page.php');

class Tx_Test_Controller_AbstractModController extends Tx_Extbase_MVC_Controller_ActionController {

	public function initializeAction() {
		$this->buildTSFE();
	}

	private function buildTSFE() {
		if (!is_object($GLOBALS['TT'])) {
			$GLOBALS['TT'] = new t3lib_timeTrack;
			$GLOBALS['TT']->start();
		}

		$TSFEclassName = t3lib_div::makeInstance('tslib_fe');

		$GLOBALS['TSFE'] = new $TSFEclassName($GLOBALS['TYPO3_CONF_VARS'], $this->pid, '0', 1, '', '', '', '');
		$GLOBALS['TSFE']->connectToMySQL();
		$GLOBALS['TSFE']->initFEuser();
		$GLOBALS['TSFE']->fetch_the_id();
		$GLOBALS['TSFE']->getPageAndRootline();
		$GLOBALS['TSFE']->initTemplate();
		$GLOBALS['TSFE']->tmpl->getFileName_backPath = PATH_site;
		$GLOBALS['TSFE']->forceTemplateParsing = 1;
		$GLOBALS['TSFE']->getConfigArray();
	}

	private function uriFor($targetPageUid, $actionName = NULL, $controllerArguments = array(), $controllerName = NULL, $extensionName = NULL, $pluginName = NULL, $format = '', $argumentPrefix = NULL) {
		if ($actionName !== NULL) {
			$controllerArguments['action'] = $actionName;
		}
		if ($controllerName !== NULL) {
			$controllerArguments['controller'] = $controllerName;
		} else {
			$controllerArguments['controller'] = $this->request->getControllerName();
		}
		if ($extensionName === NULL) {
			$extensionName = $this->request->getControllerExtensionName();
		}
		if ($pluginName === NULL &#038;&#038; TYPO3_MODE === 'FE') {
			$pluginName = Tx_Extbase_Utility_Extension::getPluginNameByAction($extensionName, $controllerArguments['controller'], $controllerArguments['action']);
		}
		if ($pluginName === NULL) {
			$pluginName = $this->request->getPluginName();
		}
		if ($targetPageUid === NULL &#038;&#038; TYPO3_MODE === 'FE') {
			$targetPageUid = Tx_Extbase_Utility_Extension::getTargetPidByPlugin($extensionName, $pluginName);
		}
		if ($format !== '') {
			$controllerArguments['format'] = $format;
		}
		if ($argumentPrefix !== NULL) {
			$prefixedControllerArguments = array($argumentPrefix => $controllerArguments);
		} else {
			$pluginNamespace = Tx_Extbase_Utility_Extension::getPluginNamespace($extensionName, $pluginName);
			$prefixedControllerArguments = array($pluginNamespace => $controllerArguments);
		}

		return $prefixedControllerArguments;
	}

	protected function buildFrontendUri($targetPageUid, $actionName = NULL, $controllerArguments = array(), $controllerName = NULL, $extensionName = NULL, $pluginName = NULL, $noCache = false, $useCacheHash = true, $createAbsoluteUri = true, $format = '', $argumentPrefix = NULL) {

		$this->uriBuilder->reset();
		$this->uriBuilder->setNoCache($noCache)
				->setUseCacheHash($useCacheHash)
				->setCreateAbsoluteUri($createAbsoluteUri)
				->setArguments(
			$this->uriFor($targetPageUid, $actionName, $controllerArguments, $controllerName, $extensionName, $pluginName, $format, $argumentPrefix)
		);

		return $this->uriBuilder->buildFrontendUri();
	}
}
</pre>
<p>So what exactly is the problem why extbase cannot build frontend uris in the backend? Short answer: Because extbase uses the TYPO3 core to build uris and the core has to have a fully functional TSFE to build frontend uris that does not exist in the backend. So the litte fix here is to build our own TSFE with the least configuration necessary. Having the TSFE globally available we are able to build frontend uris but still extbase behaves not the way we want. The usual <code>uriFor</code> function does not behave like the one in our controller. If you want to know more about it, compare it on your own. Important is, that we get the frontend uri params back so we can put them into the standard uriBuilder to build the frontend uri.</p>
<p>So, let&#8217;s see next how to actually use this in our backend module. Again some code:</p>
<pre class="brush:php">
// Classes/Controller/ModController.php

class Tx_Test_Controller_ModController extends Tx_Test_Controller_AbstractModController {

	public function indexAction() {
		return $this->buildFrontendUri(5, 'action', array(), 'controller', 'tx_ext', 'pi1', true, false, true);
	}
}
</pre>
<p>So, this controller inherits all the methods from the first controller, means we can now access the <code>buildFrontendUri</code> action of the parent controller and build all needed uris. Just try it out, play around and have fun.</p>
<p>Any questions? Leave a reply.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alexanderschnitzler.de/2012/01/building-frontend-uris-in-backend-modules-with-extbase/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Disable extbase reflection cache during development (TYPO3 4.6+)</title>
		<link>http://www.alexanderschnitzler.de/2012/01/disable-extbase-reflection-cache-during-development-typo3-4-6/</link>
		<comments>http://www.alexanderschnitzler.de/2012/01/disable-extbase-reflection-cache-during-development-typo3-4-6/#comments</comments>
		<pubDate>Sat, 28 Jan 2012 15:22:00 +0000</pubDate>
		<dc:creator>Alexander</dc:creator>
				<category><![CDATA[Extbase]]></category>
		<category><![CDATA[TYPO3]]></category>

		<guid isPermaLink="false">http://www.alexanderschnitzler.de/?p=340</guid>
		<description><![CDATA[Hey folks, remember the annotations in extbase and their functions? Sure, you do. And I bet you have had this error when changing an annotation, for example the validation of a field, when you reload the page or submit some &#8230; <a href="http://www.alexanderschnitzler.de/2012/01/disable-extbase-reflection-cache-during-development-typo3-4-6/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Hey folks,<br />
remember the annotations in extbase and their functions? Sure, you do. And I bet you have had this error when changing an annotation, for example the validation of a field, when you reload the page or submit some data and nothing happens. Instead some strange message occurs. Something like &#8220;child object type could not be determined&#8221; or some other crazy stuff. Most probably you encountered a very common error during development, not caused by your own fault, but by the caching machanism of extbase.</p>
<p>It&#8217;s very easy. Extbase uses a nice feature, called reflection, you can read PHP comments (PHP docs) with. Exactly, these annotation you make in your source code. And for sure this process takes quite a lot of cpu power, so the developers of extbase implemented a cache for all these annotations for not doing the reflection every time. And it&#8217;s great in production environments, but if you are developing your domain models it&#8217;s just annoying because you have to delete the cache every time.</p>
<p>So here&#8217;s how you can disable the caching for extbase.</p>
<pre class="&quot;brush:php;">$GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['extbase_reflection']['backend'] = 't3lib_cache_backend_NullBackend';
$GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['extbase_object']['backend'] = 't3lib_cache_backend_NullBackend';</pre>
<p>Just place these lines in your <code>localconf.php</code>.</p>
<p>But be sure you are using TYPO3 4.6, means using the caching framework with the extbase caching tables as follows:<br />
<code>cf_extbase_object<br />
cf_extbase_object_tags<br />
cf_extbase_reflection<br />
cf_extbase_reflection_tags</code></p>
<p>Alright.<br />
Hope that helps you saving time and pain during your coding fun.</p>
<p>And as always, leave a reply if you want.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alexanderschnitzler.de/2012/01/disable-extbase-reflection-cache-during-development-typo3-4-6/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Howto: Ajax Requests with Extbase and Fluid</title>
		<link>http://www.alexanderschnitzler.de/2011/06/howto-ajax-requests-with-extbase-and-fluid/</link>
		<comments>http://www.alexanderschnitzler.de/2011/06/howto-ajax-requests-with-extbase-and-fluid/#comments</comments>
		<pubDate>Tue, 28 Jun 2011 14:56:55 +0000</pubDate>
		<dc:creator>Alexander</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.alexanderschnitzler.de/?p=278</guid>
		<description><![CDATA[Welcome to this short tutorial about Extbase and Ajax. If you are familiar with TYPO3 you might have heard of the eID concept that gives you the possibility to stop the rendering process very early and run your own script instead. &#8230; <a href="http://www.alexanderschnitzler.de/2011/06/howto-ajax-requests-with-extbase-and-fluid/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Welcome to this short tutorial about Extbase and Ajax. If you are familiar with TYPO3 you might have heard of the eID concept that gives you the possibility to stop the rendering process very early and run your own script instead. That means, only the most needed components are initiated to save memory and time and at the earliest moment possible you output whatever you need. That indeed is a nice feature of TYPO3 but I&#8217;m not gonna talk about it this time for different reasons.</p>
<p>Instead I want to introduce another way having the ability to use all the features TYPO3 and Extbase come with. So, let&#8217;s get started with a very small new extension. Btw: I recommend you to check out my example extension <a href="https://github.com/alexanderschnitzler/Extbase-Ajax-Example" target="_blank">on github</a> for a better understanding of what I am talking about now.</p>
<h3><span id="more-278"></span></h3>
<p>So, what has to be done. At first you need a working Extbase extension with just one controller, two actions and one template for one of these actions. To keep it simple there is no model, no repository, nothing but the controller.</p>
<pre class="brush:php;highlight:[20]">class Tx_AsAjaxexample_Controller_ExampleController extends Tx_Extbase_MVC_Controller_ActionController {

    /**
     * @return void
     */
	public function indexAction() {
    }

    /**
     * @return void
     */
	public function ajaxAction() {
        $json = array(
            'jQuery',
            'ExtJS',
            'Prototype',
            'MooTools'
        );

       return json_encode($json);
	}
}</pre>
<p>The index action does nothing else but render the template. The ajaxAction is a bit special as I do not use the render function but return a json encoded static array (line 20). This is done because the rendering of Fluid uses <code>htmlspecialchars</code> and destroys the JSON string. Now there is another problem. Calling the <code>ajaxAction</code> in the frontend you get valid JSON but also the HTML-structure of your standard template wrapped around it. To avoid that, typoscript comes into play. Let&#8217;s have a look at it:</p>
<pre class="brush:js;highlight:[3,11];">ajaxPage = PAGE
ajaxPage {
    typeNum = 99
    config {
        disableAllHeaderCode = 1
        additionalHeaders = Content-type:application/json
        xhtml_cleaning = 0
        admPanel = 0
    }

    10 &lt; tt_content.list.20.asajaxexample_pi1
}</pre>
<p>All the magic here is to create a new <code>PAGE</code> object with a <code>typeNum</code> different from &#8220;0&#8243; (line 2) and assign the content of the extension to the blank page (line 11). Adding type=99 to the request url let&#8217;s this <code>PAGE</code> come into play and outputs nothing else but what we need, the JSON string. Please be sure not to print the parsetime ( <code>&lt;!-- Parsetime: 254ms --&gt;</code> ) by adding the following line to your localconf.php:</p>
<pre class="brush:php">$TYPO3_CONF_VARS["FE"]["debug"] = '0';</pre>
<p>Now we&#8217;re ready to put the plugin on a site and view it in the frontend. In case you are not using my example extension here&#8217;s the template for you:</p>
<pre class="brush:html">&lt;button id="ajax"&gt;fetch list&lt;/button&gt;
&lt;button id="clear"&gt;delete list(s)&lt;/button&gt;
&lt;div id="list"&gt;List(s):&lt;/div&gt;

&lt;script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
ajaxUrl = "{f:uri.action(action:'ajax', pageType:'99')}";

(function($) {
    $(document).ready(function(){

        $('#clear').click(function(){
            $('#list').text('List(s):');
            return false;
        });

        $('#ajax').click(function(){
            $.getJSON(ajaxUrl, function(data) {
                var items = [];

                $.each(data, function(key, val) {
                    items.push('&lt;li id="'   key   '"&gt;'   val   '&lt;/li&gt;');
                });

                $('&lt;ul/&gt;', {
                html: items.join('')
                }).appendTo('#list');
            });

            return false;
        });
    });
})(jQuery);
&lt;/script&gt;</pre>
<p>Update: Added <code>return false;</code> to the click-functions for disabling their normal submit-behaviour.</p>
<p>I guess the code is self-explaining. There&#8217;s one button to do the request, one to clear the DOM and a placeholder div for the result. The rest is easy JS with jQuery. Having my extension installed you can now test it. As you probably can see it&#8217;s not super-fast but also not too bad. I did some tests with firebug and the request mostly took about 300ms.</p>
<p>Alright, that&#8217;s it again. Hopefully that is a little help in your daily business. <img src='http://www.alexanderschnitzler.de/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h3>Useful Links:</h3>
<ul>
<li><a href="http://typo3.org/documentation/document-library/references/doc_core_tsref/4.5.0/view/1/6/#id2630798" target="_blank">Tsref: PAGE</a></li>
<li><a href="https://github.com/alexanderschnitzler/Extbase-Ajax-Example" target="_blank">Ext: as_ajaxexample on github</a></li>
</ul>
<p>Something you didn&#8217;t understand? Leave a reply.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alexanderschnitzler.de/2011/06/howto-ajax-requests-with-extbase-and-fluid/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Error handling with Extbase: Writing own validators</title>
		<link>http://www.alexanderschnitzler.de/2011/06/error-handling-with-extbase-writing-own-validators/</link>
		<comments>http://www.alexanderschnitzler.de/2011/06/error-handling-with-extbase-writing-own-validators/#comments</comments>
		<pubDate>Tue, 21 Jun 2011 20:28:59 +0000</pubDate>
		<dc:creator>Alexander</dc:creator>
				<category><![CDATA[TYPO3]]></category>
		<category><![CDATA[Error]]></category>
		<category><![CDATA[Extbase]]></category>
		<category><![CDATA[Fluid]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Validator]]></category>

		<guid isPermaLink="false">http://www.alexanderschnitzler.de/?p=216</guid>
		<description><![CDATA[So, here&#8217;s the next part of my series about error handling with Extbase and Fluid. This time it&#8217;s about writing own validators. But at first I will explain when to use one by a simple example. Imagine you are about &#8230; <a href="http://www.alexanderschnitzler.de/2011/06/error-handling-with-extbase-writing-own-validators/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>So, here&#8217;s the next part of my series about error handling with Extbase and Fluid. This time it&#8217;s about writing own validators. But at first I will explain when to use one by a simple example.</p>
<p>Imagine you are about to build a form that creates a new object, let&#8217;s say a frontend user. Probably the user needs an email address as a unique identifier to log in with later on. So the model has a property called <code>email</code>.</p>
<pre class="brush:php">class Tx_ExtensionName_Domain_Model_ModelName extends Tx_Extbase_DomainObject_AbstractEntity
{
    /**
     * @var string
     * @validate Tx_Extbase_Validation_Validator_EmailAddressValidator
     */
    protected $email= '';
}</pre>
<h3><span id="more-216"></span></h3>
<p>If you know my post about <a title="Error handling with Extbase: Set own error messages" href="http://www.alexanderschnitzler.de/2011/06/advanced-error-handling-with-extbase-and-fluid/" target="_blank">setting own error messages</a> this example might look very familiar. As you can see, the property is a simple string and we already have the validate annotation to verify the given address. So far there&#8217;s nothing new. The validation ensures that the address itself is valid but how do we check if it&#8217;s unique inside our environment? That&#8217;s where validation classes come into play.</p>
<p>Whereas annotations validate a single property against mostly just one rule, validators are more powerful as they are able to run a whole set of more complex validations within a different context. Keeping it simple you can say that property annotations take care that an object itself is consistent during its lifetime. Validators instead are set in the context of controller actions that handle the whole object, e.g when passing a new object to a create action. Some code for a better understanding:</p>
<pre class="brush:php;highlight:[5]">class Tx_ExtensionName_Controller_ModelNameController extends Tx_Extbase_MVC_Controller_ActionController {
{
    /**
     * @param Tx_ExtensionName_Domain_Model_ModelName $newObject
     * @validate $newObject Tx_ExtensionName_Domain_Validator_ValidatorName
     */
    public function createAction(Tx_ExtensionName_Domain_Model_ModelName $newObject)
    {
        $this-&gt;modelNameRepository-&gt;add($newObject);
    }
}</pre>
<p>It&#8217;s line five that defines that the new object has to be validated against the vaildation class. Let&#8217;s switch to the validator itself:</p>
<pre class="brush:php;highlight:[26,27]">class Tx_ExtensionName_Domain_Validator_MyValidator extends Tx_Extbase_Validation_Validator_AbstractValidator
{
    /**
     * @var Tx_ExtensionName_Domain_Repository_ModelNameRepository
     */
    protected $modelNameRepository;

    /**
     * @param Tx_ExtensionName_Domain_Repository_ModelNameRepository $modelNameRepository
     * @return void
     */
    public function injectModelNameRepository(Tx_ExtensionName_Domain_Repository_ModelNameRepository $modelNameRepository)
    {
        $this-&gt;modelNameRepository = $modelNameRepository;
    }

    /**
     * @param Tx_ExtensionName_Domain_Model_ModelName $value
     * @return bool
     */
    public function isValid($value)
    {
        $this-&gt;errors = array();

        if ($this-&gt;modelNameRepository-&gt;findByEmail($value-&gt;getEmail())-&gt;count() &gt; 0) {
            $this-&gt;errors['email'] = new Tx_Extbase_Validation_PropertyError('email', time());
            $this-&gt;errors['email']-&gt;addErrors(array(new Tx_Extbase_Validation_Error('Email not unique', 84647862842)));

            return false;
        }

        return true;
    }
}</pre>
<p>Now it becomes interesting. Actually the &#8220;isValid&#8221;-method acts as a constructor, so you can write validators with just that method if you do not need any other logic. In this case we need access to a repository so there also is an inject method. If you do not know what&#8217;s going on, search for dependency injection (DI) in general and how it&#8217;s implemented in Extbase (since 1.3) in particular.</p>
<p>Having access to the repository, we can check if there&#8217;s a frontend user with the given email address yet. If so set errors and return false, else return true. But let&#8217;s see what&#8217;s happening in line 26 and 27. Again, as I mentioned in my post about <a title="Error handling with Extbase: Set own error messages" href="http://www.alexanderschnitzler.de/2011/06/advanced-error-handling-with-extbase-and-fluid/" target="_blank">setting error messages</a>, there is an error cascade beginning with a <code>Tx_Extbase_MVC_Controller_ArgumentError</code> that is related to the handled object, e.g. the new frontend user. That object contains a <code>Tx_Extbase_Validation_PropertyError</code> for every property that is not valid. And for each validation that fails there is a <code>Tx_Extbase_Validation_Error</code> that holds an error message to display in the form. So, if there&#8217;s a matching frontend user we add a <code>Tx_Extbase_Validation_PropertyError</code> to the error array first. Now we know that the email property isn&#8217;t valid but what exactly went wrong tells us the <code>Tx_Extbase_Validation_Error</code> we assign in line 27. It took me quite a while to discover how add errors but once you know it, it absolutely makes sense and is very convenient, too.</p>
<p>Perhaps I should drop some lines about the error codes at last. Well, as you see, I just used <code>time()</code> for the <code>Tx_Extbase_Validation_PropertyError</code> as I don&#8217;t care about the message. But the <code>Tx_Extbase_Validation_Error</code> should have a certain error code you can access its related message with. I did not find a convention about how to choose an appropriate number but I recommend to take something very high or low and just increase the number by one for every validation error you create. I guess, I do not have to mention that you should not overwrite existing error codes, do I?</p>
<h3>Useful links:</h3>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Dependency_injection">http://en.wikipedia.org/wiki/Dependency_injection</a></li>
<li><a href="http://forge.typo3.org/projects/typo3v4-mvc/wiki/Dependency_Injection_%28DI%29">http://forge.typo3.org/projects/typo3v4-mvc/wiki/Dependency_Injection_%28DI%29</a></li>
<li><a href="http://doxygen.frozenkiwi.com/typo3/html/d0/d04/classTx__Extbase__Validation__Validator__AbstractValidator.html" target="_blank">Tx_Extbase_Validation_Validator_AbstractValidator</a></li>
</ul>
<p>&nbsp;</p>
<p>And as usual: Found a mistake? Have a question?<br />
Just leave a reply!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alexanderschnitzler.de/2011/06/error-handling-with-extbase-writing-own-validators/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Error handling with Extbase: Placing error messages next to fields using partials</title>
		<link>http://www.alexanderschnitzler.de/2011/06/error-handling-with-extbase-placing-error-messages-next-to-fields-using-partials/</link>
		<comments>http://www.alexanderschnitzler.de/2011/06/error-handling-with-extbase-placing-error-messages-next-to-fields-using-partials/#comments</comments>
		<pubDate>Fri, 17 Jun 2011 12:28:44 +0000</pubDate>
		<dc:creator>Alexander</dc:creator>
				<category><![CDATA[TYPO3]]></category>
		<category><![CDATA[Error]]></category>
		<category><![CDATA[Extbase]]></category>
		<category><![CDATA[Fluid]]></category>
		<category><![CDATA[Partial]]></category>

		<guid isPermaLink="false">http://www.alexanderschnitzler.de/?p=183</guid>
		<description><![CDATA[Welcome to the next part of my series on error handling with Extbase and Fluid. This time I gonna show you how to place error fields next to the fields that cause them. First time ever I worked with Fluid &#8230; <a href="http://www.alexanderschnitzler.de/2011/06/error-handling-with-extbase-placing-error-messages-next-to-fields-using-partials/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Welcome to the next part of my series on error handling with Extbase and Fluid. This time I gonna show you how to place error fields next to the fields that cause them. First time ever I worked with Fluid I just found the ability to display errors as a list. For sure, that&#8217;s the easiest way arranging them because you just have to iterate through the error objects and echo the messages.</p>
<h3><span id="more-183"></span>To be honest, I don&#8217;t really like the solution I am presenting you but it&#8217;s very convenient. As we are working with partials you should know what it is. If not, the next paragraph is for you, else head on to the next section.</h3>
<p>A partial is nothing else but a part of code, most common a reusable one that represents some logic you need again and again. For instance an error list you put an error object in and once you defined how to process it you don&#8217;t care anymore in future projects. Just copy the partial, put in another object and the rest is pure magic. If you are used to object oriented programing, I guess you are, you can see the similarity.</p>
<h2>Creating the Partial</h2>
<p>It&#8217;s recommended that you put partials in a folder named &#8220;Partials&#8221; next to the templates folder. The full path is <code>EXT:Resources/Private/Partials/</code>.</p>
<p>Once you put in a partial, let&#8217;s say <code>PartialName.html</code>, you are able to render it inside your views with the use of the following Fluid render tag.</p>
<pre class="brush:html">&lt;f:render partial="PartialName" arguments="{arguments}" /&gt;</pre>
<p>We will have a look at the arguments later, up to now its only necessary to know you can pass arguments in. So, here is the field error partial:</p>
<pre class="brush:html">&lt;!-- PartialName.html --&gt;
&lt;f:form.errors for="{objectName}"&gt;
    &lt;f:if condition="{0:error.propertyName} == {0:'{propertyName}'}"&gt;
        &lt;f:for each="{error.errors}" as="errorItem"&gt;
		    &lt;f:translate key="error.{error.propertyName}.{errorItem.code}" htmlEscape="false"&gt;Not translated: [{errorItem.message} ({errorItem.code})]&lt;/f:translate&gt;
        &lt;/f:for&gt;
    &lt;/f:if&gt;
&lt;/f:form.errors&gt;</pre>
<p>Similar to rendering a whole list we also iterate through all errors in this case except that we check if a certain error occurred. If so, we echo it via the translate tag I yet wrote about in <a href="http://www.alexanderschnitzler.de/2011/06/advanced-error-handling-with-extbase-and-fluid/">my last post</a>. I know, it&#8217;s a dirty way accessing a single error and I am curious about any other possible solution but I guess this one doesn&#8217;t take too much memory or CPU time.</p>
<p>Alright, we have to combine the partial with a fitting render tag now because we now need the arguments left out in my example above.</p>
<pre class="brush:html">&lt;f:render partial="FieldError" arguments="{objectName: 'newPerson', propertyName: 'email'}" /&gt;</pre>
<p>The arguments object contains two properties called <code>objectName</code> and <code>propertyName</code>. Both are strings you just have to replace inside your project. In this example we want to create a new object named <code>newPerson</code> with an email property. These arguments are now available inside the partial and we are able to check whether the it&#8217;s an invalid email address. Most probably you place the render tag next to your input field but no matter where you put it, please do not build a list with it. <img src='http://www.alexanderschnitzler.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>Any questions? Leave a reply.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alexanderschnitzler.de/2011/06/error-handling-with-extbase-placing-error-messages-next-to-fields-using-partials/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Howto: Build an HTML5 file uploader with Ajax</title>
		<link>http://www.alexanderschnitzler.de/2011/06/howto-build-an-html5-file-uploader-with-ajax/</link>
		<comments>http://www.alexanderschnitzler.de/2011/06/howto-build-an-html5-file-uploader-with-ajax/#comments</comments>
		<pubDate>Thu, 09 Jun 2011 13:23:10 +0000</pubDate>
		<dc:creator>Alexander</dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[File API]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Upload]]></category>
		<category><![CDATA[XHR2]]></category>
		<category><![CDATA[XMLHttpRequest]]></category>

		<guid isPermaLink="false">http://alexanderschnitzler.dev/?p=104</guid>
		<description><![CDATA[As an old friend of Flash and the possibilities we got to improve the web experience years ago I am very curios about what is possible without Flash nowadays. So the first thing I wanted to know, is how to &#8230; <a href="http://www.alexanderschnitzler.de/2011/06/howto-build-an-html5-file-uploader-with-ajax/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>As an old friend of Flash and the possibilities we got to improve the web experience years ago I am very curios about what is possible without Flash nowadays.</p>
<p>So the first thing I wanted to know, is how to develop a file uploader based on web standards with having the ability to show a progress bar. Now that I write this post, this is a very hot topic because I neither found much information about it nor did I see any website having this feature except Youtube.</p>
<p>As we are talking about the client side of the uploader first it&#8217;s all about javascript now. So, a basic understanding of this language is necessary.</p>
<p>Still with me? Alright, what do we need to build this uploader? Simple said it&#8217;s two features named File API and XHR2. Never heard of? No problem. Let&#8217;s first have a look at the File API.</p>
<h3><span id="more-104"></span>The File API</h3>
<p>The API provides access to the files stored on your hard disk and numerous file operations on these. Having a closer look you recognize that the API includes a bunch of new objects with powerful functionality bringing the web and your desktop very close together. But to build an uploader we just focus on two objects:</p>
<ol>
<li>FileList</li>
<li>File</li>
</ol>
<p>While the <code>File</code> object represent a real file on your hard disk and lets you access its information through some properties and methods the <code>FileList</code> object acts as an array or a storage of <code>File</code> objects you can easily iterate through.</p>
<p>To select a file we use the following input tag, introduced 1997, when uploading 100k must have been a pain in the ass for everybody.</p>
<pre class="brush:html">&lt;input type="file" id="file" /&gt;</pre>
<p>Clicking on the button a window appears that lets you select a file. Sure, you are used to expect nothing as you chose one but you can change this by binding an event handler to the input field.</p>
<pre class="brush:js;highlight:[5]">var input = getElementById('file'); 
input.addEventHandler('change', callbackFunction);

function callbackFunction(event) {
    var FileList = event.target.files;
    var File = FileList[0];
}</pre>
<p>In line 5 we find all the magic. We can access a <code>FileList</code> object through the <code>Event</code> object that is fired when changing the <code>input</code> element. We always get a <code>FileList</code>, even when only selecting one single file but in line 6 you can see how to access it. I recommend you to build this small example, install <a href="https://addons.mozilla.org/de/firefox/addon/firebug/" target="_blank">Firebug</a> and debug the File var.</p>
<p>That&#8217;s it for the File API part. Next we have a look at XHR2.</p>
<h3>XMLHttpRequest2</h3>
<p>I&#8217;m sure you heard of XMLHttpRequest, the magic that brought Web 2.0 to life. The XHR object gave us the possibility of asynchronious HttpRequests so we can load/send data from/to a server without doing a page reload. So we were able to send/upload data ever since this object was available first but with the support of the second version we got a new property named upload. Here some code for a better understanding:</p>
<pre class="brush:js">xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", onUploadProgress);

// void open(DOMString method, DOMString url, boolean async);
xhr.open('post', 'url', true);</pre>
<p>xhr.upload is of type XMLHttpRequestUpload, a new object that is shipped with a special Event called progress that is fired as long as the upload of data takes time giving information about the current upload status.</p>
<pre class="brush:js;highlight:[7,12]">xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", onUploadProgress);

// void open(DOMString method, DOMString url, boolean async);
xhr.open('post', 'url', true);
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.setRequestHeader("X-File-Name", File.name || File.fileName);
xhr.setRequestHeader("X-File-Size", File.fileSize);
xhr.setRequestHeader("X-File-Type", File.type);

if ('getAsBinary' in File)
	xhr.sendAsBinary(File.getAsBinary());
else
	xhr.send(File);

function onUploadProgress(event) {
    if(event.lengthComuptable) {
        log(Math.round((event.loaded * 100) / event.total) + '%');
    }
}</pre>
<p>Here we got a bunch of new lines. First of all we have to imagine that we have a variable called File in this context that holds a real <code>File</code> object we chose using the input field. As you can see we set some http headers to let the server know how to handle the uploaded file. In line 7 we access the filename either through the <code>name</code> or <code>fileName</code> property of our <code>File</code> object wheras <code>name</code> is the standard and <code>fileName</code> is how Firefox 3.5 named this property.</p>
<p>Next we start the upload with <code>xhr.send(File)</code>. Due to Firefox 3.5 there is an exception in Line 12 again.</p>
<p>After starting the upload the callback function onUploadProgress is fired as long as the upload isn&#8217;t finished. As you can see we can access the bytes already loaded and the total bytes to compute the percentage of our upload progress. That&#8217;s very equal to working with ActionScript.</p>
<p>Last and least there are two possibilities to to handle the upload success as the xhr object itselt and the xhr.upload property may fire an Event on success. But while the xhr object may retriece data from the server, e.g. some JSON, the upload property just informs you about whether the upload has failed or not.</p>
<h3>The Server Side (PHP)</h3>
<p>Depending on the server technology you are using the processing of uploaded data is different. In this case we have a look at how to handle the upload with PHP as this is widely used.</p>
<p>The traditional way of uploading and processing  files is through an HTML form that sends the data via POST to the server where the uploaded file is available in the global $_FILES var. Using xhr there is no $_FILES var but you can directly access the PHP input stream.</p>
<pre class="brush:php;">$fileName = $_SERVER['HTTP_X_FILE_NAME'];

$input = fopen('php://input', 'r');
$output = '/your/path/' . $fileName;

while ($data = fread($input, 1024))
	fwrite($output, $data);

fclose($input);
fclose($output);</pre>
<p>There is just one more thing I want to show you. Imagine the user wants to upload a huge file, let&#8217;s say 50M. You might want to give him the chance to cancel the upload to not wait until the upload is finished. But with this script a file will be written even if  you uploaded just 1K. This can cause a lot of trash on your server and I hate waisted files. Hope, you too.</p>
<p>The solution is quite easy as we just have to compare the filesize of the uploaded file with the filesize we set in the http header.</p>
<pre class="brush:php; highlight:[12,13]">$fileName = $_SERVER['HTTP_X_FILE_NAME'];

$input = fopen('php://input', 'r');
$output = '/your/path/' . $fileName;

while ($data = fread($input, 1024))
	fwrite($output, $data);

fclose($input);
fclose($output);

if(filesize($fileName) != $_SERVER['HTTP_X_FILE_SIZE'])
	unlink($fileName);</pre>
<p>If the sizes don&#8217;t match, the written file will be deleted and no trash is left behind.</p>
<h3>Useful Links:</h3>
<ul>
<li><a href="http://www.w3.org/TR/FileAPI/">http://www.w3.org/TR/FileAPI/</a></li>
<li><a href="http://www.html5rocks.com/en/tutorials/file/dndfiles/">http://www.html5rocks.com/en/tutorials/file/dndfiles/</a></li>
<li><a href="http://www.w3.org/TR/XMLHttpRequest2/">http://www.w3.org/TR/XMLHttpRequest2/</a></li>
<li><a href="http://www.html5rocks.com/en/tutorials/file/xhr2/">http://www.html5rocks.com/en/tutorials/file/xhr2/</a></li>
</ul>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alexanderschnitzler.de/2011/06/howto-build-an-html5-file-uploader-with-ajax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Error handling with Extbase: Set own error messages</title>
		<link>http://www.alexanderschnitzler.de/2011/06/advanced-error-handling-with-extbase-and-fluid/</link>
		<comments>http://www.alexanderschnitzler.de/2011/06/advanced-error-handling-with-extbase-and-fluid/#comments</comments>
		<pubDate>Tue, 07 Jun 2011 12:28:09 +0000</pubDate>
		<dc:creator>Alexander</dc:creator>
				<category><![CDATA[TYPO3]]></category>
		<category><![CDATA[Error]]></category>
		<category><![CDATA[Extbase]]></category>
		<category><![CDATA[Fluid]]></category>

		<guid isPermaLink="false">http://alexanderschnitzler.dev/?p=40</guid>
		<description><![CDATA[Ever tried to make a complex form with Extbase and Fluid and had troubles with not knowing how to properly handle errors? I did, and to make life more easy for everybody I let you know my solutions. In this &#8230; <a href="http://www.alexanderschnitzler.de/2011/06/advanced-error-handling-with-extbase-and-fluid/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Ever tried to make a complex form with Extbase and Fluid and had troubles with not knowing how to properly handle errors? I did, and to make life more easy for everybody I let you know my solutions.</p>
<p>In this first part of my series I write about setting own error messages instead of using the system ones. Ready? Here we go!</p>
<h3><span id="more-40"></span>How to set own error messages?</h3>
<p>At first we need to know when errors occur. That&#8217;s quite easy because there are just two cases:</p>
<ol>
<li>Using annotations to validate model properties against one single rule</li>
<li>Using your own validator class for more complex validation.</li>
</ol>
<p>So, when validating your model properties with annotations you can either use all the validators Extbase has on board or write your own ones. In case you want to verify an email-address it makes sense using the built-in validator because it provides a nice regular expression you probably not want to write again. Let&#8217;s see some code:</p>
<pre class="brush:php">class Tx_ExtensionName_Domain_Model_ModelName extends Tx_Extbase_DomainObject_AbstractEntity
{
    /**
     * @var string
     * @validate Tx_Extbase_Validation_Validator_EmailAddressValidator
     */
    protected $email= '';
}</pre>
<p>This part is your own model with an email property you want to validate.</p>
<pre class="brush:php">class Tx_Extbase_Validation_Validator_EmailAddressValidator extends Tx_Extbase_Validation_Validator_AbstractValidator {

	public function isValid($value) {
		$this-&gt;errors = array();
		if(is_string($value) &amp;&amp; preg_match('
				/
					^[a-z0-9!#$%&amp;\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&amp;\'*+\/=?^_`{|}~-]+)*
					@
					(?:
						(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[a-z]{2}|aero|asia|biz|cat|com|edu|coop|gov|info|int|invalid|jobs|localdomain|mil|mobi|museum|name|net|org|pro|tel|travel)|
						localhost|
						(?:(?:\d{1,2}|1\d{1,2}|2[0-5][0-5])\.){3}(?:(?:\d{1,2}|1\d{1,2}|2[0-5][0-5]))
					)
					\b
				/ix', $value)) return TRUE;
		$this-&gt;addError('The given subject was not a valid email address.', 1221559976);
		return FALSE;
	}
}</pre>
<p>And this one is the given validator class.</p>
<p>Now, when using this validator, it causes the standard error message &#8220;<em>The given subject was not a valid email address.</em>&#8220;. Either you simply want to change the message to sth. more fitting like &#8220;<em>Sorry dude, please enter a valid email address</em>&#8221; or translate it into another language there&#8217;s the same easy solution for both cases: The <a href="http://wiki.typo3.org/Fluid#f:translate" target="_blank">Fluid translation tag</a>.</p>
<p>Btw. you should have a look at the <a href="http://git.typo3.org/TYPO3v4/CoreProjects/MVC/blog_example.git" target="_blank">blog_example</a>. Most of my knowledge I do have from this extension.</p>
<pre class="brush:html">&lt;f:translate key="LLL:EXT:extension/Resources/Private/Language/locallang.xml:key" /&gt;</pre>
<p>There&#8217;s also the possibility to use this tag &#8220;inline&#8221; but it&#8217;s not that important in this blog post. Nevertheless you should have a look at it as most Fluid tags can be used this way.</p>
<pre class="brush:js">&lt;img alt="{f:translate(key:'LLL:EXT:p/a/t/h/locallang.xml:key')}" /&gt;</pre>
<p>Before showing you the template with it&#8217;s error part and how to actually combine it with the translation tags, I need your attention because the way you access errors is a bit special and worth being explained in a few sentences. Here we go:</p>
<p>In your template you can access all occurring errors through one object of type <code>Tx_Extbase_MVC_Controller_ArgumentError</code>. Let&#8217;s say you have ten properties to validate and all of them produce an error, than your error object contains an array of ten objects of type <code>Tx_Extbase_Validation_PropertyError</code> inside. Each of these objects also has an array to store multiple objects of type <code>Tx_Extbase_Validation_Error</code>.</p>
<p>Does not make sense? It does! While the first array contains all the <code>Tx_Extbase_Validation_PropertyError</code> objects for each property that threw an error, the second array inside the <code>Tx_Extbase_Validation_PropertyError</code> object contains all <code>Tx_Extbase_Validation_Error</code> objects related to the property itself. Still not clear?</p>
<p>Imagine you have more than one validation rule for a property. Perhaps you want an email address to be valid and unique inside your system environment, then you have to validate against two validation rules that can throw an error message each. For a better understanding here is a visualisation of it:</p>
<pre class="brush:php">Tx_Extbase_MVC_Controller_ArgumentError Object
(
    [message:protected] =&gt; Validation errors for argument "newObject"
    [code:protected] =&gt; 1245107351
    [propertyName:protected] =&gt; newObject
    [errors:protected] =&gt; Array
        (
            [email] =&gt; Tx_Extbase_Validation_PropertyError Object
                (
                    [message:protected] =&gt; Validation errors for property "email"
                    [code:protected] =&gt; 1242859509
                    [propertyName:protected] =&gt; email
                    [errors:protected] =&gt; Array
                        (
                            [0] =&gt; Tx_Extbase_Validation_Error Object
                                (
                                    [message:protected] =&gt; The given subject was not a valid email address.
                                    [code:protected] =&gt; 1221559976
                                )
                            [1] =&gt; Tx_Extbase_Validation_Error Object
                                (
                                    [message:protected] =&gt; The email address is not unique.
                                    [code:protected] =&gt; 1221559989
                                )
                        )
                )
	)
)</pre>
<p>In the following code I just iterate through the error array of a single <code>Tx_Extbase_Validation_PropertyError</code> object while <code>property.errors</code> is the error array.</p>
<pre class="brush:html">&lt;ul&gt;
&lt;f:for each="{property.errors}" as="propertyError"&gt;
    &lt;li&gt;
        {propertyError.message}
    &lt;/li&gt;
&lt;/f:for&gt;
&lt;/ul&gt;</pre>
<p>Now there's not much more to do or understand. Instead of showing the original error message we use a translation tag.</p>
<pre class="brush:html">&lt;ul&gt;
&lt;f:for each="{property.errors}" as="propertyError"&gt;
    &lt;li&gt;
        &lt;f:translate key="error.{property.propertyName}" htmlEscape="false"&gt;Not translated: [{propertyError.message}]&lt;/f:translate&gt;
    &lt;/li&gt;
&lt;/f:for&gt;
&lt;/ul&gt;</pre>
<p>So we can easily access our desired/translated error message. The corresponding locallang.xml should look like this:</p>
<pre class="brush:xml; highlight: [9]">&lt;?xml version="1.0" encoding="utf-8" standalone="yes" ?&gt;
&lt;T3locallang&gt;
    &lt;meta type="array"&gt;
        &lt;type&gt;module&lt;/type&gt;
        &lt;description&gt;Language labels for the extension&lt;/description&gt;
    &lt;/meta&gt;
    &lt;data type="array"&gt;
        &lt;languageKey index="default" type="array"&gt;
            &lt;label index="error.email"&gt;your error message&lt;/label&gt;
        &lt;/languageKey&gt;
    &lt;/data&gt;
&lt;/T3locallang&gt;</pre>
<p>Be free to experience what else is possible or necessary. If you want to have more than one error message translated I recommend you to extend the locallang key with the error code. Could be sth. like this:</p>
<pre class="brush:html">&lt;f:translate key="error.{field.propertyName}.{field.errorCode}" htmlEscape="false"&gt;Not translated: [{fieldError.message}]&lt;/f:translate&gt;</pre>
<pre class="brush:xml">&lt;label index="error.email.1221559976"&gt;your error message&lt;/label&gt;</pre>
<p>Alright, that's it in the first place. Here is a list of all links I referred to in this post.</p>
<h3>Useful links:</h3>
<ul>
<li><a href="http://wiki.typo3.org/Fluid" target="_blank">http://wiki.typo3.org/Fluid</a></li>
<li><a href="http://git.typo3.org/TYPO3v4/CoreProjects/MVC/blog_example.git" target="_blank">blog_example</a></li>
<li><a href="http://doxygen.frozenkiwi.com/typo3/html/d2/d4e/classTx__Extbase__MVC__Controller__ArgumentError.html" target="_blank">class Tx_Extbase_MVC_Controller_ArgumentError</a></li>
<li><a href="http://doxygen.frozenkiwi.com/typo3/html/d4/df7/classTx__Extbase__Validation__PropertyError.html" target="_blank">class Tx_Extbase_Validation_PropertyError</a></li>
<li><a href="http://doxygen.frozenkiwi.com/typo3/html/d2/d81/classTx__Extbase__Error__Error.html" target="_blank">class Tx_Extbase_Error_Error</a></li>
</ul>
<p>&nbsp;</p>
<p>Found a mistake? Have a question? Offer critisism?<br />
Just leave a reply!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.alexanderschnitzler.de/2011/06/advanced-error-handling-with-extbase-and-fluid/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

