Error sending post to controller cakephp 3

0

I collect the form data to save them in a localStorage variable

function recuperaDatos(){

            var elForm = document.querySelector("#form1"), //O simplemente 'form1'
            valores = []; //Array en el que se guardarán los valores

            [].forEach.call(elForm.elements, function(elemento){ //Recorro el conjunto de elementos
                if (elemento.value == " "  || elemento.value == null) {

                }
                valores.push(elemento.value); //Guardo el valor de cada elemento en el array
            });

            //Guardo todo de manera local
            datosLocal += localStorage.form1 = JSON.stringify({
                elementos: elForm.innerHTML, //Los elementos del formulario
                id: elForm.id || "", //El 'id' del formulario o una cadena vacía
                method: "POST", //El método establecido o "GET"
                //action: "add", //La dirección hacia la que se enviarán los datos o una cadena vacía
                enctype: elForm.enctype || "", //El tipo de contenido del formulario o una cadena vacía
                datos: valores //El array con los valores de los elementos del formulario
            });

        }

And that variable sent the data to a function that is in the controller that it saves in the database in the following way:

function enviaPost(){
    var caed = '/caed';
        if ( window.location.host != 'nodo.pw' || window.location.host != 'elmaguire.local:5757' ) {
            caed = '';
        } 
     var guardado = JSON.parse(datosLocal);
 console.log(guardado['datos']);        

           $.ajax({
                type:"POST",
                url: url+ "/users/add", 
                dataType: 'JSON',            
                data: JSON.stringify(guardado['datos']),                
                success: function (data) { 
                    console.log('Sin conexion a internet. Los datos se gusrdaran localmente para enviarlos al restablecer la conexion a internet');                                    
                    console.log(data);                                    
                },
                error: function(e) {
                        console.log( 'error add - not found'+e);                
                }
            }); 


}

and my the function that keeps in the base is the following:

public function add($type_user = '')
    {      

        $idLoggedUser = $this->Auth->user('id');
        $role = $this->Auth->user('role');
        $cnterUsrLogged =  $this->Auth->user('center_id');

        $user_id = '';    
        $errors = [];
        date_default_timezone_set('America/Mexico_City');
        $date = date('Y-m-d');        


        $roles   = $this->Users->Roles->find('Roles',[
                                                    'profile' =>$role,
                                                    'idLoggedUser'=>$idLoggedUser,
                                                    'idUserEdit'=>''
                                                    ])->combine('name', 'full_name');

        $centros = $this->Users->Centers->find('Centers',[
                                                    'profile' =>$role,
                                                    'center_id' => $cnterUsrLogged
                                                    ]);  
        $centers        = $centros->combine('id', 'plantel');     //para select


        $estados        = $this->Users->States->find();                     
        $states         = $estados->combine('id', 'name');        //para select 

        $discapacidades      = $this->Users->Disabilities->find();
        $disabilities        = $discapacidades->combine('id', 'nombre');       //para select        

        $discapEspecificas   = $this->Users->Specificdisabilities->find();     
        $specificdisabilities= $discapEspecificas->combine('id', 'nombre');     //para select


        //Inicia manejo de datos del formulario
        $user = $this->Users->newEntity();  


        if ($this->request->is('post')) {  

            $this->request->data['owners'][0]['id'] = $this->Auth->user('id'); 
            $this->request->data['owners'][0]['_joinData']['notification_id'] = '1';
            $this->request->data['owners'][0]['_joinData']['date'] = date('Y-m-d');  

            if($role == 'auxiliar'){
                $this->request->data['owners'][1]['id'] = $this->Auth->user('user_created_id');;
                $this->request->data['owners'][1]['_joinData']['notification_id'] = '1'; 
                $this->request->data['owners'][1]['_joinData']['date'] = date('Y-m-d'); 
            }

            $user = $this->Users->patchEntity($user, $this->request->getData(),['associated' => ['Owners._joinData']]);

            //$this->request->data['foto'] = $this->request->data['fotousuario'];
            //$this->request->data['firma'] = $this->request->data['firmausuario'];

            $user->fecha_inscripcion = $date;
            $user->full_name =  $user->nombre .' '.$user->ap_paterno.' '.$user->ap_materno;
            $user->user_created_id = $this->Auth->user('id');
            $user->categoria  = 'Activo';
            if($role == 'auxiliar'){ 
                 $user->role = 'estudiante';
                 $user->center_id = $cnterUsrLogged;
            } 

            // debug( $user); exit;
           //Para generar la matricula 
           if ( $user->role == 'estudiante') {    
                $matricula = $this->matricula($estados, $user->state_id, $discapacidades , $user->disability_id, $discapEspecificas, $user->specificdisability_id, $user->center_id);
                $user->matricula = $matricula;  
            }

            //cargar Imagen             
            if(!$user->errors() && $this->request->data['foto']['error'] != 4){                
                $fileOK = $this->uploadFiles('files'.DS.'Users', $this->request->data['foto'], $user->curp,'foto');               
                if(array_key_exists('filename', $fileOK)) {            
                    $user->foto = $fileOK['filename'];
                    $user->alt  = $fileOK['alt'];
                    $user->dir  = $fileOK['dir'];
                }
            }
            //carga firma

            if(!$user->errors() && $this->request->data['firma']['error'] != 4){ 
               //debug($this->request->data['firma']); exit;             
                $file_ok = $this->uploadFiles('files'.DS.'Users', $this->request->data['firma'], $user->curp,'firma');               
                if(array_key_exists('filename', $file_ok)) {            
                    $user->firma = $file_ok['filename'];
                    $user->alt_firma  = $file_ok['alt'];
                    $user->dir_firma  = $file_ok['dir'];
                }
            }
            //debug($this->request->data); 

            $errors = $user->errors(); 



            if ($this->Users->save($user, ['associated' => ['Owners._joinData']])) {

                //Guarda la notificacion para el id del nuevo usuario 
                $notificationsUsers = TableRegistry::get('notificationsUsers');
                $notifUsr = $notificationsUsers->newEntity();
                $notifUsr->date     = date('Y-m-d');
                $notifUsr->owner_id = $user->id;
                $notifUsr->user_id  = $user->id;
                $notifUsr->notification_id  = 1;
                $notificationsUsers->save( $notifUsr);   

                //send email
                $content_notif = $this->Users->Notifications->find('all', ['conditions' => ['type' => 'registro'] ])
                                                             ->first()->toArray() ; 

                $user['notifications_data'] = $content_notif; 
                $this->getMailer('User')->send('generic_email', [$user]); 

                if(!$this->request->is('ajax')){
                    return $this->redirect(['action' => 'edit'.'/'.$user->id.'/successadd']);
                }else{
                    echo "ok-ajax";
                }
            }else if($this->request->is('ajax')){
             print_r($errors);
             // guardar estos  errores en una  variable  de  sesion o en algun lugar;
             exit;
           }
           // $this->Flash->error(__('El usuario no se guardó. Por favor, intente nuevamente.'));
        }

        // model y action variables  para  pasar  al  elemento lwsuccesUsers - muestra  una ventana de notificacion
        $model = 'users'; 
        $action = 'edit'; // para que despues de darlo de alta regrese a la pantalla edit

        $this->set(compact('user','centers','roles','specificdisabilities','disabilities','date','cnterUsrLogged','states','type_user','user_id','errors','model','action','role'));
        $this->set('_serialize', ['user']);
    }

Only when saving sends me an error does not save it if you change the way you receive the data. help!

    
asked by Jasi Enriquez 19.01.2018 в 02:49
source

1 answer

0

Well I could solve it first in my cuntrolador I was missing the following line:

 $this->response->disableCache();     
          $this->autoRender = false;

in second because it did not correctly obtain data is as follows:

$this->request->data['datos'];

That's how the error stopped me from leaving. I hope you serve them -

    
answered by 22.01.2018 / 20:32
source