How to upload an image in Elgg

79 Views Asked by At

I have been trying to save an Elgg entity icon in Elgg 3.x but to no success. myObject saves into the database, but the file doesn't get uploaded.

What is it that I am doing wrong?

Thank you all in advance.

save.php form

<?php
    echo elgg_view('input/file', [
        'name' => 'upload[]',
        'multiple' => true,
        'label' => 'picTuREs',
    ]);
?>  

save.php action file

foreach (elgg_get_uploaded_files('upload') as $upload)
{
    $myObject = new ElggObject();
    $myObject->subtype = "my_object";
    $myObject->access_id = ACCESS_PUBLIC;

    $myObject->saveIconFromUploadedFile($upload);

    $myObject->save();
}  
1

There are 1 best solutions below

0
ShadowTrix On

Update your action on this:

$upload_guids = (array) get_input('uploads');

if (empty($upload_guids)) {
    return elgg_error_response(elgg_echo('file:error:empty_form'));
}

foreach ($upload_guids as $upload_guid) {
    $file = new \ElggFile();
    
    $file->title = $title;
    $file->description = $description;
    $file->access_id = $access_id;
    $file->container_guid = $container_guid;
    $file->tags = string_to_tag_array($tags);

    $file->save();
    
    if ($file->getSimpleType() === 'image') {
        $file->saveIconFromElggFile($file);
    }
} 

If you use a custom subtype then you should extend \ElggFile via this object something like this:

class MyCustomFile extends \ElggFile {
    
    const SUBTYPE = 'my_subtype';
    
    protected function initializeAttributes() {
        parent::initializeAttributes();

        $this->attributes['subtype'] = self::SUBTYPE;
    }
    
    /**
     * @see ElggEntity::saveIconFromElggFile()
     */
    public function saveIconFromElggFile(\ElggFile $file, $type = 'icon', array $coords = array()) {
        return false;
    }
}