PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, December 31, 2021

[FIXED] CakePHP 3: Hide form field based on dropdown selection

 December 31, 2021     cakephp, cakephp-3.0, drop-down-menu, javascript     No comments   

Issue

Hi I have an application form as shown in the picture in which there's a dropdown for Nationality. This form is used by local and international applicants. enter image description here

What I would love to achieve is that: CASE 1: when a local applicant selects their nationality, (Finland), the NRC and Passport fields should be shown but only NRC should be made mandatory CASE 2: when any other nationality is selected, the NRC field should be hidden and Passport field should be made mandatory.

I have managed to get CASE 1 work, it's CASE 2 where am stuck. How can I implement CASE 2 from the controller and through a JavaScript function?

Here is my form

<div class="applicants form  content">
<h3><?= __('Personal Details') ?></h3>
<?= $this->Form->create($applicant, ['type' => 'file']) ?>
<?= $this->Form->hidden('new_applicant', ['value' => '1']) ?>
<fieldset>
    <h4><?= __('My Personal Details') ?></h4>
    <h6><i>Fields Marked With (*) Are Mandatory</i></h6>
    <div class="row">
        <div class="col-sm-4">
            <?= $this->Form->control('title', ['type' => 'select', 'options' => $titles, 'disabled' => $disabled]) ?>
        </div>
        <div class="col-sm-4">
            <?= $this->Form->control('portrait', ['type' => 'file']) ?>
        </div>
        <div class="col-sm-4">
            <?= $this->Form->control('first_name', ['required' => 'required', 'placeholder' => __('First Name'), 'disabled' => $disabled]) ?>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-4">
            <?= $this->Form->control('other_names', ['placeholder' => 'Other Names', 'disabled' => $disabled]) ?>
        </div>
        <div class="col-sm-4">
            <?= $this->Form->control('last_name', ['required' => 'required', 'placeholder' => 'Last Name', 'disabled' => $disabled]) ?>
        </div>
        <div class="col-sm-4">
            <?= $this->Form->control('date_of_birth', ['id' => 'date_of_birth', 'required' => 'required', 'type' => 'text', 'placeholder' => 'YYYY/MM/DD', 'value' => $this->Time->format($applicant->date_of_birth, 'YYYY/MM/dd'), 'disabled' => $disabled]) ?>
        </div>
    </div>
    <div class="row">

        <div class="col-sm-4">
            <?= $this->Form->control('marital_status', ['type' => 'select', 'required' => 'required', 'options' => $maritalStatus]) ?>
        </div>
        <div class="col-sm-4">
            <?= $this->Form->control('nation_id', ['options' => $nations, 'required' => 'required', 'label' => __('Nationality'), 'disabled' => $disabled]) ?>
        </div>
        <div class="col-sm-4">
            <?= $this->Form->control('gender', ['type' => 'select', 'required' => 'required', 'options' => $gender, 'disabled' => $disabled]) ?>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-4">
            <?= $this->Form->control('nrc', ['id' => 'nrc', 'required' => 'required', 'type' => 'numeric', 'placeholder' => '000000/00/0', 'label' => 'NRC', 'disabled' => $disabled]) ?>
        </div>
        <div class="col-sm-4">
            <?= $this->Form->control('passport', ['placeholder' => 'Passport No.', 'disabled' => $disabled]) ?>
        </div>
    </div>
    <?= $this->Form->control('staff', ['type' => 'checkbox', 'label' => __('Member of Staff / Staff Dependent / Staff Spouse'), $checked]) ?>
    <div class="staff-form" <?= empty($checked) ? '' : 'style="display:block;"' ?>>
        <hr />
        <h4><?= __(' Member of Staff / Staff Dependent / Staff Spouse') ?></h4>
        <p>If you are either spouse, child or dependent of a member of staff, please fill-in the details below</p>
        <div class="row">
            <div class="col-sm-6">
                <?= $this->Form->control('staff_man_no') ?>
                <b>How are you related to Member of Staff?</b>
                <select>
                    <option value="child">CHILD</option>
                    <option value="spouse">SPOUSE</option>
                    <option value="memberOfStaff">MEMBER OF STAFF</option>
                </select>
            </div>
            <div class="col-sm-6">
                <?= $this->Form->control('staff_nrc_filename', [
                    'type' => 'file', 'class' => 'form-control', 'label' => __('Scanned copy of Staff NRC'),
                    '_file' => [
                        //
                        'deleteLink' => $this->Html->link(__(' [Delete]'), ['action' => 'deleteFile', 'staff_nrc_filename'])
                    ]
                ]) ?>
                <?= $this->Form->control('staff_personnel_data_filename', [
                    'type' => 'file', 'class' => 'form-control', 'label' => __('Latest Staff Personnel Data Form'),
                    '_file' => [
                        //'object' => $applicant,
                        'deleteLink' => $this->Html->link(__(' [Delete]'), ['action' => 'deleteFile', 'staff_personnel_data_filename'])
                    ]
                ]) ?>
                <?= $this->Form->control('birth_certificate_filename', [
                    'type' => 'file', 'class' => 'form-control', 'label' => __('Birth Certificate / Adoption Order'),
                    '_file' => [
                        //'object' => $applicant,
                        'deleteLink' => $this->Html->link(__(' [Delete]'), ['action' => 'deleteFile', 'birth_certificate_filename'])
                    ]
                ]) ?>
            </div>
        </div>
    </div>
    <div class="clearfix">
        <?= $this->Html->link(__('<i class="glyphicon glyphicon-home"></i>Go To Dashboard'), ['controller' => 'Applications', 'action' => 'close'], ['class' => 'btn btn-primary', 'escape' => false]) ?>
        <?= $this->Form->button(__('<i class="fa fa-save"></i>Save and Continue'), ['escape' => false, 'class' => 'pull-right btn btn-success']) ?>
    </div>
