CakePHP 3 i jQuery - opcjonalne pola
W tej części zaimplementujemy pokazywanie i ukrywanie opcjonalnych pól formularza za pomocą jQuery. Załóżmy, że mamy dwa typy użytkowników osoba fizyczna i firma. Jeden lub drugi musi być wprowadzony, ale nie chcemy wymagać informacji o firmie dla osoby fizycznej lub odwrotnie. Możemy więc włączyć/wyłączyć wymagania i wyświetlić/ukryć sekcje na podstawie wyboru. Najpierw w pliku src/Template/Layout/default.ctp dodajemy w sekcji head bibliotekę jQuery.
Następnie w formularzu dodawania użytkownika /src/Template/Users/add.ctp dodajemy pole wyboru i używamy jQuery do pokazywania i ukrywania oraz włączania i wyłączania wymaganych pól.
- echo $this->Html->script('http://code.jquery.com/jquery.min.js');
Teraz, w zależności co użytkownik wybierze firmę lub osobę fizyczną, wyświetli się tylko ta sekcja, która jest potrzebna i tylko ta sekcja będzie miała ustawione wymagane atrybuty.
- <?php echo $this->Form->input('user', ['type' => 'radio', 'label' => 'user is:', 'options' => ['Business', 'Individual'], 'required' => true]); ?>
- <div class="business" style="display:none">
- <?php
- echo $this->Form->input('business_name', ['required' => true]);
- echo $this->Form->input('business_telephone');
- echo $this->Form->input('business_address', ['required' => true]);
- echo $this->Form->input('business_city', ['required' => true]);
- echo $this->Form->input('business_state', ['required' => true, 'options' => $states]);
- echo $this->Form->input('business_zip', ['required' => true]);
- ?>
- </div>
- <div class="individual" style="display:none">
- <?php
- echo $this->Form->input('name', ['required' => true]);
- echo $this->Form->input('telephone');
- echo $this->Form->input('address', ['required' => true]);
- echo $this->Form->input('city', ['required' => true]);
- echo $this->Form->input('state', ['required' => true, 'options' => $states]);
- echo $this->Form->input('zip', ['required' => true]);
- ?>
- </div>
- <script type="text/javascript">
- if (jQuery('#user-0').is(':checked')) {
- showAndRequire('.business', true);
- showAndRequire('.individual', false);
- } else if (jQuery('#user-1').is(':checked')) {
- showAndRequire('.individual', true);
- showAndRequire('.business', false);
- }
- jQuery('#user-0').click(function() {
- showAndRequire('.business', true);
- showAndRequire('.individual', false);
- });
- jQuery('#user-1').click(function() {
- showAndRequire('.individual', true);
- showAndRequire('.business', false);
- });
- function showAndRequire(section, onOff) {
- jQuery(section).toggle(onOff);
- if (onOff) {
- jQuery(section + ' .required input').attr('required', onOff);
- jQuery(section + ' .required select').attr('required', onOff);
- } else {
- jQuery(section + ' .required input').removeAttr('required');
- jQuery(section + ' .required select').removeAttr('required');
- }
- }
- </script>