Extbase update deleted=1 object in Controller fails (Object with identity x not found) - typo3

I want do give the function to 'restore' deleted Object in my FE-Ext. It seems, that it does not find any deleted records an so i cannot update them set deleted = 0.
What you be you sugestion to handle that from the controller?:
$query->getQuerySettings()->setIgnoreEnableFields(TRUE);
$query->getQuerySettings()->setIncludeDeleted(TRUE);
Thank you.

Im not quite sure what you mean by "from the controller". Normally you implement this in your repository and just call the method from the controller.
In your repo:
public function findRecordEvenIfItIsDeleted($uid) {
$query = $this->createQuery();
$settings = $query->getQuerySettings();
settings->setIgnoreEnableFields(TRUE);
settings->setIncludeDeleted(TRUE);
$query->matching($query->equals('uid', $uid));
return $query->execute();
}
In your controller:
$myObject = $this->myRepsository->findRecordEvenIfItIsDeleted($uid);
Done. (Of course your storage pid must be set (or disable respectStoragePage as well)

You're adding does not throw any error because you are setting the querySettings to include deleted records. But maybe, this setting has to be enabled even when you are updating, as the repository should find the object you are updating.
I haven't tested it but give this a try.
In your repository(just a pseudo code)
public function update($modifiedObject) {
settings->setIncludeDeleted(TRUE);
parent::update($modifiedObject);
}

I know this question was asked long time ago but today i had a similar problem with a hidden object. My solution was this one:
add this to your Model (in your case exchange "hidden" by "deleted"):
/**
* #var boolean
*/
protected $hidden;
/**
* #return boolean $hidden
*/
public function getHidden() {
return $this->hidden;
}
/**
* #return boolean $hidden
*/
public function isHidden() {
return $this->getHidden();
}
/**
* #param boolean $hidden
* #return void
*/
public function setHidden($hidden) {
$this->hidden = $hidden;
}
in your repository add this function to find the deleted/hidden object:
public function findHiddenByUid($uid) {
$query = $this->createQuery();
$query->getQuerySettings()->setIgnoreEnableFields(TRUE);
$query->getQuerySettings()->setEnableFieldsToBeIgnored(array('disabled','hidden'));
return $query
->matching($query->equals('uid', $uid))
->execute()
->getFirst();
}
now in your Controller you can read the object, set the "hidden" option and update it:
$yourobject = $this->yourobjectRepository->findHiddenByUid($uid);
$yourobject->setHidden(1);
$this->yourobjectRepository->update($yourobject);
Maybe not interesting for your task but for others:
In my case i additionally had the problem posting a hidden object in a form to an action. So note that if you want to post an object by a form, it is better (or probably necessary) to first set the objects deleted/hidden option to 0.

Related

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')
}
}

Extbase property mapping for deleted record

I would like to build a preview page for a create form. I set "deleted" property of the record to "1" when in previewAction because in the BE the list module is used to approve the inserted records - so if the record was never finally saved its deleted anyway.
Problem: I can create the record (deleted=1) - I can jump back to the form (no history back for I have to keep the created object). But if I submit again the property mapping tells me
Object of type MyModel with identity "3" not found.
Of course that's because its deleted. The settings in the Repository to ignore deleted are not taking action here.
Yes I could bypass the Extbase magic by filling up everything manually, but this is not what I want.
Here is the action to get an idea what I'm trying
/**
* action preview
*
* #param MyModel
* #return void
*/
public function previewAction(MyModel $newModel)
{
//check if model was already saved
$uid = $this->request->hasArgument('uid') ? this->request->getArgument('uid') : 0;
if($uid){
$newModel = $this->myRepository->findDeletedByUid($uid);
$this->myRepository->update($newModel);
}
else{
$newModel->setDeleted(true);
$this->myRepository->add($newModel);
}
$this->view->assign('ad', $newModel);
$this->persistenceManager->persistAll();
$uid = $this->persistenceManager->getIdentifierByObject($newModel);
$this->view->assign('uid', $uid);
}
Any ideas?
The Extbase default query settings suppress deleted objects.
Since you've already stated the custom query findDeletedByUid() in your repository, you just need to set it to include deleted records. It is important, however, that if you want to call your controller action using the object, you'll have to retrieve it before calling the action. Use an initialization action for that. The initializaton will be called automatically before the action.
If you want to set wether the object is deleted, you'll also going to need to define a property, getter and setter in your Domain Model and a proper definition in your tca to enable the data mapper to access the column.
In the repository:
public function findDeletedByUid($uid) {
$query = $this->createQuery();
$query->getQuerySettings()->setIncludeDeleted(true);
$query->matching(
$query->equals('uid',$uid)
);
return $query->execute();
}
In your Controller class:
/**
* initialize action previewAction
* Overrides the default initializeAction with one that can retrieve deleted objects
*/
public function initializePreviewAction(){
if( $this->request->hasArgument('mymodel') ){
$uid = $this->request->getArgument('mymodel');
if( $mymodel = $this->mymodelRepository->findDeletedByUid($uid) ){
$this->request->setArgument($mymodel);
} else {
// handle non retrievable object here
}
} else {
// handle missing argument here
}
}
In your Domain Model:
...
/**
* #var bool
*/
protected $deleted;
/**
* #return bool
*/
public function getDeleted() {
return $this->deleted;
}
/**
* #param bool $deleted
*/
public function setDeleted($deleted) {
$this->deleted = $deleted;
}
In your tca.php
...
'deleted' => array(
'exclude' => 1,
'label' => 'LLL:EXT:lang/locallang_general.xlf:LGL.deleted',
'config' => array(
'type' => 'check',
),
),
Instead of doing any magic with deleted, you should use the hidden field to allow editors to preview documents.
You can tell your query to include hidden records inside the repository.
Your findDeletedByUid($uid) function caught my eye. If it's not a custom function, should it use something like findByDeleted(TRUE) or findByDeleted(1) in combination with ->getFirst() or ->findByUid()? You can find discussions in the Extbase manual reference and the Repository __call() function API sections.
Thanks for all hints.
I think depending to the answers its not possible without bypass extbase property-mapping magic. So I think in general its not a good idea to do it like that.
So I put now my own flag "stored" to the model.
In BE List-Module the not "stored" objects are still visible, but using an own BE Module or deleting the not "stored" object by a cron-job should do the job.
If anyone has a bedder idea feel free to share it :-)

Set sys_language_uid in an extbase command controller

I have a command controller (an importer) run by scheduler, which should persist data as such:
foreach ($items as $item){
// store it
$entry = $this->objectManager->get('STUBR\Importer\Domain\Model\Item');
$entry->setTitle($item['Title']);
$entry->setData(json_encode($item));
// manually set the storage page (defined in scheduler form)
$entry->setPid($itemStoragePid); // works
// manually set the language (defined in scheduler form)
// EDIT
// $entry->setSysLanguageUid = -1; // had typo
$entry->set_languageUid(-1); // works
// END EDIT
$this->itemRepository->add($entry);
}
While neither pid nor sys_language_uid are set in the model, setPid behaves as expected, but setSysLanguageUid does not.
I'm aware that something is or was not quite right with setSysLanguageUid() in extbase (https://forge.typo3.org/issues/45873), although I wasn't able to grasp the problem entirely.
How do I manually store into the sys_language_uid column?
PS: I've tried Extbase Model: setSysLanguageUid not working but probably I missed something
It's solved, I had a typo above
Solution from #Chi at https://stackoverflow.com/a/33798615/160968
/**
* languageUid
* #var int
*/
protected $languageUid;
/**
* #param int $languageUid
* #return void
*/
public function setLanguageUid($languageUid) {
$this->languageUid = $languageUid;
}
/**
* #return int
*/
public function getLanguageUid() {
return $this->languageUid;
}
And then $entry->setLanguageUid(-1);

How does Zend_Auth storage work?

This is very simple. I write
$auth->getStorage()->write($user);
And then I want, in a separate process to load this $user, but I can't because
$user = $auth->getIdentity();
is empty. Didn't I just... SET it? Why does it not work? Halp?
[EDIT 2011-04-13]
This has been asked almost two years ago. Fact is, though, that I repeated the question in July 2010 and got a fantastic answer that I back then simply did not understand.
Link: Zend_Auth fails to write to storage
I have since built a very nice litte class that I use (sometimes with extra tweaking) in all my projects using the same storage engine as Zend_Auth but circumventing all the bad.
<?php
class Qapacity_Helpers_Storage {
public function save($name = 'default', $data) {
$session = new Zend_Session_Namespace($name);
$session->data = $data;
return true;
}
public function load($name = 'default', $part = null) {
$session = new Zend_Session_Namespace($name);
if (!isset($session->data))
return null;
$data = $session->data;
if ($part && isset($data[$part]))
return $data[$part];
return $data;
}
public function clear($name = 'default') {
$session = new Zend_Session_Namespace($name);
if (isset($session->data))
unset($session->data);
return true;
}
}
?>
It's supposed to work.
Here's the implementation of the Auth getIdentity function.
/**
* Returns the identity from storage or null if no identity is available
*
* #return mixed|null
*/
public function getIdentity()
{
$storage = $this->getStorage();
if ($storage->isEmpty()) {
return null;
}
return $storage->read();
}
Here's the implementation of the PHP Session Storage write and read functions:
/**
* Defined by Zend_Auth_Storage_Interface
*
* #return mixed
*/
public function read()
{
return $this->_session->{$this->_member};
}
/**
* Defined by Zend_Auth_Storage_Interface
*
* #param mixed $contents
* #return void
*/
public function write($contents)
{
$this->_session->{$this->_member} = $contents;
}
Are you sure you are loading the same instance of the Zend_Auth class?
Are you using
$auth = Zend_Auth::getInstance();
Maybe you are calling the write method after the getIdentity method?
Anyway, as I said before, what you are doing should work.
So on a page reload you can fetch the session, while not if redirecting? Are you redirecting on a different Domain-Name? Then it might be an issues with the Cookies and you'd need to manually set session.cookie_domain ini variable.
Check if the cookie named PHPSESSID has been properly been set and if it's being sent to the server on every page request? Is it constant or does it change on every request?
Also, you might want to check if the session data is being properly saved to the disk. The sessions can be found in the directory defined by the ini variable session.save_path. Is the file corresponding to your PHPSESSID there and does it contain a meaningful entry? In my case it contains
root#ip-10-226-50-144:~# less /var/lib/php5/sess_081fee38856c59a563cc320899f6021f
foo_auth|a:1:{s:7:"storage";a:1:{s:9:"user_id";s:2:"77";}}
Add:
register_shutdown_function('session_write_close');
to index.php before:
$application->bootstrap()->run();

Akeneo 2.1.4 : How can I change a products' parent (used product model)

I have the requirement where upon importing I need to be able to change to products' product model. I tried to do this by changing the parent in the CSV file I'm importing, but this will show the following message:
WARNING
parent: Property "parent" cannot be modified, "new_parent_code" given.
What is the proper way to make this work? I tried 'hacking' the database by manually assigning a different parent to the product by editing the parent directly in the pim_catalog_product-table, and this seemed to work, but when editing the product unexpected results occur.
Could anyone point me in the right direction how I can change a product parent upon importing?
update:
I now came up with the following solution:
In my own bundle, I added Resources/config/updaters.yml (using DependencyInjecten Extension) with the following:
parameters:
# Rewrite parent field setter so we can allow the importer to update the parent:
pim_catalog.updater.setter.parent_field.class: Vendor\Bundle\InstallerBundle\Updater\Setter\ParentFieldSetter
And my custom ParentFieldSetter.php:
namespace Vendor\Bundle\InstallerBundle\Updater\Setter;
use Akeneo\Component\StorageUtils\Exception\ImmutablePropertyException;
use Akeneo\Component\StorageUtils\Repository\IdentifiableObjectRepositoryInterface;
/**
* Class ParentFieldSetter
*/
class ParentFieldSetter extends \Pim\Component\Catalog\Updater\Setter\ParentFieldSetter
{
/**
* #var IdentifiableObjectRepositoryInterface
*/
private $productModelRepository;
/**
* ParentFieldSetter constructor.
* #param IdentifiableObjectRepositoryInterface $productModelRepository
* #param array $supportedFields
*/
public function __construct(
IdentifiableObjectRepositoryInterface $productModelRepository,
array $supportedFields
) {
$this->productModelRepository = $productModelRepository;
parent::__construct($productModelRepository, $supportedFields);
}
/**
* #param \Pim\Component\Catalog\Model\ProductInterface|\Pim\Component\Catalog\Model\ProductModelInterface $product
* #param string $field
* #param mixed $data
* #param array $options
*/
public function setFieldData($product, $field, $data, array $options = []): void
{
try {
parent::setFieldData($product, $field, $data, $options);
} catch (ImmutablePropertyException $exception) {
if ($exception->getPropertyName() === 'parent') {
// Allow us to change the product parent:
if ($parent = $this->productModelRepository->findOneByIdentifier($data)) {
$familyVariant = $parent->getFamilyVariant();
$product->setParent($parent);
$product->setFamilyVariant($familyVariant);
if (null === $product->getFamily()) {
$product->setFamily($familyVariant->getFamily());
}
}
} else {
throw $exception;
}
}
}
}
This works. Now, upon importing the parent gets saved properly. I'm only wondering if:
a). This implementation is correct.
b). I'm not causing some other major issues by changing the parent.
I also noted the following TODO-statement in the original Akeneo-code above the code that throws the error when attempting to change the parent:
// TODO: This is to be removed in PIM-6350.
Anyone from Akeneo care to shed some light on this?