Error while saving data

Asked

Viewed 454 times

1

I’m learning how to use Cakephp, and I’m trying to make a tool to upload images using cake 2.4.4. the problem is that only the fields modified and created are entered into the database, although name and size should also be saved. Debugkit shows this SQL log

INSERT INTO caketest.galleries(modified,created) VALUES ('2014-05-20 14:55:07', '2014-05-20 14:55:07')

When trying to save the image, controller executes the message

$this->Session->setFlash('O Ficheiro foi guardado com sucesso.', 'default', array('class'=>'alert flashMessageSuccess'));`

always, however the file is not moved to the server folder. What is the problem with my code?

Controller

public function uploadImages(){
        $this->set('title_for_layout', 'Inserir imagens');
        $this->layout = 'admin';
        if($this->request->is('post') || $this->request->is('put')){

            $this->loadModel('Gallery');
            $file = array(
                'Gallery' => array(
                    $this->request->data['Gallery']
                    )
                );
            $this->Gallery->create();
            debug($this->request->data);
            debug($this->request->data['Gallery']);
            debug($file);
            if($this->Gallery->save($this->request->data)){
                move_uploaded_file($this->data['Gallery']['tmp_name'], WWW_ROOT. 'img/Gallery/' . $this->data['Gallery']['name']);
                $this->Session->setFlash('O Ficheiro foi guardado com sucesso.', 'default', array('class'=>'alert flashMessageSuccess'));
            }else{
                $this->Session->setFlash('Erro ao guardar o ficheiro.', 'default', array('class'=>'alert flashMessageDanger'));
            }
        }
    }

Model

App::uses('AppModel', 'Model');
class Gallery extends AppModel{
    public $useTable = 'galleries';
    var $validate = array(
        'name' => array(
            'is_valid' => array(
                'rule' => 'notEmpty',
                'message' => 'Seleccione um ficheiro por favor.'
                ),
            'is_unique' => array(
                'rule' => 'isUnique',
                'message' => 'Já existe um ficheiro com este nome.'
                ),
            'extension' => array(
                'rule' => array('extension', array('gif', 'jpeg', 'png', 'jpg')),
                'message' => 'O ficheiro deve estar num formato gif, jpeg, jpg ou png.'
            ),
        'size' => array(
            'sizeCheck' => array(
                'rule' => array('fileSize', '<=', '2MB'),
                'message' => 'O ficheiro deve ter um tamanho inferior a 2MB.'
                )
            )

        )
    );
}

View

echo $this->Session->flash();

echo "<br>";
echo $this->Form->create('Gallery',array('type'=>'file'));

echo "<h3><small>Seleccione uma imagem por favor.</small></h3>";
echo $this->Form->input('file', array('type' => 'file'));//file('file');
echo $this->Form->error('file', array(), array('class' => 'alert flashMessageWarning'));
echo "<br>";
echo $this->Form->submit(__('Guardar'), array('class' => 'btn btn-success','formnovalidate' => true)) ;
echo $this->Form->end();

My table has columns:

 id | name | size | created | modified

Debug($this->request->data)

array(
    'Gallery' => array(
        'file' => array(
            'name' => '1604710_722861904399871_963210258_n.jpg',
            'type' => 'image/jpeg',
            'tmp_name' => 'C:\wamp\tmp\php2B49.tmp',
            'error' => (int) 0,
            'size' => (int) 31483
        )
    )
)
  • I didn’t understand this part of your question "When trying to save the image, the controller executes the message INSERT INTO caketest.galleries(modified,created) VALUES ('2014-05-20 14:55:07', '2014-05-20 14:55:07')"

  • 1

    @Erloncharles I edited the question. I was wrong to copy the line, I apologize.

  • What are the columns of your table?

  • @Erloncharles id, name, size, created and modified.

1 answer

0


According to the Cookbook your data must be as follows to be saved

Array 
(
    [ModelName] => Array
    (
        [fieldname1] => 'value'
        [fieldname2] => 'value'
    )
)

The problem is with the array where are the data to be saved, it saves the image, but saves only the data that is saved without having to pass the values that are the columns created and modified

Solution

I recommend to make a formatting in your array, going up the key data "file" to the same level of the key itself or return a array thus:

Array(
    'Gallery' => Array(
        'name' => '1604710_722861904399871_963210258_n.jpg',
        'size' => (int) 31483
    )
)

To do this your controller should look like this:

public function uploadImages(){
    $this->set('title_for_layout', 'Inserir imagens');
    $this->layout = 'admin';
    if($this->request->is('post') || $this->request->is('put')){

        $this->loadModel('Gallery');
        $file = array(
            "Gallery" => array(
                "name" => $this->request->data["Gallery"]["file"]["name"],
                "size" => $this->request->data["Gallery"]["file"]["size"]
                )
            );
        $this->Gallery->create();
        if($this->Gallery->save($file)){
            move_uploaded_file($this->data['Gallery']['tmp_name'], WWW_ROOT. 'img/Gallery/' . $this->data['Gallery']['name']);
            $this->Session->setFlash('O Ficheiro foi guardado com sucesso.', 'default', array('class'=>'alert flashMessageSuccess'));
        }else{
            $this->Session->setFlash('Erro ao guardar o ficheiro.', 'default', array('class'=>'alert flashMessageDanger'));
        }
    }
}

Move the file

With respect to moving the file to the documentation of the move-uploaded-file() says that:

If filename is not a valid submitted file, then no action will occur and move_uploaded_file() will return FALSE.

If filename is a valid uploaded file, but cannot be moved for any reason, no action will occur and move_uploaded_file() will return FALSE. Additionally, an alert will be issued.

Therefore permissions to write to the destination folder, access to the source folder, the existence of the destination folder, and anything else that makes move_uploaded_file() to move the file.

  • I made the modification, and I get this message $this->Session->setFlash('Erro ao guardar o ficheiro.', 'default', array('class'=>'alert flashMessageDanger'));. The array has not been saved, Debugkit shows this SQL SELECT COUNT(*) AS CountFROMcaketest.galleriesASGalleryWHEREGallery.name = '1604710_722861904399871_963210258_n.jpg'

  • some error message is displayed in the inputs?

  • Validation errors?

  • is exactly what I want to know

  • No. And Debugkit shows : $this->validationErrors(array) Galleryimage(array) name(array) 0 size. cake is making a SELECT, shouldn’t be doing a INSERT ?

  • Check the edition and test with this controller

  • the array is as you indicated to me, however it continues to show $this->Session->setFlash('Erro ao guardar o ficheiro.', 'default', array('class'=>'alert flashMessageDanger')); and Cake continues to do the SELECT, according to Debugkit.

  • I tried to comment on the validation rules in the model, and the data was entered in the BD, however the file was not moved to the folder.

  • Clean your database and try again, can be validation by file name.

  • I cleaned the database and tried again, with the validation, and did not give again, I think the validation of size may be causing this. In Debugkit get, $this->validationErrors(array),&#xA;Gallery(array),&#xA;name(array),&#xA;0size.

  • Apparently one was missing ) in the validation, which placed the validation of the size within the validation of name. But the Image is not being stored in the folder, I don’t have to put too, in the $file, the value for tmp_name?

  • Thank you very much for your help!

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.