Sunday, June 25, 2017

Error Invalid data type, must be an array or \\ArrayAccess instance

Leave a Comment

When I send a image and text data, have the next problem, this happend when I send data from angular to cakephp 3 with rest service and don't know how solve:

Possibly unhandled rejection: {     "data":{       "message":"Invalid data type, must be an array or \\ArrayAccess instance.",       "url":"/documents/add",       "code":500,      "file":"C:\\xampp\\htdocs\\frontend_dekma\\app\\vendor\\cakephp\\cakephp\\src\\Utility\\Hash.php",       "line":51     },      "status":500,     "config":{       "method":"POST",       "transformResponse":[null],       "jsonpCallbackParam":"callback",     "headers":{       "Access-Control-Allow-Origin":"*",       "Access-Control-Allow-Headers":       "Accept, Authorization, Cache-Control, Content-Type, X-Requested-With, x-csrf-token",       "Accept":"application/json",     "Authorization":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImV4cCI6MTQ5NzYzNzczNX0.im1g6BeHhMAF-MA0jhzYsU15UAH6BS1tByIqbj2acAQ"},     "url":"/app/documents/add",     "data":{}     },     "statusText":"Internal Server Error"} 

Now in angular have my service for send this information:

.service('fileUpload', ['$http', function ($http) {             this.uploadFileToUrl = function(file, uploadUrl){                 var formData = new FormData();                 console.log(file);                 // here take the values                 formData.append('photo', file.photo);                 formData.append('descripcion', file.descripcion);                 //show values formData                 for (var key of formData.entries()) {                     console.log(key[0] + ', ' + key[1]);                 }                 //post url uploadUrl = '/app/documents/add'                 $http.post(uploadUrl, formData, {                     transformRequest: angular.identity,                     headers: {                         'Access-Control-Allow-Origin' : '*',                         'Access-Control-Allow-Headers': 'Accept, Authorization, Cache-Control, Content-Type, X-Requested-With, x-csrf-token',                         'Content-Type': undefined                     }                 })                 .then(function(response){                     console.log(response);                 });             }         }]) 

This is the controller on my backend:

   public function add()     {         $document = $this->Documents->newEntity();         $data = ['result' => 'null', 'id' => 'null'];         if ($this->request->is('post'))         {             $document = $this->Documents->patchEntity($document, $this->request->getData());             if ($this->Documents->save($document))             {                 $data = ['result' => 'success', 'id' => $document->id];             } else {                 $data = ['result' => 'error'];             }         }         $this->set(compact('data'));         $this->set('_serialize', ['data']);     } 

GOOD I DID SOMETHING DIFFERENT BUT HELP ME TO DETECT WHERE IS THE PROBLEM

first I try to use cakephp-upload. But initially with the example of the blog did not understand well how it worked so in the beginning I ran into this error I did not understand either. Now I treat in a different way, everything works until I tried to store the data in the database is here when the error occurs, Actually continued with the same error at the beginning of the post but now I know where is the problem:

After hours of many test I comment this part and work fine, but obviously not store nothing on the DataBase. With a different code. now work, but need that store the data on the database, and understand the error.

public function add() {     $document = $this->Documents->newEntity();     $data = ['result' => $this->request->getData(), 'id' => 'null'];     $file = $this->request->getData('photo');     $file['name'] =  time() . '-' . str_replace(' ', '_', $file['name']); // timestamp files to prevent clobber     if (move_uploaded_file($file['tmp_name'], WWW_ROOT . 'files/' . $file['name']))     {         //When comment this part dont have error          //but can't save in the data base my information         //         /*          $document->photo = $file['name'];         $document->descripcion = $this->request->getData('descripcion');         $document = $this->Documents->patchEntity($document, $this->request->getData());         if ($this->Documents->save($document)) {             $data = ['result' => 'success', 'id' => $document->id];         }         */      }     $this->set(compact('data'));     $this->set('_serialize', ['data']); } 

1 Answers

Answers 1

The exception is occuring at line ~80: /home/user/myapp/vendor/josegonzalez/cakephp-upload/src/Model/Behavior/UploadBehavior.php

public function beforeSave(Event $event, Entity $entity, ArrayObject $options) {     foreach ($this->config() as $field => $settings) {         if (Hash::get((array)$entity->get($field), 'error') !== UPLOAD_ERR_OK) {             HERE ---> if (Hash::get($settings, 'restoreValueOnFailure', true)) { 

The tutorial of the blog is for earlier version if cake or not ok. Check this doc: http://cakephp-upload.readthedocs.io/en/latest/examples.html

In your DocumentsTable.php you should have something like this:

$this->addBehavior('Josegonzalez/Upload.Upload', [     'path' => [], ]); 

The 'path' should not be a value, but a key to an array: 'path' => [],

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment