XF 2.1 Best way to delete previous record?

grantus

Active member
I have an upload form and users can upload a file, but I would like to check on save if they already have an entry, if so then delete it.

So I'm trying to do it in my actionSave:

Code:
public function actionSave(ParameterBag $params) {
    // validate form inputs
    
    // check if user already has an entry, if so delete it
}

I already have a functioning actionDelete:

Code:
$plugin = $this->plugin('XF:Delete');
return $plugin->actionDelete(
$signup,
$this->buildLink('signup/delete', $signup),
$this->buildLink('signup/'),
$signup->name
);

but that's just for the delete button. How can I do it upon saving the new upload?
 
Solution
You'd need to call ->fetchOne() in the Finder query to fetch the entity before deleting it. Currently you're calling delete() on an un-fetched Finder instance.
I just tried to do it instead in the Entity's _postSave like this:

Code:
protected function _postSave() {
        $finder = $this->finder('Test\ILL:BthisSignup')
        ->where('user_id', \XF::visitor()->user_id)
        ->order('signup_id', 'asc');

        if ($finder) {
            $finder->delete();
        }
    }

but it looks like delete() is only available in the _postDelete. Is that correct?
 
You'd need to call ->fetchOne() in the Finder query to fetch the entity before deleting it. Currently you're calling delete() on an un-fetched Finder instance.
 
Solution
You'd need to call ->fetchOne() in the Finder query to fetch the entity before deleting it. Currently you're calling delete() on an un-fetched Finder instance.
You're right, I forgot about that. But I'm trying this:

Code:
protected function _postSave() {
        $finder = \XF::finder('Test\ILL:BthisSignup');
        $file = $finder->where('user_id', \XF::visitor()->user_id)->order('signup_id', 'asc')->fetchOne();

        if ($file) {
            $file->delete();
        }
    }

and it's deleting all the entries for that user instead of just the one from the query, so it's not even inserting the new one.
 
Back
Top Bottom