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.




Wednesday, January 25, 2017

TYPO3 - Adding direct mail fields to femanager

In a project I needed to add the direct mail fields "Activate Newsletter" and "Subscribe to categories" to the TYPO3 femanager (thanks to Alex Kellner for this great extension), so frontend users are able to subscribe to a newsletter and select newsletter categories.

Since femanager is created with Extbase, it is easily extendable and I created a small TYPO3 extension named femanager_dmail_subscribe, that automatically adds "Newsletter subscription", "Newsletter category" and "HTML newsletter" direct mail fields to femanager, so editors can select the direct mail fields a frontend user should be able to edit.

femanager plugin field settings

In order to display direct mail categories in the frontend, it is required to add the sysfolder with the direct mail categories to the femanager record storage page.

femanager plugin record storage page
After installing and configuring the extension as shown above, frontend users can edit the selected fields (see screenshot below)

Frontend user can edit direct mail fields

I uploaded 2 versions of the extension to TER. Version 1.0.0 is compatible with TYPO3 6.2 and femanager 1.5.2 and version 2.0.0 is compatible with TYPO3 7.6 and femanager 2.x