I have a little form, with just a file field to upload a document. I'm using Symfony2.6 with mongodb annotation. I get a "No mapping found for field 'file'" exception.
My document class :
namespace My\Bundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #MongoDB\Document
*/
class ImportFile
{
[...]
/**
* #Assert\File(maxSize = "5M", mimeTypes = {"image/jpeg", "image/gif", "image/png"})
*/
protected $file;
[...]
/**
* #return $file
*/
public function getFile()
{
return $this->file;
}
/**
* #param $file
*/
public function setFile($file)
{
$this->file = $file;
}
(the namespace is correct, i changed it for the post)
Here is my controller with my form builder :
$importFile = new ImportFile();
$form = $this->createFormBuilder($importFile)
->add('file')
->getForm();
The file field should be automatically detected (as it mentioned here http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html) but it doesn't work. If i add:
$form = $this->createFormBuilder($importFile)
->add('file','file')
->getForm();
it works, but i should'nt have to add the file type as it should be automatically detected. what am i doing wrong ?
I think the problem is in your annotation. You added just an assert but no field definition:
/**
* #Field(type="file")
* #Assert\File(maxSize = "5M", mimeTypes = {"image/jpeg", "image/gif", "image/png"})
*/
I hope it helps.
As you mention here:
I don't want this field to be mapped in the database
You should use mapped property at form field definition:
mapped => false
So, this should resolved your problem ( but remeber that after submit, value from file property will not be mapped with your odm Document ):
$form = $this->createFormBuilder($importFile)
->add('file', 'file', array(
'mapped' => false
))
->getForm();
More here: http://symfony.com/doc/current/reference/forms/types/text.html#mapped
Related
I have slug field in my TCA and in general it works, when adding via Backend > List module, even if I won't input any value the unique eval ensures that slug will be unique, so when I'll create many rows with the same name Foo TYPO3 backend will enshure that it will resolve to unique slugs like foo, foo-1, foo-2, etc. Kudos!:
'slug' => [
'exclude' => true,
'label' => 'Slug',
'displayCond' => 'VERSION:IS:false',
'config' => [
'type' => 'slug',
'generatorOptions' => [
'fields' => ['name'],
'fieldSeparator' => '/',
'replacements' => [
'/' => '',
],
],
'fallbackCharacter' => '-',
'eval' => 'unique',
'default' => '',
'appearance' => [
'prefix' => \BIESIOR\Garage\UserFunctions\SlugPrefix::class . '->getPrefix'
],
],
],
However when creating a new object from my form within new/create actions (typical Extbase CRUD from extension_builder as you can see) like:
public function createAction(Car $newCar)
{
$this->addFlashMessage(
'The object was created. Please be aware that this action is publicly accessible unless you implement an access check. See https://docs.typo3.org/typo3cms/extensions/extension_builder/User/Index.html',
'',
\TYPO3\CMS\Core\Messaging\AbstractMessage::WARNING);
$this->carRepository->add($newCar);
$this->redirect('list');
}
of course slug is note set.
My first idea is to duplicate the logic of TCA type='slug' and just add this functionality with some own JS, AJAX and PHP, however that sounds as overload and time consumption. Especially that I don't want the user to care about slug part at all. Is there any simple API for lookup for a unique slug of the given table that can be used in custom action instead?
Note this question is not about how to handle it with JS, that's just concept. I would like to skip this part for FE user at all, he doesn't need to know what the slug is. Just during creating a new object, I want to get unique value like foo-123 instead.
In addition to Jonas Eberles answer here's another example which also respects the eval configuration of the slug field (can be uniqueInSite, uniqueInPid or simply unique).
use TYPO3\CMS\Core\DataHandling\Model\RecordStateFactory;
use TYPO3\CMS\Core\DataHandling\SlugHelper;
use TYPO3\CMS\Core\Utility\GeneralUtility;
...
public function createAction(Car $newCar)
{
$this->carRepository->add($newCar);
GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager::class)->persistAll();
$record = $this->carRepository->findByUidAssoc($newCar->getUid())[0];
$tableName = 'tx_garage_domain_model_car';
$slugFieldName = 'slug';
// Get field configuration
$fieldConfig = $GLOBALS['TCA'][$tableName]['columns'][$slugFieldName]['config'];
$evalInfo = GeneralUtility::trimExplode(',', $fieldConfig['eval'], true);
// Initialize Slug helper
/** #var SlugHelper $slugHelper */
$slugHelper = GeneralUtility::makeInstance(
SlugHelper::class,
$tableName,
$slugFieldName,
$fieldConfig
);
// Generate slug
$slug = $slugHelper->generate($record, $record['pid']);
$state = RecordStateFactory::forName($tableName)
->fromArray($record, $record['pid'], $record['uid']);
// Build slug depending on eval configuration
if (in_array('uniqueInSite', $evalInfo)) {
$slug = $slugHelper->buildSlugForUniqueInSite($slug, $state);
} else if (in_array('uniqueInPid', $evalInfo)) {
$slug = $slugHelper->buildSlugForUniqueInPid($slug, $state);
} else if (in_array('unique', $evalInfo)) {
$slug = $slugHelper->buildSlugForUniqueInTable($slug, $state);
}
$newCar->setSlug($slug);
$this->carRepository->update($newCar);
}
with custom finder in the repository to fetch assoc array instead of the mapped object for $racord argument
public function findByUidAssoc($uid)
{
$query = $this->createQuery();
$query->matching(
$query->equals('uid', $uid)
);
return $query->execute(true)[0];
}
Note that the record needs to be persisted before executing above code.
References:
SlugHelper::generate
SlugHelper::buildSlugForUniqueInSite
SlugHelper::buildSlugForUniqueInPid
SlugHelper::buildSlugForUniqueInTable
According to answers from Elias and Jonas, I created a class which simplifies things especially when you have more models to handle
typo3conf/ext/sitepackage/Classes/Utility/SlugUtility.php
<?php
namespace VENDOR\Sitepackage\Utility; // <- to be replaced with your namespace
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\DataHandling\Model\RecordStateFactory;
use TYPO3\CMS\Core\DataHandling\SlugHelper;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/***
*
* This file is part of the "Sitepackage" Extension for TYPO3 CMS.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* (c) 2020 Marcus Biesioroff <biesior#gmail.com>
* Concept by: Elias Häußler
* Jonas Eberle
*
***/
class SlugUtility
{
/**
* #param int $uid UID of record saved in DB
* #param string $tableName Name of the table to lookup for uniques
* #param string $slugFieldName Name of the slug field
*
* #return string Resolved unique slug
* #throws \TYPO3\CMS\Core\Exception\SiteNotFoundException
*/
public static function generateUniqueSlug(int $uid, string $tableName, string $slugFieldName): string
{
/** #var Connection $connection */
$connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable($tableName);
$queryBuilder = $connection->createQueryBuilder();
$record = $queryBuilder
->select('*')
->from($tableName)
->where('uid=:uid')
->setParameter(':uid', $uid)
->execute()
->fetch();
if (!$record) return false;
// Get field configuration
$fieldConfig = $GLOBALS['TCA'][$tableName]['columns'][$slugFieldName]['config'];
$evalInfo = GeneralUtility::trimExplode(',', $fieldConfig['eval'], true);
// Initialize Slug helper
/** #var SlugHelper $slugHelper */
$slugHelper = GeneralUtility::makeInstance(
SlugHelper::class,
$tableName,
$slugFieldName,
$fieldConfig
);
// Generate slug
$slug = $slugHelper->generate($record, $record['pid']);
$state = RecordStateFactory::forName($tableName)
->fromArray($record, $record['pid'], $record['uid']);
// Build slug depending on eval configuration
if (in_array('uniqueInSite', $evalInfo)) {
$slug = $slugHelper->buildSlugForUniqueInSite($slug, $state);
} else if (in_array('uniqueInPid', $evalInfo)) {
$slug = $slugHelper->buildSlugForUniqueInPid($slug, $state);
} else if (in_array('unique', $evalInfo)) {
$slug = $slugHelper->buildSlugForUniqueInTable($slug, $state);
}
return $slug;
}
}
Usage in any place, like controller. Scheduler task, repository, etc. Keep in mind that record should be saved before (it may be created by Extbase, or just with plain SQL), just need to have created uid and be valid TYPO3 record.
use VENDOR\Sitepackage\Utility\SlugUtility;
use \TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager;
...
$pageSlug = SlugUtility::generateUniqueSlug(
5, // int $uid UID of record saved in DB
'pages', // string $tableName Name of the table to lookup for uniques
'slug' // string $slugFieldName Name of the slug field
)
// or
$uniqueSlug = SlugUtility::generateUniqueSlug(
123,
'tx_garage_domain_model_car',
'slug'
);
// or according to the original question,
// if you created new model object with Extbase,
// persist it, create unique slug with SlugUtility
// set the slug property to the created model object and finally update
public function createAction(Car $newCar)
{
$this->carRepository->add($newCar);
GeneralUtility::makeInstance(PersistenceManager::class)->persistAll();
$uniqueSlug = SlugUtility::generateUniqueSlug(
$newCar->getUid(),
'tx_garage_domain_model_car',
'slug'
);
if($uniqueSlug) {
$newCar->setSlug($uniqueSlug);
$this->carRepository->update($newCar);
}
$this->redirect('list');
}
// no need for second call to persistAll()
// as Extbase will call it at action's finalizing.
// etc.
You can use the SlugHelper directly. The API was obviously not made very fluent for that use case but it works...
$this->carRepository->add($newCar);
// probably you need to persist first - I am not sure if this is really necessary
$this->objectManager()->get(
\TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager::class
)->persistAll();
$table = 'tx_garage_domain_model_car';
$field = 'slug';
// a stripped down record with just the necessary fields is enough
$record = ['name' => $newCar->getName()];
$pid = $this->settings->persistence->...
$slugHelper = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
\TYPO3\CMS\Core\DataHandling\SlugHelper::class,
$table,
$field,
$GLOBALS['TCA'][$table]['columns'][$field]['config']
);
$newCar->slug = $slugHelper->generate($record, $pid);
I have to implement a "Book" management in the Backend. Each book has a PDF preview, a title, description and so on...
The BE user should be able to upload a PDF and set a title, description etc. through a Backend module.
The created Book should be selectable in a plugin (or content element ?) so it can be display in the frontend.
Also, the uploaded PDF should only be downloadable by a certain group of FE users.
I don't know how to handle the upload part in the backend. I didn't find much info online beside this upload example: https://github.com/helhum/upload_example it seems quite complex and I'm not sure if it's the best solution for me.
What would be the best way to proceed for my task ?
Use File Abstraction Layer (FAL). You don't need the example in backend, but it's great for frontend upload.
Domain/Model/Book.php
...
/**
* File (file references)
*
* #var \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\TYPO3\CMS\Extbase\Domain\Model\FileReference>
* #lazy
*/
protected $files = NULL;
/**
* Construct
*
*
*/
public function __construct() {
//Do not remove the next line: It would break the functionality
$this->initStorageObjects();
}
/**
* Initializes all ObjectStorage properties
* Do not modify this method!
* It will be rewritten on each save in the extension builder
* You may modify the constructor of this class instead
*
* #return void
*/
protected function initStorageObjects() {
$this->files = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();
}
/**
* Set files (file references)
*
* #param \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\TYPO3\CMS\Extbase\Domain\Model\FileReference> $files
* #return void
*/
public function setFiles(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $files) {
$this->files = $files;
}
/**
* Get files (file references)
*
* #return \TYPO3\CMS\Extbase\Persistence\ObjectStorage<\TYPO3\CMS\Extbase\Domain\Model\FileReference> $files
*/
public function getFiles() {
return $this->files;
}
...
TCA/tx_yourextension_domain_model_book.php
...
'files' => [
'label' => 'LLL:EXT:werkhandkunst/Resources/Private/Language/locallang_db.xlf:file',
'config' => \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::getFileFieldTCAConfig(
'files', ['
maxitems' => 25,
],
$GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext']
),
],
...
ext_tables.sql
CREATE TABLE tx_yourextension_domain_model_book (
...
files int(11) unsigned DEFAULT '0' NOT NULL,
...
)
I have a simple class:
class Type
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=15)
*/
private $name;
...
}
And have a some 'type' objects in database.
So, if i want to change one of them, i create new controller rule (like /types/edit/{id}) and new action:
public function typesEditViewAction($id)
{
...
$editedType = new Type();
$form = $this->createFormBuilder($editedType)
->add('name', 'text')
->add('id', 'hidden', array('data' => $id))
->getForm();
// send form to twig template
...
}
After that, i create another controller rule (like /types/do_edit) and action:
public function typesEditAction(Request $request)
{
...
$editedType = new Type();
$form = $this->createFormBuilder($editedType)
->add('name', 'text')
->add('id', 'hidden')
->getForm();
$form->bind($request); // <--- ERROR THERE !!!
// change 'type' object in db
...
}
And i found a small problem there.
Сlass 'Type' doesn't have аuto-generated setter setId() and on binding i got error.
Neither the property "id" nor one of the methods "setId()", "__set()" or "__call()" exist and have public access in class "Lan\CsmBundle\Entity\Type".
Now, i remove 'id' field from symfony2 form object ($form) and transmit it manually to template.
At second controller's action i have $form object and 'id'-field apart.
I don't know a 'proper'-way for doing that (updating 'type' class). Please help.
Symfony has an integrated ParamConverter which automatically fetches your entity from database and throws an Exception ( which you can catch in a listener ) if the entity is not found.
You can easily handle GET and POST requests in one controller method.
make sure you have the public getters and setters for your properties in your entity.
I added annotations to make the routing clearer and still have a working example.
use Vendor\YourBundle\Entity\Type;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
// ...
/**
* #Route("/edit/{id}", requirements={"id" = "\d+"})
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, Type $type)
{
$form = $this->createFormBuilder($type)
->add('name', 'text')
->add('id', 'hidden')
->getForm()
;
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getEntityManager();
$em->flush(); // entity is already persisted and managed by doctrine.
// return success response
}
}
// return the form ( will include the errors if validation failed )
}
I strongly suggest you should create a form type to further simplify your controller.
For anyone else stumbling on this where you added the ID field to your FormType because the frontend needed it you can just set the ID column to "not-mapped" like so:
->add('my_field', 'hidden', ['mapped'=>false])
and it prevents the ID value trying to get used by the form processing method.
In my extbase model, I created getters and setters for the fields t3_origuid, sys_language_uid, and l10n_parent.
When setting these fields and persisting, only the l10n_parent field is updated in the database. Is it possible to change the other fields, without manually querying the database of course.
To set sys_language_uid through extbase you need to use the internal API AbstractDomainObject::_setProperty() with $entity->_setProperty('_languageUid', $languageUid) where $languageUid would be the id of your langage record. You will find a more complete example on forge: https://forge.typo3.org/issues/61722.
You could also use this small service I've written to translate any domain object easily:
<?php
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface;
use TYPO3\CMS\Extbase\Persistence\Generic\Mapper\ColumnMap;
use TYPO3\CMS\Core\SingletonInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;
/**
* Provides services to translate domain objects
*/
class TranslationService implements SingletonInterface {
/**
* #var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper
* #inject
*/
protected $dataMapper;
/**
* Translates a domain object
*
* #param DomainObjectInterface $origin
* #param DomainObjectInterface $translation
* #param int $language
* #throws \Exception
* #return void
*/
public function translate(DomainObjectInterface $origin, DomainObjectInterface $translation, $language) {
if (get_class($origin) !== get_class($translation)) {
throw new \Exception('Origin and translation must be the same type.', 1432499926);
}
$dataMap = $this->dataMapper->getDataMap(get_class($origin));
if (!$dataMap->getTranslationOriginColumnName()) {
throw new \Exception('The type is not translatable.', 1432500079);
}
if ($origin === $translation) {
throw new \Exception('Origin can\'t be translation of its own.', 1432502696);
}
$propertyName = GeneralUtility::underscoredToLowerCamelCase($dataMap->getTranslationOriginColumnName());
if ($translation->_setProperty($propertyName, $origin) === FALSE) {
$columnMap = $dataMap->getColumnMap($propertyName);
$columnMap->setTypeOfRelation(ColumnMap::RELATION_HAS_ONE);
$columnMap->setType($dataMap->getClassName());
$columnMap->setChildTableName($dataMap->getTableName());
$translation->{$propertyName} = $origin;
}
$translation->_setProperty('_languageUid', $language);
}
}
You have define your fields in the TCA.
'sys_language_uid' => array(
'config' => array(
'type' => 'passthrough'
)
)
And the same for the other fields...
there are some tutorials in the web for mapping tables of typo3 with extbase.
this tutorial is in german, but the code speaks for itself.
I'm building a Zend Framework 1.11.11 application and would like to make the routes and content database driven.
I've written a FrontController Plugin that retrieves the 'paths' from the database and creates an entry in the Router for each one, with the associated controller and action.
However, I'd like to be able to use 'aliases' - a URL that behaves like a normal URL, but is an alias.
For example, if I create the following:
// Create the Zend Route
$entry = new Zend_Controller_Router_Route_Static(
$route->getUrl(), // The string/url to match
array('controller' => $route->getControllers()->getName(),
'action' => $route->getActions()->getName())
);
// Add the route to the router
$router->addRoute($route->getUrl(), $entry);
Then a route for /about/ for example can goto the staticController, indexAction.
However, what's the best way for me to create an alias of this route? So if I went to /abt/ it would render the same Controller and Action?
To me it doesn't make sense to recreate the same route as I'll be using the route as the page 'identifier' to then load content from the database for the page...
you can extend static router:
class My_Route_ArrayStatic extends Zend_Controller_Router_Route_Static
{
protected $_routes = array();
/**
* Prepares the array of routes for mapping
* first route in array will become primary, all others
* aliases
*
* #param array $routes array of routes
* #param array $defaults
*/
public function __construct(array $routes, $defaults = array())
{
$this->_routes = $routes;
$route = reset($routes);
parent::__construct($route, $defaults);
}
/**
* Matches a user submitted path with a previously specified array of routes
*
* #param string $path
* #param boolean $partial
* #return array|false
*/
public function match($path, $partial = false)
{
$return = false;
foreach ($this->_routes as $route) {
$this->setRoute($route);
$success = parent::match($path, $partial);
if (false !== $success) {
$return = $success;
break;
}
}
$this->setRoute(reset($this->_routes));
return $return;
}
public function setRoute($route)
{
$this->_route = trim($route, '/');
}
}
and add new router this way:
$r = My_Route_ArrayStatic(array('about', 'abt'), $defaults);