FriendsOfCake / cakephp-upload

CakePHP: Handle file uploading sans ridiculous automagic
https://cakephp-upload.readthedocs.io/
MIT License
551 stars 255 forks source link

Add/Edit Record with Multiple Attachment inserting empty records #491

Closed karthikeyanangler closed 2 years ago

karthikeyanangler commented 6 years ago

Dear Friends,

So far the plugin is working fine while Add/Edit a record if we select one or multiple files in the form field. In case if we didn't select any file, its insert a single empty record in the attachment table.

As per the requirement, the File Upload for Add/ Edit is Optional. See my code below, and please guide me to what I have missed.

InvoiceAttachmentTable

public function initialize(array $config)
{
    # File upload Behavior
    $this->addBehavior('Josegonzalez/Upload.Upload', [
        'file' => [                 
            'path' => 'webroot{DS}files{DS}invoices{DS}{field-value:invoice_id}{DS}',
            'fields' => [                    
                'dir' => 'file_dir', 
                'size' => 'file_size', 
                'type' => 'file_type', 
            ],
            'deleteCallback' => function ($path, $entity, $field, $settings) {

                return [
                    $path . $entity->{$field},                       
                ];
            },
            'keepFilesOnDelete' => false
        ],
    ]);
}
public function validationDefault(Validator $validator)
{
    $validator->provider('upload', \Josegonzalez\Upload\Validation\UploadValidation::class);

    $validator
        ->integer('id')
        ->allowEmpty('id', 'create');

    $validator
        ->add('file', 'fileCompletedUpload', [
            'rule' => 'isFileUpload',
            'message' => 'There was no file found to upload',
            'provider' => 'upload'
        ])->add('file', 'fileSuccessfulWrite', [
            'rule' => 'isSuccessfulWrite',
            'message' => 'This upload failed',
            'provider' => 'upload'
        ])->allowEmpty('file');

    $validator
        ->scalar('file_dir')
        ->maxLength('file_dir', 255)
        ->allowEmpty('file_dir');

    $validator
        ->integer('file_size')
        ->allowEmpty('file_size');

    $validator
        ->scalar('file_type')
        ->maxLength('file_type', 255)
        ->allowEmpty('file_type');

    return $validator;
}

create-invoice.ctp

<?= $this->Form->create($invoice, ['type' => 'file']) ?>

<?php echo $this->Form->control('invoice_attachments[].file', ['label' => false,'multiple' => true ,'type'=>'file', 'class' => 'form-control']); ?>

<?= $this->Form->end() ?>

Note: I have shared the code which related to the upload behaviour only.