SilverStripe 4 - Сохранить загруженный файл как свойство расширения члена - PullRequest
0 голосов
/ 23 мая 2018

Я пытаюсь сохранить загруженный файл с помощью AJAX-запроса на контроллере страницы как свойство расширения Member.

Я получил Member DataExtension, который реализует свойство File с отношением many_many, например:

My Member Extension

[...]
/**
 * Classe Utente - Estensione
 */
class UtenteExtension extends DataExtension
{
    // Dichiarazione Proprietà
    private static $many_many = [
        'AllegatiUpload' => File::class, // this field should save users file uploads
        [...]
    ];
    private static $owns = [
        'AllegatiUpload',
        [...]
    ];
[...]

The Controller участвует:

use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\ErrorPage;
use SilverStripe\Assets\Folder;
use SilverStripe\Assets\File;
use SilverStripe\Assets\Upload;
use SilverStripe\Security;
use SilverStripe\Security\Group;
use SilverStripe\Assets\Storage\AssetStore;

/**
 * Classe Controller Utente - Dashboard
 */
class UtenteDashboardController extends PageController
{
    // Dichiarazione Proprietà
    private static $allowed_actions = [
        'carica'
    ];

    /**
    * Funzione gestione validazione ed invio form caricamento
    * @param  HTTPRequest $request Richiesta HTTP
    * @return HTTPResponse Risposta HTTP
    */
    public function carica(SS_HTTPRequest $request) {
        if (!$request->isAjax()) {
            return ErrorPage::response_for(404);
        } else if (!$request->isPOST()) {
            return $this->httpError(400, 'Metodo POST richiesto');
        } else {
            $documento = $request->postVar('documento'); // File data sent by FormData JS API

            if (!isset($documento)) {
                return $this->httpError(500, 'Dati richiesti mancanti');
            } else {
                // User check
                $utente = Security::getCurrentUser();

                if ($utente->inGroup(Group::get()->filter('Code', 'clienti')->first()->ID)) {
                    // File uploading
                    $cartellaUpload = 'clienti/'. strtolower($utente->Surname) .'/uploads';

                    Folder::find_or_make($cartellaUpload);

                    // I tried with the official guide approach, with this line - with no results
                    //$utente->AllegatiUpload()->setFromLocalFile($cartellaUpload, documento, AssetStore::CONFLICT_OVERWRITE);
                     // Then I tried with this approach
                    $file = File::create();
                    $upload = Upload::create();

                    $upload->loadIntoFile($documento, $file, $cartellaUpload);

                    // Upload check
                    if ($upload->isError()) {
                        return $this->httpError(400, 'Errore di caricamento file');
                    } else {
                        // Relate the file to the destinaion user field
                        $utente->{'AllegatiUpload.ID'} = $upload->getFile()->ID;
                        // Update user
                        $utente->write(); 

                        return new HTTPResponse;
                    }
                } else {
                    return $this->httpError(401, 'Utente non abilitato');
                }
            }
        }
    }
}

Я застрял в процессе, чтобы связать файл с правильным Member.Я думаю, что мне не хватает правильного синтаксиса, потому что я работаю с отношением many_many, а это не подходит:

// Relate the file to the destinaion user field
utente->{'AllegatiUpload.ID'} = $upload->getFile()->ID;

Я тоже пытался с таким подходом:

$allegato = $utente->AllegatiUpload();

$allegato->setField('Documento', $upload->getFile()->ID);
$allegato->write();

Но я получаю это исключение:

[Emergency] Uncaught BadMethodCallException: Object -> __ call (): метод write не существует в SilverStripe \ ORM \ ManyManyList '

Может быть, я должен сначала преобразовать AllegatiUpload в DataObject, а затем добавить в него свойство File, чтобы избежать этого?

1 Ответ

0 голосов
/ 30 мая 2018

Вы добавляете новые элементы в отношения с синтаксисом $object->RelationName()->add($item), в вашем случае:

$utente->AllegatiUpload()->add($file);

ссылка https://docs.silverstripe.org/en/4/developer_guides/model/relations/#adding-relations

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...