CakePHP3 Tutorial

Next: Building a multilingual Webapp with CakePHP UP: TOC

The objective for this chapter is to provide functionality that allows enter master/detail records such as users and their objects for sharing. Therefore we need to create:

  • A View that has a form
  • Two Table entries; one for users the other for sharing objects
  • A Controller function that validates and stores the entered data

Preparing a View for Data Entering in File .../cakephp3/src/Template/Objects/add.ctp

Add an Object for Sharing

Form->create('Objects'); echo $this->Form->input('obj_title'); echo $this->Form->input('obj_desc'); echo $this->Form->input('email'); echo $this->Form->button(__('Save')); echo $this->Form->end(); ?>

This is the controller action. This source file is in .../cakephp3/src/Controller/ObjectsController.php

Objects->newEntity();

        // generate a random primary key 
        $object->id = Text::uuid();

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

            // Check if email exists; if not create one in Table User.
            $userTable = TableRegistry::get('Users');
            $user = $userTable->find('all')->where(['email' => $this->request->data['email']])->first();

            if (empty($user)) {
                $user = $userTable->newEntity();

                // prepare data for saving
                $user->id = Text::uuid();
                $user->nick = substr($this->request->data['email'],0,3);
                $user->email = $this->request->data['email'];
                $userTable->save($user);
            } 
            $user_id = $user->id;

            // prepare data and save
            $object = $this->Objects->patchEntity($object, $this->request->data); 
            $object['user_id'] = $user_id;
            if ($this->Objects->save($object)) {
                $this->Flash->success('Your data has been saved. Please check your email for further steps');
                return $this->redirect('/');
            }
       }
    }
}

This is the Table file. This source file is in .../cakephp3/src/Model/Table/ObjectsTable.php


table('obj');
        $this->addBehavior('Timestamp');
    }
}



This is the Table file. This source file is in .../cakephp3/src/Model/Table/UsersTable.php


table('user');
        $this->addBehavior('Timestamp');
    }
}
?>
Next: Building a multilingual Webapp with CakePHP UP: TOC