</fieldset>
<?= $this->Form->end() ?>

And this is my method in my ApplicantsController.php

public function edit()
{
    $applicant = $this->Applicants->findById(
        $this->request->session()->read('Auth.User.id'))
        ->contain(['Nations', 'Students'])->first();
    if(empty($applicant) && empty($this->request->getData('new_applicant')))
        return $this->verifyStudent();

    $applicant = empty($applicant) ? $this->Applicants->newEntity() : $applicant;

    if ($this->request->is(['patch', 'post', 'put']) && count($this->request->getData()) > 2) {
        $toSave = $this->Applicants->patchEntity($applicant, $this->request->getData());
        foreach ($this->fileFields as $field=>$name) {
            $toSave->set($field, empty($applicant->$field) ? null : $applicant->$field);
        }
        $toSave->set('id', $this->request->session()->read('Auth.User.id'));
        $toSave->set('completed', 1);

        if ($this->Applicants->save($toSave)) {
            $this->loadComponent('FileUpload');
            foreach ($this->fileFields as $field => $filename) {
                $this->_saveFile($toSave, $field, $filename);
            }
            if ($this->Applicants->save($toSave)) {
                $this->Flash->success(__('The applicant has been saved.'));
                $applicant = $toSave;
                if ($this->request->session()->check('Online.Application.id')) {
                    return $this->redirect(['controller' => 'ApplicantContacts', 'action' => 'edit']);
                } else {
                    return $this->redirect(['controller' => 'Applications', 'action' => 'add']);
                }
            }
        } else {
            $this->Flash->error(__('Failed to save, if problem persists, contact System Administrator.'));
        }
    }
    $nations = $this->Applicants->Nations->find('list', ['limit' => 300, 'valueField' => 'nationality'])
        ->where(['nationality is not'=>'TBA'])->orderAsc('nationality');

    /**$nations = $this->Applicants->Nations->find('list', ['limit' => 300, 'valueField' => 'description'])
        ->where(['code is not'=>' null'])->orderAsc('description');*/

    $titles = Utility::getTitles();
    $maritalStatus = Utility::getMaritalStatus();
    $gender = Utility::getGender();
    $this->set(compact('applicant', 'nations', 'disabilities', 'applicantContact', 'imagePath', 'gender', 'titles', 'maritalStatus'));
    $this->set('_serialize', ['applicant']);
    $this->viewBuilder()->setLayout('application');
}

And here is a javascript function in applicants.js I have been trying to create, it's incomplete

$('input[type=radio]').on('change', function(){
    if(tmp !== null) {
        tmp.hide();
    }
    tmp = $($(this).val()).show();
});

$('#nation_id').on('change',function(){
    alert('The text has been changed.');
});

How can I achieve my goal, any help will be appreciated.


Solution

okay after much thought, I noticed Cakephp defines its JavaScript files in /webroot/js/ folder for specific controller. All I had to do was create an applicants.js file and modify my earlier JavaScript function I shared as follows

$('#nation_id').change(function () {
    if ($(this).val() == 42) {
        $("#nrc_div").show();
        $('#passport_div').show();
        document.getElementById("nrc").required = true;
        document.getElementById("passport").required = false;
    } else {
        $("#nrc_div").hide();
        $('#passport_div').show();
        document.getElementById("nrc").required = false;
        document.getElementById("passport").required = true;
    }
});

Value 42 is the id of FINLAND. Then I added id's to my nrc div and passport div in my edit.ctp form as follows:

NRC div

<div id="nrc_div" class="col-sm-4" style="display:none;">
            <?= $this->Form->control('nrc', ['id' => 'nrc', 'type' => 'numeric', 'placeholder' => '000000/00/0', 'label' => 'NRC', 'disabled' => $disabled]) ?>
        </div>

and Passport div

<div id="passport_div" class="col-sm-4" style="display:none;">
            <?= $this->Form->control('passport', ['placeholder' => 'Passport No.', 'disabled' => $disabled]) ?>
        </div>


Answered By - Mann Tazho
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing