Showing posts with label Extbase. Show all posts
Showing posts with label Extbase. Show all posts

Friday, June 4, 2021

How to use constructor dependency injection in a XCLASSed TYPO3 class

Some time ago in needed to extend an Extbase controller in TYPO3 10.4 which used dependency injection through constructor injection. So I used XCLASS to extend the original controller and added an own constructor which added an additional dependency, but this obviously did not work out properly, since the constructor was always called with the amount of arguments from the original class.

Later I created this issue on TYPO3 forge in order to find out if this is a bug/missing feature or if I missed something in my code. In order to demonstrate the problem, I created this small demo extension which basically just extended a TYPO3 core class using XCLASS and just days later, a solution for the issue was provided.

The solution is pretty simple and you just have to ensure to add a reference to the extended class in the Services.yaml file of the extending extension.

Example:


  TYPO3\CMS\Belog\Controller\BackendLogController: '@Derhansen\XclassDi\Controller\ExtendedBackendLogController'

The complete Services.yaml file can be found here.

Thanks a lot to Lukas Niestroj, who pointed out the solution to the problem.


Monday, September 2, 2019

How to fix TYPO3 error "There is no column with name 't3ver_oid' on table"

Recently the following error message showed up in a project I was updating to TYPO3 9.5:

There is no column with name 't3ver_oid' on table 'tx_news_domain_model_news'.

When you see this message in a TYPO3 project, you should of course first check, if the field is really available in the mentioned table and second, you should check, if extension dependencies are correct.

When extending an Extbase extension (in this case ext:news), you must ensure, that the extending extension is loaded after the extension you extend. In order to do so, you must add a dependency to the extension you extend in your ext_emconf.php like shown below (example when extending ext:news):


'constraints' => [
    'depends' => [
        'news' => '7.3.0-7.3.99'
    ],
],

After adding the dependency, make sure to regenerate PackageStates.php ("Dump Autoload Information" in install tool or "composer dumpautoload"  for composer projects)

Monday, April 1, 2019

Extbase $query->statement() - What can possibly go wrong?

Last week I had to resolve a problem in a 3rd party Extension, where an Extbase Plugin returned unexpected results when used multiple times on the same page. The problem showed up in the frontend, where the plugin listed some products by a given category. When the plugin was present one time on a page, the output was as following (simplified):

Output of plugin 1
Product 1 for Category 1
Product 2 for Category 1
Product 3 for Category 1

When the plugin was present two times on a page, the output was as following (simplified):

Output of plugin 1 with Category 1 as selection criteria
Product 1 for Category 1 (uid 1)
Product 2 for Category 1 (uid 2)
Product 3 for Category 1 (uid 3)

Output of plugin 2 with Category 2 as selection criteria
Product 1 for Category 2 (uid 10)
Product 2 for Category 1 (uid 2) <-- Whoops!
Product 3 for Category 2 (uid 11)

Somehow, the output of plugin 2 contained a result, that did not belong to the result set. As written, the examples above are simplified. The output on the production website showed hundreds of products, and just some of them were wrong.

In order to debug the problem, I had a look at the Extbase Repository for the Products Domain model and found this (again simplified).


class ProductRepository extends \TYPO3\CMS\Extbase\Persistence\Repository
{
    /**
     * @param $categoryUid
     * @return array|\TYPO3\CMS\Extbase\Persistence\QueryResultInterface
     */
    public function findByCategory($categoryUid)
    {
        $query = $this->createQuery();
        $query->statement('SELECT * FROM tx_products_domain_model_product_' . $categoryUid);
        return $query->execute();
    }
}

OK... so there are several individual tables for products by category. They all have the same structure and the only difference is, that they have a different name (post-fixed with the category uid) and hold different data. There is also a SQL injection vulnerability, but that has nothing to do with the main problem.

What goes wrong here?


In order to explain, why plugin 2 returns an object, that obviously belongs to plugin 1, you have to know the internals of an Extbase repository, the Extbase QueryResult object and the DataMapper.

Extbase determines the Domain Model based on the Classname. This is done in the constructor of the repository like shown below:

public function __construct(\TYPO3\CMS\Extbase\Object\ObjectManagerInterface $objectManager)
{
    $this->objectManager = $objectManager;
    $this->objectType = ClassNamingUtility::translateRepositoryNameToModelName($this->getRepositoryClassName());
}

So when the findByCategory function uses the createQuery() function, the query is initialized to create a query for the object type the Repository determined (in this case Product).

When the query is executed using $query-execute(), it returns an object of the type \TYPO3\CMS\Extbase\Persistence\Generic\QueryResult and here we come closer to the explanation of the problem. The QueryResult object has the following function:

protected function initialize()
{
    if (!is_array($this->queryResult)) {
        $this->queryResult = $this->dataMapper->map(
            $this->query->getType(),
            $this->persistenceManager->getObjectDataByQuery($this->query)
        );
    }
}

This function uses the result from the persistenceManager (raw data from the database with language/workspace overlay) and uses the TYPO3 DataMapper to  create an array with Objects of the given type (Product). The DataMapper does this row by row using the following function mapSingleRow($className, array $row)

And here is the final explanation for the behavior of the 2 plugins on the same page.

protected function mapSingleRow($className, array $row)
{
    if ($this->persistenceSession->hasIdentifier($row['uid'], $className)) {
        $object = $this->persistenceSession->getObjectByIdentifier($row['uid'], $className);
    } else {
        $object = $this->createEmptyObject($className);
        $this->persistenceSession->registerObject($object, $row['uid']);
        $this->thawProperties($object, $row);
        $this->emitAfterMappingSingleRow($object);
        $object->_memorizeCleanState();
        $this->persistenceSession->registerReconstitutedEntity($object);
    }
    return $object;
}

For performance reasons, the DataMapper caches all objects it creates based on their UID. Since the repository in this TYPO3 extension uses different tables (with own UIDs) for data storage, it may happen, that the DataMapper already processed an object with the given UID (but from a different table) and therefore will return a cached version of an object.

So when the output for plugin 1 was created, the DataMapper did create a cached Product object for UID 2 and when the output for plugin 2 was created, the DataMapper returned the cached version of the Product object with UID 2.

So always keep in mind, that an Extbase repository will return objects of exactly one type and that the datasource must always contain unique uids.



Monday, March 18, 2019

Extending Extbase domain models and controllers using XCLASS

In TYPO3 9.5 LTS it has been deprecated (see notice) to extend Extbase classes using TypoScript config.tx_extbase.objects and plugin.tx_%plugin%.objects. In order to migrate existing extensions, which extends another TYPO3 extension, you should now use XLASSes.

For my TYPO3 Extension sf_event_mgt I also provide a small demo extension, which shows how to extend domain models and controllers of the main extension. The previous version using config.tx_extbase.objects can be found here. I migrated this demo extension to use XCLASSes instead.

The code below shows, how two models and one controller are extended using XLASS


// XCLASS event
$GLOBALS['TYPO3_CONF_VARS']['SYS']['Objects'][\DERHANSEN\SfEventMgt\Domain\Model\Event::class] = [
    'className' => \DERHANSEN\SfEventMgtExtendDemo\Domain\Model\Event::class
];

// Register extended domain class
GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Object\Container\Container::class)
    ->registerImplementation(
        \DERHANSEN\SfEventMgt\Domain\Model\Event::class,
        \DERHANSEN\SfEventMgtExtendDemo\Domain\Model\Event::class
    );

// XCLASS registration
$GLOBALS['TYPO3_CONF_VARS']['SYS']['Objects'][\DERHANSEN\SfEventMgt\Domain\Model\Registration::class] = [
    'className' => \DERHANSEN\SfEventMgtExtendDemo\Domain\Model\Registration::class
];

// Register extended registration class
GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Object\Container\Container::class)
    ->registerImplementation(
        \DERHANSEN\SfEventMgt\Domain\Model\Registration::class,
        \DERHANSEN\SfEventMgtExtendDemo\Domain\Model\Registration::class
    );

// XCLASS EventController
$GLOBALS['TYPO3_CONF_VARS']['SYS']['Objects'][\DERHANSEN\SfEventMgt\Controller\EventController::class] = [
    'className' => \DERHANSEN\SfEventMgtExtendDemo\Controller\EventController::class
];


For domain models, the important part is the registerImplementation() call, since this instructs Extbase to use the extended domain model when an object is processed by the property mapper.

Note, that there are some limitations using XCLASS, so it is highly recommended to read the official documentation.

Wednesday, April 11, 2018

TYPO3 extension sf_event_mgt version 3.0 released

Today I finally released the new version 3.0 of my TYPO3 extension sf_event_mgt - Event management and registration. The new version comes with tons of new features, bugfixes and improvements and also contains 2 breaking changes, so make sure to read the release notes.

Thanks to everyone, who contributed to the extension over the last few months. Also a special thanks to Alex Kellner for his extension powermail, from which I adapted ideas and some code for the registration fields feature.


New features 

Below follows some of the new features of sf_event_mgt 3.0.

Registration fields

Im order to make the extension more easy to use for non-programmers, I added the possibility for editors add additional registration fields to the default registration form on event basis.

Registration fields
Creating of registration fields works basically as in powermail. The user can add registrations fields in a new tab as shown in the screenshot above and choose one of the following field types: input, textarea, radio and checkbox.  When a participant registers to an event, all filled out registration fields are saved to the registration record in the TYPO3 backend.



allowLanguageSynchronization for TYPO3 8.7

The TCA settings allowLanguageSynchronization has been introduced in TYPO3 8.6 and is the successor for "l10n_mode=mergeIfNotBlank". Note, that sf_event_mgt did not use "l10n_mode=mergeIfNotBlank", so the language synchronization feature is only available in TYPO3 8.7



Signals

Finally, I also added signals in various actions, so it is now easily possible to modify/extend variables given to the desired views.



Wednesday, June 28, 2017

TYPO3 8.7 LTS - How to enable the image cropping tool in your own extension

People using TYPO3 7.6 or 8.7 for sure know the cool Image Cropping tool that was introduced with TYPO3 7. As an extension developer, you can easily switch on the Image Cropping tool for your own extension by enabling adding the imageoverlayPalette to the foreign_types config array for the FILETYPE_IMAGE in the TCA like shown in this blogpost by Marcus Schwemer. In TYPO3 8.7 the Image Cropping tool does not show as expected, due to structural TCA changes in the TYPO3 8.

For TYPO3 8.7, the following (minimal) TCA configuration will enable the Image Cropping tool for the field "image" in an own extension:


'image' => [
    'exclude' => 1,
    'label' => 'LLL:EXT:custom_extension/Resources/Private/Language/locallang_db.xlf:tx_customextension_domain_model_tablename.custom_field',
    'config' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getFileFieldTCAConfig('image', [
        'foreign_match_fields' => [
            'fieldname' => 'image',
            'tablenames' => 'tx_customextension_domain_model_tablename',
            'table_local' => 'sys_file',
        ],
        'overrideChildTca' => [
            'types' => [
                \TYPO3\CMS\Core\Resource\File::FILETYPE_IMAGE => [
                    'showitem' => '
                            --palette--;LLL:EXT:lang/Resources/Private/Language/locallang_tca.xlf:sys_file_reference.imageoverlayPalette;imageoverlayPalette,
                            --palette--;;filePalette'
                ],
            ],
        ],
        'minitems' => 0,
        'maxitems' => 999,
    ], $GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext']),
],

Note, that the configuration array only shows the configuration for a single field and that the array must be located in the "columns"-array of your domain model TCA. For TYPO3 8.7, the overrideChildTca config is the important part, which enables the Image Cropping tool.

If your extension needs to support TYPO3 7.6 and 8.7, your TCA should include both the overrideChildTca config as described in this blogpost and the foreign_types config as described in Marcus's blogpost.




Monday, June 26, 2017

TYPO3 Extbase - Manual validation of a domain model

When you create an Extbase extension and allow a website user to submit form data that will be saved to the TYPO3 database, you usually work with validators in your domain model to ensure, that the given data will match certain criteria (e.g. properties have the right data type or expected data format). Extbase offers an easy way to add validation rules to domain model properties, by just adding the @validate annotation followed by one or multiple validators as shown in the following example:

/**
 * Description
 *
 * @var string
 * @validate NotEmpty, StringLength(minimum=10, maximum=50)
 */
protected $description = '';

Extbase will take care of the domain model validation, when the given form data is converted to an object of the type TYPO3\CMS\Extbase\Mvc\Controller\Argument.

Manual validation


If you manually create a domain model object and want to make sure, that your Extbase validation rules are meet, you can trigger the domain model validation manually as shown below:

/** @var Data $dataModel */
$dataModel = $this->objectManager->get(Data::class);
$dataModel->setDescription('too short');

/* @var $validator \TYPO3\CMS\Extbase\Validation\Validator\ConjunctionValidator */
$validator = $this->objectManager->get(ValidatorResolver::class)->getBaseValidatorConjunction(Data::class);
$validationResults = $validator->validate($dataModel);

if ($validationResults->hasErrors()) {
    // @todo cycle through errors in $validationResults->getFlattenedErrors()
}

By creating the domain model object manually, you must take into account, that this will create a new object, where all properties are initialized with the default values defined in the domain model.

Practical use case


As an example for a practical use case for manual domain model validation, lets assume you have a REST webservice and need to import some data to TYPO3. You typically fetch the data from the webservice and add the data to the database. Instead of checking the content of the incoming record/field manually using if-statements, you can use the Extbase property mapper in combination with manual domain model validation.

Below follows some example code for the described use case:

/** @var PropertyMapper $propertyMapper */
$propertyMapper = $this->objectManager->get(PropertyMapper::class);

// Get some data - could for example be some data from a REST webservice
$data = $this->getApiData();

foreach ($data as $importRecord) {
    $dataModel = $propertyMapper->convert($importRecord, Data::class);
    // Note: The propertyMapper will set domain model default values for all all non-mappable values

    /* @var $validator \TYPO3\CMS\Extbase\Validation\Validator\ConjunctionValidator */
    $validator = $this->objectManager->get(ValidatorResolver::class)->getBaseValidatorConjunction(Data::class);
    $validationResults = $validator->validate($dataModel);

    if ($validationResults->hasErrors()) {
        // Record could not be imported, collect error messages for each field in $errorMessages array

        /** @var Error $error */
        foreach ($validationResults->getFlattenedErrors() as $field => $errors) {
            $errorMessages = [];
            foreach ($errors as $error) {
                $errorMessages[] = $error->getMessage();
            }
        }
    } else {
        // Import record to repository...
    }
}

By using the Extbase property mapper to create domain model objects, you do not need to check and assign each field individually. You just have to make sure, that the array given passed to the "convert" function use the same field naming as the domain model do like shown below.


'title' => 'a title',
'email' => 'torben@derhansen.com',
'description' => 'a description',
'year' => 2017,
'amount' => 19.99,
'paid' => true

Note, that the resulting object from the property mapper will contain the default values for each property, that can't be mapped properly.

In the code example above, the resulting domain model object will manually be validated and if no validation errors occur, the object can be added to the repository.

I created a small demo extension with a command controller, which contains 2 example commands that show validation results for some dummy data.

Monday, May 15, 2017

How to use MySQL FIELD-function in TYPO3 8.7 with Doctrine DBAL

When you want to query an Extbase repository for a list of UIDs or PIDs, you usually add a query constraint like query->in('pid', $pidList) to the query, where $pidList is an array of integers. But what, if you want to control the sorting of the returned records? Lets assume, you want to select the following list of UIDs [5, 3, 4, 1] from your repository and the sorting or the UIDs must remain.
Extbase only has the possibility to sort the query result by a given column either ascending or descending, so there is no possibility to control so returned sorting as intended.

In order to resolve the problem, I found this very helpful article from Manfred Rutschmann, where he describes exactly the same situation and offers a solution for the problem, which works great in TYPO3 7.6. Sadly the solution does not work in TYPO3 8.7 LTS and fails with an exception, that e.g. column tx_myext_domain_model_mymodel.uid=5 does not exist.

Since I'm using MySQL as a database engine, I tried to find a solution, where I could use the MySQL FIELD-function to apply the special sorting to the ORDER BY clause.

Fortunately Doctrine DBAL was integrated in TYPO3 8.7 LTS, which offers an easy and readable way to construct my query. I added the following function to my Extbase repository.


In line 31 I add my own ORDER BY FIELD clause, where the special sorting is applied

Since the queryBuilder just returns an array of database records (where each records is just an array of returned fields/values), I use the TYPO3 DataMapper in line 35 to map the returned rows as objects, so the returned QueryResult object will contain objects of the type Mymodel

The example shown has one little downside, since it only works with a MySQL Database.

If you want to get more details about the Doctrine DBAL integration in TYPO3, make sure to read the documentation.




Monday, February 8, 2016

How Extbase determines the storagePid setting for a plugin

When you search for the terms "extbase storagePid" in your favorite search engine, you will find several blogs, forum-posts, mailing list entries and code examples on how to set the storagePid for the plugin of an Extbase extension.  Many examples refer to TypoScript persistence settings for the extension itself (plugin.tx_myext.persistence.storagePid), which is good, as long as you do not directly set persistence settings for a plugin like shown in the example.

Example


Let us assume, that you have a TYPO3 Extbase extension, that has configured a storagePid for a plugin in TypoScript as shown below.


plugin.tx_myext_myplugin {
 persistence {
  storagePid = {$plugin.tx_myext_myplugin.persistence.storagePid}
 }
}
Now you want the editor to be able to set the storagePid from the plugin settings. Since a TYPO3 plugin by default has a configuration setting called Record Storage Page, you use this configuration setting and select a page.

Surprisingly, the Plugin will still use the setting configured in TypoScript. But why?

Extbase storagePid determination


Extbase uses the configurationManager to determine the storagePid. When you create an Extbase extension which should be configurable by users, it is important to understand how and in which order Extbase determines/overrides the storagePid for a plugin.

Step 1 - Default storagePid


Extbase uses the default storagePid which is 0

Step 2 - Extbase persistence settings


If Extbase has configured a storagePid in config.tx_extbase.persistence.storagePid, then Extbase will use this storagePid. (note, in the code, this happens before before step 1)

Step 3 - Extension/Plugin configuration from TypoScript


Extbase fetches the configuration for the plugin from TypoScript persistence settings in plugin.tx_myext.persistence.storagePid and merges it with plugin.tx_myext_myplugin.persistence.storagePid - The plugin settings override the extension settings. If the resulting storagePid is set (or empty), Extbase will use the configured value as storagePid

Step 4 - Override storagePid from starting point setting


If the plugin uses the starting point (Record Storage Page) and one/multiple pages are selected as starting point, Extbase will now use this as storagePid.

Step 5 - Override storagePid from Plugin settings


Now Extbase fetches the configuration for the plugin from TypoScript from plugin.tx_myext_myplugin.persistence.storagePid and if set (or empty), Extbase now uses this as storagePid.


Step 6 - Override storagePid from Flexform


Finally Extbase checks, if the plugin has configured a flexform and if so, it merges all settings, persistence and view elements from the flexform with the current Extbase plugin configuration. The merge is done recursive and settings from TypoScript will be overridden by the flexform settings. So if you have configured persistence.storagePid in your flexform, this will be used as the storagePid.

Make sure you read the important note below, since there is something to keep in mind when working with empty flexform values.

Step 7 - Expand storagePid if recursive setting is set


If persistence.recursive is set in plugin.tx_myext_myplugin or in your flexform, Extbase will expand all configured storagePids recursive by the configured depth. If set, the final storagePid will contain a list of page uids for all subfolders of the original storagePid.


It is important to know, that each determination step will override the storagePid setting from the previous step. So for our example from above, the starting point setting gets overridden by the Plugin TypoScript setting.

Also keep in mind, that as soon as you use plugin.tx_myext_myplugin.persistence.storagePid, the persistence settings for the extension plugin.tx_myext.persistence.storagePid and also the record storage page settings will get overridden.


StoragePid when creating new records


When you have set the storagePid (which in fact may contain several page uids), Extbase will always use the first uid when creating a new record. So if you have configured  plugin.tx_myext_myplugin.persistence.storagePid = 10,11,12 then new records created from the plugin will be saved to the page with the uid 10.

In order to override this behaviour, you can either add a property to your domain object which contains the page uid - e.g. getPid() - or you can override the storagePid for new records by TypoScript with the newRecordStoragePid setting as shown below:

plugin.tx_myext {
 persistence {
  storagePid = {$plugin.tx_myext.persistence.storagePid}
  classes {
   Vendor\Myext\Domain\Model\Mymodel {
    newRecordStoragePid = 16
   }
  }
 }
}

Setting the storagePid from flexform


To set the storagePid from flexform, you can use the code snippet below. It is an extract from a flexform XML structure which contains a field for the storagePid and another field for the recursive setting.

<persistence.storagePid>
    <TCEforms>
        <exclude>1</exclude>
        <label>Storage PID</label>
        <config>
            <type>group</type>
            <internal_type>db</internal_type>
            <allowed>pages</allowed>
            <size>3</size>
            <maxitems>99</maxitems>
            <minitems>0</minitems>
            <show_thumbs>1</show_thumbs>
            <wizards>
                <suggest>
                    <type>suggest</type>
                </suggest>
            </wizards>
        </config>
    </TCEforms>
</persistence.storagePid>

<persistence.recursive>
    <TCEforms>
        <label>LLL:EXT:lang/locallang_general.xlf:LGL.recursive</label>
        <config>
            <type>select</type>
            <items type="array">
                <numIndex index="1" type="array">
                    <numIndex index="0">LLL:EXT:news/Resources/Private/Language/locallang_be.xlf:flexforms_general.recursive.I.inherit</numIndex>
                    <numIndex index="1"></numIndex>
                </numIndex>
                <numIndex index="2" type="array">
                    <numIndex index="0">LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:recursive.I.0</numIndex>
                    <numIndex index="1">0</numIndex>
                </numIndex>
                <numIndex index="3" type="array">
                    <numIndex index="0">LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:recursive.I.1</numIndex>
                    <numIndex index="1">1</numIndex>
                </numIndex>
                <numIndex index="4" type="array">
                    <numIndex index="0">LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:recursive.I.2</numIndex>
                    <numIndex index="1">2</numIndex>
                </numIndex>
                <numIndex index="5" type="array">
                    <numIndex index="0">LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:recursive.I.3</numIndex>
                    <numIndex index="1">3</numIndex>
                </numIndex>
                <numIndex index="6" type="array">
                    <numIndex index="0">LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:recursive.I.4</numIndex>
                    <numIndex index="1">4</numIndex>
                </numIndex>
                <numIndex index="7" type="array">
                    <numIndex index="0">LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:recursive.I.5</numIndex>
                    <numIndex index="1">250</numIndex>
                </numIndex>
            </items>
        </config>
    </TCEforms>
</persistence.recursive>

It is important, that the field naming of the fields is equal to the TypoScript naming. Since Extbase will merge all flexform fields to the plugin configuration, persistence.storagePid and persistence.recursive from the flexform will override the TypoScript settings.

Important note:
If you have set a storagePid by flexform and delete it afterwards, then the final storagePid will be empty. The reason for this is the field pi_flexform in tt_content table for the plugin, which will contain an empty value for persistence.storagePid


<field index="persistence.storagePid">
  <value index="vDEF"></value>
</field>

This empty value actually overrides all other storagePid settings. You can avoid this behavior by using the processDatamap_postProcessFieldArray hook to unset empty field values in flexform if needed

Conclusion


As a result of this blogpost, I would recommend to use plugin.tx_myext.persistence.storagePid and the record storage page option to set the storagePid of a plugin, since it works out of the box and does not have any things to keep mind.

Sunday, January 17, 2016

TYPO3 ExtBase - Hidden and deleted property of domain models

TYPO3 ExtBase repositories do by default only return non-hidden and non-deleted records. You can easily override this behavior by modifying the default query settings for the given repository. If you for example want to return all FrontendUser (including hidden and deleted) from a TYPO3 website, you can set the query settings as shown below.

Now all available FrontendUser records are returned. When you now loop over the queryResult, you will see, that the FrontendUser Objects returned do not contain any information about if the record actually is hidden or deleted.


Note that the example above shows the assignment of the defaultQuerySettings directly in an action. Typically you define this in the initializeObject method or directly in the repository.

In order to obtain those information, you need to extend the existing FrontendUser domain model with two fields. First, you need to create an own domain model with two properties as shown below (must be located in a extension - usually your own).
Note that I called the property which indicates if a record is hidden or not "disable" and not "hidden". I could not get the example to work with a property called "hidden".

Next you need to add the new fields to the TCA by adding the file fe_users.php with the following content to the folder Configuration/TCA/Overrides.

Finally you must add you new domain model as a subclass for the original FrontendUser domain modal and map the two new properties. Add the file ext_typoscript_setup.txt to the root folder of your extension with the following content.

Note, that the key in line 6 (in this example "0") must be used in line 12 as recordType.

After clearing all caches, ExtBase now returns all FrontendUsers containing the two new properties "deleted" and "disable"

Friday, November 7, 2014

TYPO3 CMS - Event management extension with registration option

Today I've published the first release of my latest extension "Event management and registration" (sf_event_mgt) for TYPO3 CMS. The extension enables TYPO3 editors to manage events in the TYPO3 backend and can show a list- and a detail-view for upcoming, past or all events in the frontend. The list-view can be extended by individual layouts as known from the TYPO3 news extension (tx_news), so it should for example be possible to create a nice image slider for all upcoming top-events.

As events also could require a registration process (e.g. if the number of participants is limited), I added a registration option, so users can register for an event. TYPO3 editors can assign a maximun value for participants to each individual event, so it can not be over-booked. The registration contains a double opt in process, so users must confirm, that they actually have registered for the event. To ensure, that new registrations are processed in time by the registering user, a validity for confirmation-links can be configured.

Event record in TYPO3 backend

The extension also comes with a backend module, which enables TYPO3 editors to get an overview of all available events. Also the backend module contains a CSV-Export option for events where registration is enabled, so a list of registered participants easily can be exported.

Event backend administration module
The backend module also contains a notification module, where TYPO3 editors can send e-mail notifications to all participants of an event (e.g. if the event has been cancelled). Notification templates can be configured individually with some lines of TypoScript and with a Fluid template.

Notification module to send notifications to participants
Finally, the extension has some nice features, which are more technical, but makes the extension very flexible and extendible. Of course, the extension comes with a documentation ReST format which explains all features in detail.

I've tried to keep the code quality at a high level, respected the TYPO3 CGL as much as possible and also "Event management and registration" is fully covered by tests (which does not mean it is bug-free).

The extension is available on TER and bugs as well as feature requests can be reported on GitHub, where also the source code of the extension is hosted.



Sunday, July 20, 2014

TYPO3 6.2 - automated test execution and CGL code analysis for ExtBase extensions with Jenkins CI

Some of my public repositories on GitHub are integrated in Travis CI and Scrutinizer CI, so each new commit automatically starts a predefined build process where tests and code analysis are executed. For open source projects, the combination of GitHub, Travis CI and Scrutinizer CI is perfect. For private repositories, you can also use those services if you pay for them or you could built up the CI environtment yourself.

On work I've been using Jenkins CI for some years now to build our PHP, Java and Android projects. I'm also using Jenkins CI to process tests automation and code analysis for our TYPO3 extensions, which should be tested on different TYPO3 versions. This configuration was some kind of complicated, since each TYPO3 extension had to be installed in a working TYPO3 environment before it could be tested automatically by Jenkins CI. I've written a blogpost about this setup back in january 2013.

In this article I describe how I've setup a simple job in Jenkins CI for a TYPO3 6.2 ExtBase extension. The job executes the standalone unit tests and also does some TYPO3 CGL code analysis. Everything shown below should be seen as an example, since some analysis tasks like code coverage or pdepend are missing.

Prerequisites
  • A running Jenkins CI server with at least the Git Plugin and the PHP Plugin
  • ANT, composer, phpunit, phpmd and phpcs installed on the Jenkins CI server
  • Jenkins workspace dir configured with ${ITEM_ROOTDIR}/workspace/
  • The TYPO3 CMS CGL installed as a global standard
  • An ExtBase extension with some working unit tests
Creating the ANT build file

As fas as I know it is still best to use ANT for PHP projects on Jenkins CI. Therefore I created an ANT build file, which contains some tasks for the build. The ANT build file is added to my ExtBase extension (e.g. my_extkey/Resources/Private/Build/build.xml).

The first task will just create some directories.

<target name="init">
   <mkdir dir="${env.WORKSPACE}/build"/>
   <mkdir dir="${env.WORKSPACE}/build/phpcs"/>
   <mkdir dir="${env.WORKSPACE}/build/phpunit"/>
   <mkdir dir="${env.WORKSPACE}/typo3_core"/>
</target>

The final structure of the workspace should look like shown below.
  • build/ - contains build results 
  • jobname/ - the name of the Jenkins CI job. In this example the TYPO3 extension key
  • typo3_core/ - path for the TYPO3 core
The next task I've created is the task for the unit tests execution. I'll clone the current TYPO3 6.2 master branch, install all dependencies with composer, create typo3conf, typo3temp and uploads folder, symlink the extbase extension to typo3conf/ext/ and finally execute the unit tests.

<target name="unittests">
    <exec executable="git" failonerror="true">
        <arg line="clone --single-branch --branch master --depth 1 https://github.com/TYPO3/TYPO3.CMS.git ${env.WORKSPACE}/typo3_core" />
    </exec>

    <exec executable="composer">
        <arg line="install --working-dir ${env.WORKSPACE}/typo3_core" />
    </exec>

    <mkdir dir="${env.WORKSPACE}/typo3_core/uploads"/>
    <mkdir dir="${env.WORKSPACE}/typo3_core/typo3temp"/>
    <mkdir dir="${env.WORKSPACE}/typo3_core/typo3conf/ext"/>

    <symlink link="${env.WORKSPACE}/typo3_core/typo3conf/ext/${env.JOB_NAME}" resource="${env.WORKSPACE}/${env.JOB_NAME}"/>

    <exec executable="phpunit" dir="${env.WORKSPACE}/typo3_core">
        <arg line="--log-junit ${env.WORKSPACE}/build/phpunit/unittests.xml  --bootstrap typo3/sysext/core/Build/UnitTestsBootstrap.php typo3conf/ext/${env.JOB_NAME}/Tests/Unit" />
    </exec>
</target>

Note that I'll set the task to fail on error if the TYPO3 core could not be cloned. 

Finally I'll add some code analysis tasks and a cleanup task to remove some files from the build.

<target name="phpcs">
    <exec executable="phpcs">
        <arg line="--report=checkstyle --report-file=${env.WORKSPACE}/build/phpcs/checkstyle.xml --standard=TYPO3CMS --extensions=php,inc ${env.WORKSPACE}/${env.JOB_NAME}" />
    </exec>
</target>

<target name="phpmd">
    <exec executable="phpmd">
        <arg line=" ${env.WORKSPACE}/${env.JOB_NAME} xml codesize,unusedcode,naming,design --reportfile ${env.WORKSPACE}/build/messdetector.xml --exclude Tests/" />
    </exec>
</target>

<target name="phpcpd">
    <exec executable="phpcpd">
        <arg line=" --log-pmd ${env.WORKSPACE}/build/phpcpd.xml ${env.WORKSPACE}/${env.JOB_NAME}" />
    </exec>
</target>

<target name="cleanup">
    <delete dir="${env.WORKSPACE}/typo3_core"/>
</target>

The complete ANT build file can be found here. It should be generic so it can be used with a common ExtBase extension without any further modifications.

Update 02.01.2015

I updated the ANT build file so it also supports the execution of functional tests.

Jenkins CI job setup

The job setup on Jenkins CI is as shown on the next screenshots.

The ANT script assumes, that the job name is equal to the TYPO3 extension key. So I'll setup the job in Jenkins CI as shown above.

The job name must be TYPO3 extension key
In the SCM settings you have to make sure, that the source code is cloned to a seperate directory named like the extension key.

The ExtBase extension should be cloned in a seperate directory
Next I'll set the path to the ANT build.xml file.

ANT configuration
After the build, the code analysis should be processed.

Post build analysis


And finally the results of the phpunit tests should be evaluated.

PHPUnit result analysis

I've configured the build just to be instable, if a unit test fails (set threshold to zero). You can also configure the build to fail, if a certain amount of failed/incomplete tests are reached.

After some builds, you'll end up with a Jenkins CI job, that shows some graphs of the code analysis.

Code analysis graph
If the build contains failing tests, then the build status will become "instable" and the build will show, which tests failed.

Build with one failed test

Outlook and conclusion

As written before, the Jenkins CI job I've shown above should be seen as an simple example. I did not add any build triggers and executed the jobs manually. In a production CI environment this task should be automated, so each new commit to the repository will trigger the build.

Also I did not add any functional tests to the TYPO3 ExtBase extension, because this would require MySQL database access and would make the ANT script and the job setup more complicated. Cloning the whole TYPO3 master branch each time the job executes could also be done more simple, if you have a clone of the repository locally somewhere and just copy all files from there.

Depending on you requirements, you could also add Selenium tests (follow this article on how to setup a Selenium Grid on Jenkins CI) to the job or you could take another step forward and completely automate the deployment of the ExtBase Extension.

Anyhow, I hope I could give you a little insight in using Jenkins CI to automate some tasks a TYPO3 developer should take care of.

By the way: When I wrote this article, I did a clean installation of Jenkins CI in my home network and configured everything from scratch to see, if the example shown in this article works as expected. This all just took me about 1-2 hours until I had a working CI environment.

Monday, November 18, 2013

Howto debug a TYPO3 ExtBase extension with PhpStorm and XDebug


In this article I will show you step by step, how simple it is to setup PhpStorm and XDebug to debug a TYPO3 ExtBase extension. Of course you can also debug every other TYPO3 component with this setup.

Setup 

Before you can start with debugging, you need to setup XDebug, a debugging extension for you webbrowser and your PhpStorm project.

XDebug Setup
First you need to install XDebug on you system and add the following lines to your xdebug.ini (on Ubuntu 12.04 the file is located at /etc/php5/conf.d/xdebug.ini) configuration file.

xdebug.max_nesting_level = 500

xdebug.idekey = PHPSTORM
xdebug.remote_host = 127.0.0.1
xdebug.remote_enable = 1
xdebug.remote_port = 9000
xdebug.remote_handler = dbgp
xdebug.remote_mode = req

Make sure you restart your webserver after you have added updated the XDebug configuration file.

Browser Setup
Next you need to install a debug extension for you webbrowser. Since I use Google Chrome, I install the Xdebug helper, which is open source (on GitHub) and available on the Google Chrome Web Store.

PHPStorm Setup
Finally configure the server in you PhpStorm project settings like shown below.

Server Configuration

There are 2 important things to keep in mind.
  1. The host must not contain http:// 
  2. Symlinked files/directories must be mapped manually. On the screenshot above I map the typo3_src folder and the project-folder to to real location on my filesystem.
That's it - now you are ready to debug your TYPO3 ExtBase extension in PhpStorm.


Start debugging
Now it's time to start the debug session.

1. Enable your browser debug extension for the website you want to debug. In Chrome you just click on the debug icon.


2. Enable PhpStorm to listen to debug sessions by clicking on the icon shown below.


3. Set a breakpoint in your controller


4. Open the website on the server. PhpStorm now catches the incoming debug session and stops at the first breakpoint.


As you see on the screenshot above, PhpStorm stops at the breakpoint which has been set in step 3.

Happy debugging!


Troubleshooting

1. PhpStorm claims port 9000 is busy.
I had this error on an Ubuntu 12.04 development machine. Here php-fpm was installed and was listening on port 9000, so it was conflicting with XDebug. to resolve this problem I changed to port for php-fpm to listen to port 9001 instead by editing the configuration file /etc/php5/fpm/pool/www.conf

2. Debugger does'nt stop at breakpoint
When the debugger does'nt stop at the breakpoint, then it could be, that there is something wrong with the path mapping. I resolved this by adding xdebug_break(); to my code which resulted PhpStorm in stopping at the line with xdebug_break() and I could fix the path mappings at this point manually.


Tuesday, October 22, 2013

TYPO3 - PHPUnit Testing Framework tests for repositories with storagePids

When I develop a TYPO3 ExtBase extension, I often use the Testing Framework shipped with the TYPO3 extension PHPUnit. With the Testing Framework it is possible to create real testrecords in the TYPO3 database and use those records in your tests to verify everything works as expected.

In a project I faced the situation, that one of my repository methods did not find the records created with the Testing Framework. Well, after some hours of debugging I finally found the solution.

The problem

I created a new TYPO3 ExtBase extension with some tables, a controller and a view. Really nothing special about that. I then created a function in my repository which searches for some records in the database with a configurable limit. 


/**
 * Returns the latest records. 
 *
 * @param int $limit The Limit
 * @return array|\TYPO3\CMS\Extbase\Persistence\QueryResultInterface
 */
public function findLatest($limit) {
 $query = $this->createQuery();
 $query->setOrderings(array('datecreated' => QueryInterface::ORDER_DESCENDING));
 $query->setLimit((integer)$limit);
 $records = $query->execute();
 return $records;
}

Then I started to create some tests for the newly created function in the repository. One test was as following.


/**
 * Test if findLatest returns expected amout of records if limit given
 *
 * @test
 * @return void
 */
public function findLatestReturnsLimitedResult() {
 $this->testingFramework->createRecord('tx_myext_domain_model_table', array('datecreated' => time()));
 $this->testingFramework->createRecord('tx_myext_domain_model_table', array('datecreated' => time()));
 $this->testingFramework->createRecord('tx_myext_domain_model_table', array('datecreated' => time()));

 $this->createTestRecords();
 $this->assertEquals(2, $this->myRepository->findLatest(2)->count());
}

In the test above, 3 records with the Testing Framework are created and I'll use the function findLatest with a given limit of 2 to test, if really 2 records are returned.

Well, actually findLatest did return 0 records. I then created some real records in the TYPO3 backend and verified, that findLatest actually works as expected, so the problem must be somewhere in my test or in the TYPO3 setup.

So I started to debug my test and first of all, I verified, that the Testing Framework really created 3 records. Yes, 3 records were created, all having the pid 0. Ok then, since the testrecords where created correctly, there seem to be something wrong with the search. I'll then debugged the resulting SQL Query from the repository function findLatest and found out, that the records were searched in pid 1. OK, so the problem seems to have something to do with the storagePids.

ExtBase, tests and storagePid(s)

When you create an ExtBase extension, the Extension Builder automatically creates some TS for you where you can set the storagePid(s) for your extension.


persistence {
  # cat=plugin.tx_myext//a; type=string; label=Default storage PID
  storagePid =
}

This storagePid can be used to set the location of your records in the TYPO3 backend. Generally every TYPO3 Extension you create with the Extension Builder makes use of the storagePid(s) and overrides them, if a startingPoint is set in the plugin.

When you run your tests in TYPO3 backend (or through your IDE), ExtBase uses the backendConfigurationManager to get the ExtBase framework configuration. In the backendConfigurationManager class, there is a function called getDefaultStoragePid(), which returns the local function getCurrentPageId(). Let's have a look at this function.

protected function getCurrentPageId() {
 $pageId = (integer) \TYPO3\CMS\Core\Utility\GeneralUtility::_GP('id');
 if ($pageId > 0) {
  return $pageId;
 }
 // get current site root
 $rootPages = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid', 'pages', 'deleted=0 AND hidden=0 AND is_siteroot=1', '', '', '1');
 if (count($rootPages) > 0) {
  return $rootPages[0]['uid'];
 }
 // get root template
 $rootTemplates = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('pid', 'sys_template', 'deleted=0 AND hidden=0 AND root=1', '', '', '1');
 if (count($rootTemplates) > 0) {
  return $rootTemplates[0]['pid'];
 }
 // fallback
 return self::DEFAULT_BACKEND_STORAGE_PID;
}

So, if your TYPO3 installation where you develop your ExtBase extension has a root page, then this page ID is returned. Or if you have no root page but a TS Template which is marked as root template, then the page ID of that page is returned.

The returned page ID is used in the queryFactory class to set the storagePid(s), which leads to the situation I described earlier.

Solution / Workarounds

So how do we tell TYPO3 to search for our test records in pid 0 during tests? On solution is to set the storagePid for the ExtBase Framework to 0 like shown below.

config.tx_extbase {
  persistence {
    storagePid = 0
  }
}

This solution has some problems, since it can be overridden by other extensions and also it requires manual configuration when setting up your testing environment.

You could also just disable the check for storagePid(s) (with setRespectStoragePage(FALSE)) in your tests, but I think this solution is'nt really good, since your tests then also may find records you created in the TYPO3 backend during development.

If you want to keep your tests independent, I would recommend to set the storagePid(s) directly in the setup of the tests.

/**
 * Set up for test
 *
 * @return void
 */
public function setUp() {
 $this->testingFramework = new \Tx_Phpunit_Framework('tx_myext');
 $this->fixture = $this->objectManager->get('Derhansen\\MyExt\\Domain\\Repository\\MyRepository');

 /** @var $querySettings Typo3QuerySettings */
 $querySettings = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Typo3QuerySettings');
 $querySettings->setStoragePageIds(array(0));
 $this->fixture->setDefaultQuerySettings($querySettings);
}

The code above sets the storage pid to 0 and now the tests should find the records created with the testing framework and tests should not interfere with other records created manually.

Sunday, July 21, 2013

TYPO3 ExtBase backend module with progressbar using AJAX


Assume you have created a TYPO3 ExtBase Extension and must enable the user to import data (e.g. CSV file) to the tables of your TYPO3 ExtBase extension. With ExtBase, you can easily create a TYPO3 backend module so the user can upload the CSV file and start the data import.

Now assume the user uploads a very big set of data (several 100 MBs) to be imported and starts the data import process. Well, the user will see the hourglass a long, long time and if the user is impacient, he will surely assume that something went wrong and will click somewhere else in the TYPO3 backend and within that cancel the data import.

So would'nt it be nice if you could show the user a progressbar or an updating informal text, that the import is still running?

When you look at the concepts of some extensions with backend modules in TER, you will often see, that PHP methods like flush() or ob_flush() is used to update data in a backend module for long taking processes.

With ExtBase you can't use flush(), since the output for the backend module is rendered with fluid and the output will first display, when the action that displays the content has finished.

In this article I will show how to use AJAX in a TYPO3 ExtBase backend module to show an updating JQuery UI progressbar.



Please note, that the example code located on Github has been created with TYPO3 6.1 and uses namespaces, so it only runs with TYPO3 > 6.x. But - the shown technique can also be adapted to TYPO3 4.5.

First of all, I've created a TYPO3 extension with the extension builder. The extension has a backend module called "mod1". This module uses the controller "Example" and the action "index".

/**
 * Registers a Backend Module
 */
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::registerModule(
 'derhansen.' . $_EXTKEY,
 'web', // Make module a submodule of 'web'
 'mod1', // Submodule key
 '', // Position
 array(
  'Example' => 'index',
  
 ),
 array(
  'access' => 'user,group',
  'icon'   => 'EXT:' . $_EXTKEY . '/ext_icon.gif',
  'labels' => 'LLL:EXT:' . $_EXTKEY . '/Resources/Private/Language/locallang_mod1.xlf',
 )
);

The extension builder automatically creates Typoscript files with constants and setup settings for the backend module templates. Those settings look like:


templateRootPath = EXT:extbase_bemodule_ajax/Resources/Private/Backend/Templates/

As you may notice, the templates, layouts and partials are located in a subfolder named "Backend". Using this, you always need to include the extension's Typoscript in your sites Typoscript template. If you remove the folder "Backend" and just place your templates, layouts and partials in the "normal" folder-structure of an ExtBase extension, there is no need to include the Typoscript of your extension. I have done this to keep things simple.

Next I've created the layout and the template for the backend module. Notice, that I have created a viewhelper named IncludeJQueryViewHelper, which automatically includes JQuery and JQueryUi with the nesceccary CSS files to the backend module.


{namespace h=derhansen\ExtbaseBemoduleAjax\ViewHelpers\Be}

<h:IncludeJQuery jquery="1" jqueryui="1" />

<f:be.container loadExtJs="0" loadPrototype="0" loadScriptaculous="0">
...
</f:be.container>

Also notice, that the f:be.container viewhelper is configured to disable extJs, prototype and scriptaculous.

In the template for the backend module I have placed some text, a JQuery UI Progressbar and a JQuery UI Button. I also created some Javascript code, which starts starts the progressbar and also retrieves the status of the progressbar by AJAX.

When the start-button is clicked, an AJAX request (startLongProcess) is called which starts a long taking process in our ExampleController. The AJAX request is asynchronous, so the process is not blocking the TYPO3 backend. Right after the long taking process is started, another AJAX request (checkLongProcess) is called which retrieves the status of the long taking process and updates the progressbar.

To keep things simple, the long taking action in the ExampleController just executes a for-loop 20 times and does a sleep(1) on each iteration. Below follows both the startLongProcess action, which starts the long process and the checkLongProcess action, which is used to update the progressbar.


/**
 * Example for a long process (just loops 20 seconds). Returns TRUE if process is finished
 *
 * @return bool TRUE if process is finished
 */
public function startLongProcessAction() {
 for ( $i = 1; $i <= 20; $i++) {
  /* Increase counter stored in session variable */
  session_start();
  $_SESSION['progval'] = $i * 5;
  session_write_close ();
  sleep(1);
 }

 /* Reset the counter in session variable to 0 */
 session_start();
 $_SESSION['progval'] = 0;
 session_write_close ();
 return json_encode(TRUE);
}

/**
 * Checks the status of the long process
 *
 * @return int Status of process in percent
 */
public function checkLongProcessAction() {
 session_start();
 if (!isset($_SESSION['progval'])) {
  $_SESSION['progval'] = 0;
 }
 session_write_close ();
 return json_encode($_SESSION['progval']);
}

Notice, that this example uses PHP session variables to store the actual state of the long taking process. You can also use a database or other techniques to store the actual state.

When working with PHP session variables inside a method, you have to keep in mind, that the session variable is stored, after the method is finished to prevent concurrent writes to the session. To store the session variable while the for-loop is running, you have to use session_write_close() to actually store the session variable.

Finally I updated ext_tables.php so the 2 new actions can be called by the module.

Conclusion
Creating a ExtBase backend module that uses AJAX to dynamically update content on the modules page is quite simple. You can use the same techniques for backend modules as for TYPO3 frontend plugins.

The complete code for the example shown here is available on Github

Saturday, May 4, 2013

TYPO3 Extbase - own validators and multi step form validation using the old and new property mapper

TYPO3 Extbase comes with some standard validators which can be used to validate user input. When working with domain models, you can use those validators to validate the properties of the domain model.

When you use Extbase to create a form, where some part of the validation is done through an external API (e.g. logically validation) or you want to validate properties against other properties, the validation process can be more complicated. If you have a multiple step form, where all user input is collected, not persisted and finally sent to an external API which validates the input, it can be even more complicated to "jump back" to the desired step of the multiple step form and output the validation errors of the external API.

In this article I will show how to use Extbase validators to validiate a domain model and add several error messages for validation errors at once. I will also show how to display error messages for desired fields in a multiple step form after the validation process via @validate has been performed.

Besides this, the article also shows how to create a multiple step form in Extbase and how to handle validation and persistence.

At the time of writing of this article, TYPO3 6.1 with Extbase 6.1 was released. In Extbase 6.1, the new property mapper is enabled by default.

This article covers both the new and the old property mapper. I have created 2 GitHub repositories, which include all examples for the old and the new property mapper.
The code examples in this article are may be incomplete to save space. Please visit the GitHub repositories mentioned above to see the complete code.

Which property mapper to use - old or new one?

Writing this article, I spent some time with the validation classes of Extbase. Since Extbase 1.4, a lot of things like Tx_Extbase_MVC_Controller_ArgumentError or the $errors array in Tx_Extbase_Validation_Validator_AbstractValidator became deprecated and should be removed in TYPO3 6.0. Well, in TYPO3 6.0, those classed still existed and the deprecation notice now mentioned, that they will be removed in TYPO3 6.1. Some kind of confusing, I thought. Finally, as TYPO3 6.1 came out, the deprecation notice showed, that the deprecated stuff will be removed two versions after TYPO3 6.1 (so it will "survive" TYPO3 6.2 LTS). I guess, this is due to keep the backward compatibility to the upcoming LTS version of TYPO3 as high as possible.

For those who are unsure which property mapper to use, I recommend the following. If you create a new TYPO3 extension for TYPO3 6.0 or greater - use the new property mapper. It is configurable and extensible and ensures, that you don't use deprecated functions and classes.


Creating an own validator with validation errors for multiple properties

First I will show you how to create an own validator, which validates a given domain model and is able to add errors for multiple properties. The validator checks, if the given ZIP-code and city-name do match logically (e.g. for the ZIP "20095" the city name must be "Hamburg")

Assume you have a domain model "addressdata", which contains fields for a users addressdata. Straight validation like "Empty" or "Numeric" can is implemented in the domain model by using @validate annotations.

To implement the logical validation, I create a new validator in ExtBase.

Old property mapper

/**
 * Validates the given value
 *
 * @param mixed $value
 *
 * @return bool
 */
public function isValid($value) {
 $apiValidationResult = $this->apiService->validateAddressData($value);
 $success = TRUE;
 if ($apiValidationResult['zip']) {
  $error = $this->objectManager->get('Tx_Extbase_Validation_Error', $apiValidationResult['zip'], time());
  $this->errors['zip'] = $this->objectManager->get('Tx_Extbase_Validation_PropertyError', 'zip');
  $this->errors['zip']->addErrors(array($error));
  $success = FALSE;
 }
 if ($apiValidationResult['city']) {
  $error = $this->objectManager->get('Tx_Extbase_Validation_Error', $apiValidationResult['city'], time());
  $this->errors['city'] = $this->objectManager->get('Tx_Extbase_Validation_PropertyError', 'city');
  $this->errors['city']->addErrors(array($error));
  $success = FALSE;
 }
 return $success;
}

New property mapper

/**
 * Validates the given value
 *
 * @param mixed $value
 * @return bool
 */
protected function isValid($value) {
 $apiValidationResult = $this->apiService->validateAddressData($value);
 $success = TRUE;
 if ($apiValidationResult['zip']) {
  $error = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Validation\\Error',
   $apiValidationResult['zip'], time());
  $this->result->forProperty('zip')->addError($error);
  $success = FALSE;
 }
 if ($apiValidationResult['city']) {
  $error = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Validation\\Error',
   $apiValidationResult['city'], time());
  $this->result->forProperty('city')->addError($error);
  $success = FALSE;
 }
 return $success;
}


The code above shows, that an external API is used to validate the adress data logically. If the external API returns errors for given fields, errors are manually added for each property to the ExtBase validator.

To use the newly created validator, you just have to use the @validate annotation in your action like shown below.

Old property mapper

/**
 * Create action
 *
 * @param Tx_ValidationExamples_Domain_Model_Addressdata $newAddressdata
 * @validate $newAddressdata Tx_ValidationExamples_Validation_Validator_AddressdataValidator
 * @return void
 */
public function createAction(Tx_ValidationExamples_Domain_Model_Addressdata $newAddressdata) {
 $this->addressdataRepository->add($newAddressdata);
 $this->view->assign('message', 'Addressdata has been created');
}

New property mapper

/**
 * Create action
 *
 * @param \derhansen\ValidationExamplesNew\Domain\Model\Addressdata $newAddressdata
 * @validate $newAddressdata \derhansen\ValidationExamplesNew\Validation\Validator\AddressdataValidator
 * @return void
 */
public function createAction(\derhansen\ValidationExamplesNew\Domain\Model\Addressdata $newAddressdata) {
 $this->addressdataRepository->add($newAddressdata);
 $this->view->assign('message', 'Your new Addressdata was created.');
}

The complete source for this example has been tagged in the Github repository. Below follows direct links to the tags.

Adding custom validation errors in a multiple step form after extbase domain object validation

Sometimes the validation of a form can't be implemented by using @validate annotations. Assume you have a multiple step form, where you just collect user input and validate it using an external API in the last step of your form.

There are several approaches to create multiple step forms in Extbase. For this article I use the approach of splitting the main domain model into several small part-domain models, saving them to session variables after each step and consolidate them in the end to the main domain-object which gets persisted.

Below is a chart of the multiple step form validation process I'm going to create.



One advantage of splitting the main domain model to several small part domain models is the fact, that you can use @validation directly in the domain model without caring about the actual step of the form, where you switch validation for single properties on or off.

I created a 3 step form to enter some addressdata. The first step requires first- and lastname, the second step requires the street and streetnumber and the third step requires the zip-code and the city. When all form data has been collected, a new addressdata object is persisted to the database.

The first version of the multiple step form is tagged in the GitHub repository as example2. It includes the main validation of Extbase and is able to save the form data, when no domain model validation errors are present.
Please note, that the example2-tag for the old property mapper misses this code change, which I first discovered after the repository has been tagged.

Now I've implemented the external API service, which does some logical validation for the given address data.

/**
 * Simulates validation of addressdata entered in the multiple steps form.
 * Returns an array of validation errors for each step of the multiple steps form
 *
 * @param Tx_ValidationExamples_Domain_Model_Addressdata $addressdata
 * @return array
 */
public function validateMultipleSteps(Tx_ValidationExamples_Domain_Model_Addressdata $addressdata) {
 $errors = array();
 if ($addressdata->getStreet() == 'Elbstraße' && $addressdata->getStreetnr() > 145) {
  $errors['step2']['streetnr'] = 'Streetnr not valid for this street';
 }
 if ($addressdata->getZip() == 20095 && $addressdata->getCity() != 'Hamburg') {
  $errors['step3']['zip'] = 'ZIP Code and city do not match';
  $errors['step3']['city'] = 'ZIP Code and city do not match';
 }
 return $errors;
}

The call to the API service is implemented in the createAction() for the form. If the API service returns errors for some fields, then the createAction() saves the validation result to a session variable and redirects the user to the desired step in the multiple step form.

In the action for the given step, I've implemented a check for the validation results of the API service. This check sets validation errors to the given properties of the domain model. If there already are validation errors for the domain model, the new ones from the external API validation are added.

Old property mapper


/**
 * Sets validation errors for fields in the given step
 *
 * @param string $step The step
 * @return void
 */
protected function setApiValidationErrors($step) {
 $apiresults = $GLOBALS['TSFE']->fe_user->getKey('ses', 'apiresults');
 if (array_key_exists($step, $apiresults)) {
  /* Set Form Errors manually */
  $origErrors = $this->controllerContext->getRequest()->getErrors();
  if ($origErrors) {
   $errors = $origErrors[$step . 'data'];
  } else {
   $errors = $this->objectManager->get('Tx_Extbase_MVC_Controller_ArgumentError' ,$step . 'data');
  }

  $propertyErrors = array();

  /* Add validation errors */
  foreach ($apiresults[$step] as $key => $value) {
   $propertyErrors[$key] = $this->objectManager->get('Tx_Extbase_Validation_PropertyError', $key);
   $message = $apiresults[$step][$key];
   $propertyError = $this->objectManager->get('Tx_Extbase_Validation_Error', $message, time());
   $propertyErrors[$key]->addErrors(array($propertyError));
  }
  $errors->addErrors($propertyErrors);

  $this->controllerContext->getRequest()->setErrors(array($errors));
 }
}

New property mapper


/**
 * Sets validation errors for fields in the given step
 *
 * @param string $step The step
 * @return void
 */
protected function setApiValidationErrors($step) {
 $apiresults = $GLOBALS['TSFE']->fe_user->getKey('ses', 'apiresults');
 if (array_key_exists($step, $apiresults)) {
  /* Set Form Errors manually  - get results from property mapper and add new errors */
  $result = $this->getControllerContext()->getRequest()->getOriginalRequestMappingResults();

  /* Add validation errors */
  foreach ($apiresults[$step] as $key => $value) {
   $error = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Validation\Error',
    $apiresults[$step][$key], time());
   $result->forProperty($step . 'data.' . $key)->addError($error);
  }
  $this->getControllerContext()->getRequest()->setOriginalRequestMappingResults($result);
 }
}

Since the code above is specially made for handling multiple steps / fields (like this example), below follows a more common example which shows how to set a validation error for a special property of a domain object.

Old property mapper


/* Set validation error for property */
$errors = $this->objectManager->get('Tx_Extbase_MVC_Controller_ArgumentError', 'addressdata'); 

$propertyErrors = array();

$propertyErrors['streetnr'] = $this->objectManager->get('Tx_Extbase_Validation_PropertyError', 'streetnr');
$message = 'Validation message for streetnr';
$propertyError = $this->objectManager->get('Tx_Extbase_Validation_Error', $message, time());
$propertyErrors['streetnr']->addErrors(array($propertyError));

$errors->addErrors($propertyErrors);

$this->controllerContext->getRequest()->setErrors(array($errors));

New property mapper

$result = $this->getControllerContext()->getRequest()->getOriginalRequestMappingResults();
$error = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Validation\Error', 'Validation message for streetnr', time());
$result->forProperty('addressdata.streetnr')->addError($error);
$this->getControllerContext()->getRequest()->setOriginalRequestMappingResults($result);

This code adds an error for the domain object "addressdata" and sets a single validation message for the property "streetnr".

The final version of the multiple step form is tagged in the GitHub repository as example3.

Conclusion

Using the techniques shown above gives you flexibility when working with Extbase and external validation services. It also shows how to set validation errors for multiple properties at once and how to control validation results after the property mapper has processed domain validation.

As you may have noticed, the examples for the new property mapper in Extbase look more clear, contains lesser code and are better readable, since it does not use arrays to collect validation errors but objects.


Tuesday, April 23, 2013

Asynchronous banner management for TYPO3

Today I published my banner management extension sf_banners for TYPO3. It is able to show image, flash and HTML banners on a TYPO3 website. Each banner contains a statistic which shows the banners' impressions and clicks. The banners can be limited to an maximum amount of clicks/impressions and you can control the date on which the banners are shown by using the TYPO3 start- and stop function.


One of the main features of the extension is the ability to load banners asynchronously, so the main load time af a page is not being affected by the plugins rendering process.


The extension has been developed using Extbase and Fluid to ensure compatibility to existing and future TYPO3 versions. Also test driven development was one of the main aspects in the development process to ensure, that new features and code changes do not break existing functionality. The extension has been tested with all current versions of TYPO3 from 4.5.x to 6.0.x

If you have any comments or suggestions, feel free to post them on the extensions GitHub projectpage.

Development process

Below follows a short summary about the development process of the extension.

The first approach of the extension was to use pure Extbase/Fluid functionality to display the banners on a page. Since the extension has to update impressions and also has to select the banners from the repository on each request, the plugin has to be non-cached. After having finished this approach, I was disappointed by the performance of the page rendering time. As I tested the extension on several TYPO3 versions, I also found out, that the page rendering time decreased the higher the TYPO3 version got.

So I read a lot of discussions on the TYPO3 mailinglists and the internet about Extbase and performance tuning and ended up with the solution to load all banners asynchronously by Ajax. To do so, I implemented JQuery and added an action to the controller which delivered the banners content as pure HTML. After that, everything seemed to run fine. Since the plugin now was cached and content fetched by Ajax, the page load time was'nt mainly affected by the extension. Sadly my integration tests showed, that there were problems with HTML/JS banners containing document.write JavaScript code. As the banners HTML/JS code was loaded asynchronously, a document.write statement would be executed after the page DOM is loaded. The result was, that the main page was loaded and shortly after that, the HTML/JS banner was shown and the formerly rendered page output was completely removed.

The solution to get rid of the document.write problem was postscribe. This standalone JS library overrides document.write and enables the usage of document.write after the DOM is ready.

All development steps are filed on GitHub and you can look at each of the approaches described above, as the different steps have been tagged.