简体   繁体   中英

cakephp saveall with dynamic number of elements in the form

// add.ctp

<?php echo $this->Form->create('City');?>
    <fieldset>

        <?php 
        echo $this->Form->input('City.city_name');
        echo $this->Form->input('City.city_latitude');
        echo $this->Form->input('City.city_longitude');
        ?>
        <div class="add_more_city"><button class="btn green">Add More</button></div>
        <?php echo $this->Form->submit('Save', array('class' => 'form-submit',  'title' => 'Click here to add the city')); ?>
    </fieldset>
<?php echo $this->Form->end(); ?>
    <script>
    $(document).ready(function(){
        $('.add_more_city').click(function(e){
            e.preventDefault();
            $(this).before('City Name<input name="data[City][city_name]" maxlength="100" type="text" id="CityCityName" required="required"/>City Latitude<input name="data[City][city_latitude]" step="any" type="number" id="CityCityLatitude" required="required"/></div><div class="input number required"><label for="CityCityLongitude">City Longitude</label><input name="data[City][city_longitude]" step="any" type="number" id="CityCityLongitude" required="required"/></div>');
        });
    });
    </script>

//City Controller

public function add() {
        if(!$this->Session->check('Auth.User')){
            $this->redirect(array('controller'=>'users','action' => 'login'));      
        }else{
            if(AuthComponent::user('role')=='Admin'){
                if ($this->request->is('post')) {    
                    $this->City->create();
                        if ($this->City->saveAll($this->request->data)) {

                            $this->Session->setFlash(__('City has been added '));
                            return $this->redirect(array('controller' => 'cities','action' => 'add'));
                        } else {
                            $this->Session->setFlash(__('The city has not added. Please, try again.'));
                        } 
                }
            }else{
                $this->Session->setFlash(__('You are not authorized to access it'));
                $this->redirect(array('controller'=>'users','action' => 'login'));
            }
        }
    }

//Model

<?php
    App::uses('AuthComponent', 'Controller/Component');
    class city extends AppModel {
         public $validate = array(
           'city_name' => array(
            'nonEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'A city name is required',
                'allowEmpty' => false
            ),
            'between' => array(
                'rule' => array('between', 3, 100),
                'required' => true,
                'message' => 'City must be between 3 to 100 characters'
            ),
            'valid' => array(
                'rule'    => "/[a-zA-Z0-9]+(?:[ '-][a-zA-Z0-9]+)*/",
                'message' => 'City can only be letters, numbers, comma and hyphen'
            )
        ),

        'city_latitude' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'A Latitude is required'
            ),
            'valid' => array(
                'rule'=> '/^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?)/',
                'message'=> 'Valid latitude is required'
            )

        ),
        'city_longitude' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'A Longitude is required'
            ),
            'valid' => array(
                'rule'=> '/\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/',
                'message'=> 'Valid Longitude is required'
            )
        )

    );


        /**
     * Before isUniqueUsername
     * @param array $options
     * @return boolean
     */


    }

?>

I want to use the saveAll to save multiple city data together. Form to add text input to add multiple city is triggered with the help of add more button(java function). Cakephp saveAll is not working. could you help me to do that

I got my solution. The problem was with the field. I am dynamically updating the name parameter of the form.

   <?php echo $this->Form->create('City');?>
        <fieldset>
        <?php 
        echo $this->Form->input('city_name', array('name' => 'City[0][city_name]'));
echo $this->Form->input('city_latitude', array('name' => 'City[0][city_latitude]'));
echo $this->Form->input('city_longitude', array('name' => 'City[0][city_longitude]'));
        ?>
        <div class="extra"></div>
        <div class="add_more_city" id="add_more_1"><button class="btn green">Add More</button></div>
        <?php echo $this->Form->submit('Save', array('class' => 'form-submit',  'title' => 'Click here to add the city')); ?>
    </fieldset>
<?php echo $this->Form->end(); ?>





<script>
    $(document).ready(function(){
        $('.add_more_city').click(function(e){
            e.preventDefault();
            var get_id=$('.add_more_city').attr('id');
            var split_id=get_id.split('_');
            var id = parseInt(split_id[2]);
            var id_update =id+1;
            $('.add_more_city').attr('id','add_more_'+id_update);
            $('.extra').before(' <div class="input text"><label for="CityCityName">City Name</label><input name="City['+id+'][city_name]" maxlength="100" type="text" id="CityCityName"/></div><div class="input number"><label for="CityCityLatitude">City Latitude</label><input name="City['+id+'][city_latitude]" step="any" type="number" id="CityCityLatitude"/></div><div class="input number"><label for="CityCityLongitude">City Longitude</label><input name="City['+id+'][city_longitude]" step="any" type="number" id="CityCityLongitude"/></div></div>');
        });
    });
    </script>

Change the field names -

echo $this->Form->input('city_name', array('name' => 'City[][city_name]'));
echo $this->Form->input('city_latitude', array('name' => 'City[][city_latitude]'));
echo $this->Form->input('city_longitude', array('name' => 'City[][city_longitude]'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM