Add data to TYPO3 Repository Extbase - typo3

I want to develop an extension for TYPO3 6.2.
In the controller class I created a action called "fetchFeUsersAction".
This action loads a set of data from the table fe_users in the table which was created from the extensionbuilder from the model.
The function to the get the users in the Repository looks like this:
public function getFeUsers()
{
/** #var Query $q */
$q = $this->createQuery();
$q->statement('SELECT * from fe_users');
$data = $q->execute(true);
return $data;
}
This works very fine.
But now I want to store the results from the table fe_users in my model with this action:
public function fetchFeUsersAction()
{
$data = $this->adressRepo->getFeUsers();
foreach ($data as $feuser) {
/** #var Adresse $address */
$address = $this->objectManager->get(Adresse::class);
$q= $this->adressRepo->createQuery();
$q->matching(contains('email', $feuser['email']));
$contain= $q->execute();
if($contain==NULL){
$address->setEmail($feuser['email']);
$this->adressRepo->add($address);
}
}
$this->redirect('list');
}
Here I want to check if the email adress is already stored in my table.
If the email adress is not stored it should be added to the model.
But it doesnt work. Even with an empty table. Without the condition it works very fine.

Extbase persists the complete data into the DB later. You need to persist manually i think, like this:
/** #var \TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager */
$persistenceManager = GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager::class);
$persistenceManager->persistAll();
Not currently tested, just copied it from my of my extensions. but in there i had the same problem to check if it exists.
Hope this helps a little bit.

Related

Sanitize user-input in TYPO3 repository function needed?

I have a TYPO3 repository function that create a like-query.
I wonder, if I have to sanitize the user input to prevent sql-injection and if so, how.
I read s.th. that this is automatically done by the doctrine layer.
I'm on TYPO3 9.5.
Please advice.
Here is my repository-class together with the function:
class ProductRepository extends \TYPO3\CMS\Extbase\Persistence\Repository
{
/**
* find
*
* #return Tx_Extbase_Persistence_QueryResult
*/
public function findAllLike( $name) {
$query = $this->createQuery();
$orConstraints = array();
$orConstraints[] = $query->like('productname', '%'.$name.'%');
$orConstraints[] = $query->like('tradename','%'.$name.'%');
$constraints[] = $query->logicalOr($orConstraints);
return $query->matching($query->logicalAnd($constraints))->execute();
}
Yes you have to escape your like query
see the documentation on TYPO3 Querybuilder
https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ApiOverview/Database/QueryBuilder/Index.html#database-query-builder-escape-like-wildcards

TYPO3 FileReference repository query search through file name

I have made a 'document' model which contains a field 'file' which is a FileReference. Now im working on a repository query function that retrieves all documents containing certain string in the files name ( using $query->like() for this ). However I run against the following error:
When ever I disable this $query->like and I debug the 'document' that I receive it looks like the relation information regarding the field 'uidLocal' is correct because I receive the name of the file.
Some more code im using:
class FileReference extends \TYPO3\CMS\Extbase\Domain\Model\FileReference
{
/**
* #var \**\***\Domain\Model\File
*/
protected $uidLocal;
/**
* #param \**\***\Domain\Model\File $uidLocal
* #return void
*/
public function setUidLocal($uidLocal)
{
$this->uidLocal = $uidLocal;
}
/**
* #return \**\***\Domain\Model\File
*/
public function getUidLocal()
{
return $this->uidLocal;
}
}
The repository query:
$query->matching(
$query->logicalAnd(
$query->greaterThanOrEqual('crdate', $from),
$query->contains('usergroups', $participant),
// TODO: Onderstaande check moet aan maar resulteerd in error..
$query->like('file.uidLocal.name', '%'.$filename.'_'.$type.'.%')
)
);
Now I can ofcourse filter the document name after the query but that wont do well for the performance of the task. Does anyone know what im missing and where the error comes from?
Thanks in advance for contributing ideas,
Falko
I guess you are trying something like that?
$query = $this->createQuery();
$query->matching($query->like('file.uidLocal.name', '%somefile%'));
I am not sure if you can join from sys_file_reference to sys_file with extbase query.
For me it looks like the TCA or the FileReference Model is not implemented that way.
Maybe a workaround is to create a custom sql query wich returns uids and then create your document models with something like ->findAllByUids($uids);
Here is a working example wich uses the query builder instead of extbase query.
class ArticleRepository extends Repository
{
public function findAllByFilename($filename)
{
/* #var $queryBuilder \TYPO3\CMS\Core\Database\Query\QueryBuilder */
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
->getQueryBuilderForTable('tx_example_domain_model_article');
$queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
$res = $queryBuilder
->select('article.uid')
->from('tx_example_domain_model_article', 'article')
->leftJoin('article', 'sys_file_reference', 'reference',
$queryBuilder->expr()->andX(
$queryBuilder->expr()->eq('reference.uid_foreign', $queryBuilder->quoteIdentifier('article.uid')),
$queryBuilder->expr()->eq('reference.tablenames', $queryBuilder->quote('tx_example_domain_model_article')),
$queryBuilder->expr()->eq('reference.fieldname', $queryBuilder->quote('image')),
$queryBuilder->expr()->eq('reference.table_local', $queryBuilder->quote('sys_file'))
))
->leftJoin('article', 'sys_file', 'file',
$queryBuilder->expr()->eq('file.uid', $queryBuilder->quoteIdentifier('reference.uid_local'))
)
->where($queryBuilder->expr()->eq('file.name', $queryBuilder->createNamedParameter($filename)))
->execute();
debug($queryBuilder->getSQL());
$uids = [];
while ($row = $res->fetch()) {
$uids[] = $row['uid'];
}
return $this->findAllByUids($uids);
}
public function findAllByUids($uids) {
$query = $this->createQuery();
$query->matching($query->in('uid', $uids));
return $query->execute();
}

Typo3 accessing an existing table to consume data of it

I tried to integrate an existing table to my extension. The problem is that the content of the table isn't taken over. I created a new model with the name of the existing table and named the properties according to the existing column names. I also implemented the corresponding getters and setters of the properties.
The name of the existing table is tx_institutsseminarverwaltung_domain_model_event.
What is my failure in this case? Just want to access the data of an existing table from another extension.
Thanks in advance.
UPDATE:
I tried this:
/**
* Protected Variable objectManager wird mit NULL initialisiert.
*
* #var \TYPO3\CMS\Extbase\Object\ObjectManagerInterface
* #inject
*/
protected $objectManager = NULL;
and listAction():
/**
* action list
*
* #return void
*/
public function listAction() {
echo "test";
$theRepository = $this->objectManager->get('\TYPO3\institutsseminarverwaltung\Domain\Repository\EventRepository');
$yourRecords = $theRepository->findAll();
$this->view->assign('events', $yourRecords);
}
But no results returned.
You should use the repository linked to this table. Something like this :
$theRepository = $this->objectManager->get(\Your\VendorName\Domain\Repository\TheRepository::class);
$yourRecords = $theRepository->findAll();
How are you trying to "consume" or access the data from the other table in your extension?
Do you have a repository for the existing table (maybe there is already an existing repository, that you can reuse)?
See german typo3 board mapping existing tables and SO thread TYPO3 / How to make repository from existing table fe_users?
solution is:
$querySettings = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Typo3QuerySettings');
$querySettings->setRespectStoragePage(FALSE);
$theRepository = $this->objectManager->get('TYPO3\\institutsseminarverwaltung\\Domain\\Repository\\EventRepository');
$theRepository->setDefaultQuerySettings($querySettings);
$yourRecords = $theRepository->findAll();
$this->view->assign('events', $yourRecords);

Edit hidden records in frontend

I am building an extension to edit tt_news records in frontend.
I set setIgnoreEnableFields(TRUE) in my repository.
But if I try edit a hidden record, I get the error
Object with identity „12345" not found.
Any solution for this?
I am guessing you are using an action like
/**
* Single view of a news record
*
* #param \Vendor\Ext\Domain\Model\News $news news item
*/
public function detailAction(\Vendor\Ext\Domain\Model\News $news = null)
Your problem is, that the Repository is not used to fetch the record.
As a solution, remove the argument, clear the caches and try something like that
/**
* Single view of a news record
*
* #param \Vendor\Ext\Domain\Model\News $news news item
*/
public function detailAction() {
$id = (int)$this->request->getArgument('news');
if ($id) {
$news = $this->newsRepository->findByUid($previewNewsId);
}
}
Now you can manipulate the QuerySettings and use those.
The problem is the PropertyMapping. If extbase try to assign an uid (12345) to an Domain Object (tt_news) the "setEnableFields" setting of the Repository isn't respected. So you must fetch the object by yourself.
the simple solution is to do this in an initialize*Action for each "show" action. For editAction an example:
public function initializeEditAction() {
if ($this->request->hasArgument('news')) {
$newsUid = $this->request->getArgument('news');
if (!$this->newsRepository->findByUid($newsUid)) {
$defaultQuerySettings = $this->newsRepository->createQuery()->getQuerySettings();
$defaultQuerySettings->setIgnoreEnableFields(TRUE);
$this->newsRepository->setDefaultQuerySettings($defaultQuerySettings);
if ($news = $this->newsRepository->findByUid($newsUid)) {
$this->request->setArgument('news', $news);
}
}
}
}
The Hard Part is to get the object to update. As I never try this I have found an TypeConverter to fetch also hidden Records at https://gist.github.com/helhum/58a406fbb846b56a8b50
Maybe Instead to register the TypeConverter for everything (like the example in ext_localconf.php) you can try to assign it only in the initializeUpdateAction
public function initializeUpdateAction() {
if ($this->arguments->hasArgument('news')) {
$this->arguments->getArgument('news')->getPropertyMappingConfiguration()
->setTypeConverter('MyVendor\\MyExtension\\Property\\TypeConverters\\MyPersistenObjectConverter')
}
}

Zend duplicated rows on mysql insert

For some reason, when I do an mysql db insert from Zend, my row is dulpicated. I've tried a direct insert via phpmyadmin and it works perfect, so its not a mysql server problem.
This is the code I use:
<?php
class Model_Team extends Zend_Db_Table_Abstract {
protected $_name = 'team';
public function createUser($data) {
$user = $this->createRow();
$user->name = $data['name'];
$user->title = $data['title'];
$id = $user->save();
return $id;
}
}
?>
Thanks in advance.
EDIT:
I've found that this duplication only occurs when i call the form via AJAX (modal box), although the form post is normal, not an ajax request)
I don't know why your code is double pumping the database on save but it should'nt matter as you're using the Row object and save(). (save() inserts or updates)
You may want to restructure your createUser() function so that it can't create a new row if the row already exists.
<?php
class Model_Team extends Zend_Db_Table_Abstract {
protected $_name = 'team';
public function createUser(array $data) {
$user = $this->createRow();
//test if user has id in the array
if (array_key_exists('id', $data)){
$user->id = $data['id'];
}
$user->name = $data['name'];
$user->title = $data['title'];
$user->save();
//no need to create a new variable to return the user row
return $user;
}
}
This method will create and update a user row.
To help you further I'll need to see the controller code most of my double pumps have happened there.
Instead of using createRow() have you tried using insert()?
/**
* Insert array of data as new row into database
* #param array $data associative array of column => value pairs.
* #return int Primary Key of inserted row
*/
public function createUser($data)
{
return $this->insert($data);
}
Also - could we see the ajax code? It may be that the form is being posted as well?