This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

cydrick.nonog
cydrick.nonog

Hi,

Im creating a plugin that has uploading files. But i dont want to add it in sysem_files table. I try to extend the System\Models\File and change the $table to my file table. The problem is in saving, it still save in system_files table.

Anyone can help me about this. Thanks in advanced.

cydrick.nonog
cydrick.nonog
I just solved this problem, the problem is not the extended System\Models\File, but the problem is the file upload form widget.
)
deroccha
deroccha

Hi can you show how did you solved this problem?

cydrick.nonog
cydrick.nonog

I created another form widget that is almost the same as the file upload that was created by octobercms

cydrick.nonog
cydrick.nonog

In my created form widget I extends

cydrick.nonog
cydrick.nonog

` <?php namespace Cydrick\KidlatArchive\FormWidgets;

use Backend\FormWidgets\FileUpload as FileUploadBase; use Str; use Input; use Validator; //use System\Models\File; use System\Classes\SystemException; //use Backend\Classes\FormField; //use Backend\Classes\FormWidgetBase; use October\Rain\Support\ValidationException; use Exception;

class FileUpload extends FileUploadBase {

public function getRelatedModel(){
    list($model,$attribute) = $this->resolveModelAttribute($this->valueFrom);
    return $model->{$this->getRelationType()}[$this->fieldName][0];
}
public function onRemoveAttachment()
{
    $classname = $this->getRelatedModel();
    if (($file_id = post('file_id')) && ($file = $classname::find($file_id))) {
        $this->getRelationObject()->remove($file, $this->sessionKey);
    }
}

public function onSortAttachments()
{
    if ($sortData = post('sortOrder')) {
        $ids = array_keys($sortData);
        $orders = array_values($sortData);

        $classname = $this->getRelatedModel();
        $file = new $classname;

        $file->setSortableOrder($ids, $orders);
    }
}

public function onLoadAttachmentConfig()
{
    $classname = $this->getRelatedModel();
    if (($file_id = post('file_id')) && ($file = $classname::find($file_id))) {
        $this->vars['file'] = $file;
        return $this->makePartial('config_form');
    }

    throw new SystemException('Unable to find file, it may no longer exist');
}

public function onSaveAttachmentConfig()
{
    $classname = $this->getRelatedModel();
    try {
        if (($file_id = post('file_id')) && ($file = $classname::find($file_id))) {
            $file->title = post('title');
            $file->description = post('description');
            $file->save();

            $file->thumb = $file->getThumb($this->imageWidth, $this->imageHeight, ['mode' => 'crop']);
            return ['item' => $file->toArray()];
        }

        throw new SystemException('Unable to find file, it may no longer exist');
    }
    catch (Exception $ex) {
        return json_encode(['error' => $ex->getMessage()]);
    }
}
protected function checkUploadPostback()
{
    $classname = $this->getRelatedModel();
    if (!($uniqueId = post('X_OCTOBER_FILEUPLOAD')) || $uniqueId != $this->getId()) {
        return;
    }

    try {
        $uploadedFile = Input::file('file_data');

        $isImage = starts_with($this->getDisplayMode(), 'image');
        //echo $classname;
        $validationRules = ['max:'.$classname::getMaxFilesize()];
        if ($isImage) {
            $validationRules[] = 'mimes:jpg,jpeg,bmp,png,gif,svg';
        }

        $validation = Validator::make(
            ['file_data' => $uploadedFile],
            ['file_data' => $validationRules]
        );

        if ($validation->fails()) {
            throw new ValidationException($validation);
        }

        if (!$uploadedFile->isValid()) {
            throw new SystemException('File is not valid');
        }

        $fileRelation = $this->getRelationObject();

        $file = new $classname;
        $file->data = $uploadedFile;
        $file->is_public = $fileRelation->isPublic();
        $file->save();

        $fileRelation->add($file, $this->sessionKey);

        $file->thumb = $file->getThumb($this->imageWidth, $this->imageHeight, ['mode' => 'crop']);
        $result = $file;

    }
    catch (Exception $ex) {
        $result = json_encode(['error' => $ex->getMessage()]);
    }

    header('Content-Type: application/json');
    die($result);
}

}

`

deroccha
deroccha

thanks for sharing

deroccha
deroccha

and can you share as well your Plugin.php? I get a redirect problem when I init the widget

cydrick.nonog
cydrick.nonog

'Cydrick\KidlatArchive\FormWidgets\FileUpload' => [ 'label' => "FileUpload", "alias" => "ckafileupload" ]

put that on your registerForm Widgets

cydrick.nonog
cydrick.nonog

remember to change the namespace

deroccha
deroccha

Yes I was doing. Anyway I get Error uploading file: Call to undefined method October\Rain\Database\QueryBuilder::getMaxFilesize() and I was trying to use in my Model

use October\Rain\Database\Attach\File as FileBase; which contains the validation but still the same

deroccha
deroccha

I wonder if there is a way just to extend Sytem\Models\Files

like public $hasOne = [ 'upload_settings' =>[' System\Models\File'] ];

than push the datas on beforeSave event

Last updated

cydrick.nonog
cydrick.nonog

about the model.

I also created my own Model for file. And add it to relation of another Model

$hasOne = [ 'myfiles' => ['Cydrick\MyPlugin\Models\File'] ];

thats how i implemented my model.

deroccha
deroccha

this one drives me crazy so practically I need extra fields to save for each uploaded photo inside my Plugin, like author hyperlink to internal and external content which would be defined under settings.

So I made a model which one has this extra fields

now when you attach the widget how do you tell which model should be used ?

public $attachMany = [ 'photos' => ['System\Models\File'], ];

or

public $attachMany = [ 'photos' => ['Author\Plugin\Models\CustomFile'], ];

I've been trying both of. Won't work I'm lost I think I will cry :D

cydrick.nonog
cydrick.nonog

what was the error?

deroccha
deroccha

Okay I reproduce the hole as I'm building up

My Plugin


--item
--- Item.php
--portfoliofile
--- PortfolioFile.php
formwidgets
-- portfoliouploads
--- assets
--- partials 
-- PortfolioUploads.php
Plugin.php

Registering form widget in Plugin.php

    <code>/**
     * Register formWidgets
     *
     */
    public function registerFormWidgets() {
        return [
            '\Kakuki\Portfolio\FormWidgets\PortfolioUploads' => [
                'label' => 'Image upload with link',
                'code' => 'portfoliouploads',
            ],
        ];
    }</code>
 than my Item.php Model would have many images attached

    <code>public $attachMany = [
        'photos' => ['Kakuki\Portfolio\Models\PortfolioFile'],
    ];</code>

than PortfolioFile Model
<code>class PortfolioFile extends Model
{

    /**
     * @var string The database table used by the model.
     */
    protected $table = 'kakuki_portfolio_portfolio_files';
}</code>

than using your code  I get on upload ```Error uploading file: Call to undefined method Illuminate\Database\Query\Builder::getMaxFilesize()```

Last updated

cydrick.nonog
cydrick.nonog

This is the original System\Model File

namespace System\Models;

use Config;
use Request;
use October\Rain\Database\Attach\File as FileBase;

/**
 * File attachment model
 *
 * @package october\system
 * @author Alexey Bobkov, Samuel Georges
 */
class File extends FileBase {
...
}
cydrick.nonog
cydrick.nonog

means you need to extend your ProtfolioFile to October\Rain\Database\Attach\File Sample

namespace Author\Plugin\Models;
use Config;
use Request;
use October\Rain\Database\Attach\File as FileBase;

class PortfolioFile extends FileBase
{
    protected $table = 'kakuki_portfolio_portfolio_files';

    //
    // Configuration
    //

    /**
     * Define the storage path, override this method to define.
     */
    public function getStorageDirectory()
    {
        $uploadsDir = Config::get('cms.uploadsDir');
        if ($this->isPublic()) {
            return base_path() . $uploadsDir . '/public/';
        }
        else {
            return base_path() . $uploadsDir . '/protected/';
        }
    }

    /**
     * Define the public address for the storage path.
     */
    public function getPublicDirectory()
    {
        $uploadsDir = Config::get('cms.uploadsDir');
        if ($this->isPublic()) {
            return Request::getBasePath() . $uploadsDir . '/public/';
        }
        else {
            return Request::getBasePath() . $uploadsDir . '/protected/';
        }
    }
}
deroccha
deroccha

thanks a lot I will give another try

cydrick.nonog

1-20 of 28

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.