</> Code The Pixel

CakePHP 4 Dynamic Input and Save Multiple Entities

Asyraf Wahi Anuar - March 21, 2021

Estimated reading time: 5 minutes, 21 seconds

When developing a web application, a dynamic input usually will be used to complete some of the tasks such as dynamically inserting data or bulk data. Using jQuery, the dynamic input can be easily generated even there are lots of web articles/tutorials that have been published regarding this matter but this tutorial was specifically focused on generating dynamic input for CakePHP 4 and saving it into the database. The focus of this tutorial is to create the dynamic input field and save the multiple entities.

Insert jQuery
Load the jQuery in your template file/view. Recommended to use CDN:

<?= $this->Html->script('https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js'); ?>

The Dynamic Input Form
In this tutorial, the dynamic data is the users' data which include i) fullname; ii) username; iii) email; iv) password; v) role; vi) status and; vii) verified. This process is used to bulk register a user account where each of the aforementioned data is required. Create a form known as bulk_insert.php in …templates/Users which contain the following codes:

<?= $this->Form->create() ?>
    <table class="table table-bordered" id="dynamic_field">  
             <?php echo $this->Form->control('0.user_detail.fullname', ['class' => 'form-control','required' => false,'label' => false, 'type' => 'text', 'placeholder' => 'Fullname', 'id' => '0-user-detail-fullname']); ?>
             <?php echo $this->Form->control('0.username', ['class' => 'form-control','required' => false,'label' => false, 'type' => 'text', 'placeholder' => 'Username', 'id' => '0-username']); ?>
             <?php echo $this->Form->control('0.email', ['class' => 'form-control','required' => false,'label' => false, 'type' => 'text', 'placeholder' => 'Email', 'id' => '0-email']); ?>
             <?php echo $this->Form->control('0.password', ['class' => 'form-control','required' => false,'label' => false, 'type' => 'password', 'placeholder' => 'Password', 'id' => '0-password']); ?>
             <?php echo $this->Form->control('0.user_group_id', ['options' => $userGroups, 'default' => '3', 'empty' => false, 'class' => 'form-control','required' => false,'label' => false, 'id' => '0-user-group-id']); ?>
            <?php echo $this->Form->checkbox('0.status', [
                'class' => 'form-control',
                'type' => 'checkbox']); ?>
            <?php echo $this->Form->checkbox('0.is_email_verified', [
                'class' => 'form-control',
                'type' => 'checkbox']); ?>
             <td><button type="button" name="add" id="add" class="btn btn-outline-primary btn-flat"><i class="fas fa-plus"></i></button></td>  
<?= $this->Form->button(__('Submit'),['class' => 'btn btn-outline-primary btn-flat']) ?>
<?= $this->Form->end() ?>

Did you notice the field naming convention? Any dots in your field names will be converted into nested request data. This is very important when you want to save multiple entities at once.

The Dynamic Input Script
Include the following script at the end of your input form.

      var i=1;  
            '<tr id="row'+i+'">'+
            '<td><?php echo $this->Form->control("'+i+'.user_detail.fullname",["class" => "form-control","required" => false,"label" => false, "type" => "text", "placeholder" => "Fullname"]); ?></td>'+
            '<td><?php echo $this->Form->control("'+i+'.username",["class" => "form-control","required" => false,"label" => false, "type" => "text", "placeholder" => "Username"]); ?></td>'+
            '<td><?php echo $this->Form->control("'+i+'.email",["class" => "form-control","required" => false,"label" => false, "type" => "text", "placeholder" => "Email"]); ?></td>'+
            '<td><?php echo $this->Form->control("'+i+'.password",["class" => "form-control","required" => false,"label" => false, "type" => "password", "placeholder" => "Password"]); ?></td>'+
            '<td><?php echo $this->Form->control("'+i+'.user_group_id", ["options" => $userGroups, "default" => "3", "empty" => false, "class" => "form-control","required" => false,"label" => false]); ?></td>'+
            '<td><?php echo $this->Form->checkbox("'+i+'.status", ["class" => "form-control","type" => "checkbox"]); ?></td>'+
            '<td><?php echo $this->Form->checkbox("'+i+'.is_email_verifiedx", ["class" => "form-control","type" => "checkbox"]); ?></td>'+
            '<td><button type="button" name="remove" id="'+i+'" class="btn btn-outline-danger btn-flat btn_remove"><i class="fas fa-times"></i></button></td>'+
      $(document).on('click', '.btn_remove', function(){  
           var button_id = $(this).attr("id");   

The Controller
The following codes are used to process the dynamic form and save it into the database using saveMany method as shown below.

public function bulkRegister()
    $users = $this->getTableLocator()->get('Users');
    $entities = $users->newEntities($this->request->getData());
    foreach ($entities as $entity) {
        if ($users->saveMany($entities)) {
            $this->Flash->success(__('The users has been saved.'));
            return $this->redirect(['action' => 'index']);
        $this->Flash->error(__('The users could not be saved. Please, try again.'));

The following figure shows the dynamic input form.

That all. Happy coding :)

Cite this article (APA 6th Edition)

CakePHP 4 Print PDF Using CakePDF
June, 17 2020
CakePHP 4 jQuery Date Time Picker
October, 01 2018
CakePHP 4 Authentication Using Auth...
May, 14 2020
CakePHP 4 Export To CSV
May, 29 2020
CakePHP 4 Authentication Using...
May, 11 2020
CakePHP 4 File Upload Using Proffer Plugin
May, 15 2020
CakePHP 4 Find, Sort & Count
June, 02 2020
Sharing Link
Click the icon to share