Cakephp使用saveAll并指定只有哪些型号 [英] Cakephp use saveAll and specify which models only

查看:298
本文介绍了Cakephp使用saveAll并指定只有哪些型号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我对cakephp比较新,现在我试图使用saveall()并保存个别模型取决于用户选择的寄存器的角色。

Im new to relatively new to cakephp, right now I'm trying to use saveall() and save individual models depending on the role the user chose for the register.

这是我的视图:

    <?php echo $this->Form->create('User', array('type' => 'file')); ?>
    <fieldset>
        <legend><?php echo __('Add User'); ?></legend>
        <?php
            echo $this->Form->file('User.user_image');
            echo $this->Form->input('User.name', array( 'label' => 'Nombre'));
            echo $this->Form->input('User.last_name', array( 'label' => 'Apellidos' ));
            echo $this->Form->input('User.email', array( 'label' => 'E-Mail' ));
            echo $this->Form->input('User.password', array( 'label' => 'Contraseña' ));
            echo $this->Form->input('User.phone', array( 'label' => 'Telefono' ));
            //echo $this->Form->input('created_ip_connection');
            //echo $this->Form->input('last_ip_connection'); 
            echo $this->Form->input('User.group_id', array('empty' => 'Elige un rol',  'label' => 'Rol de Usuario'));
        ?>
        <div style="display: none;" id="companyAdd">
            <legend><?php echo __('Datos de Compañia'); ?></legend>
            <?php
                echo $this->Form->input('Address.exterior_number', array( 'label' => 'Numero Exterior', 'required' => false ));
                echo $this->Form->input('Address.internal_number', array( 'label' => 'Numero Interior', 'required' => false ));
                echo $this->Form->input('Address.street', array( 'label' => 'Calle', 'required' => false ));
                echo $this->Form->input('Address.suburby', array( 'label' => 'Colonia', 'required' => false ));
                echo $this->Form->input('Address.country_id', array('empty' => 'Selecciona País', 'label' => 'Pais', 'required' => false));
                echo $this->Form->input('Address.state_id', array('empty' => 'Selecciona País', 'label' => 'Estado', 'required' => false));
                echo $this->Form->input('Address.city_id', array('empty' => 'Selecciona Estado', 'label' => 'Municipio', 'required' => false));
                echo $this->Form->input('Company.name', array( 'label' => 'Nombre de Compañia', 'required' => false ));
                echo $this->Form->input('Company.description', array( 'label' => 'Descripción de Compañia', 'required' => false ));
                echo $this->Form->input('Company.bank_acc', array( 'label' => 'Cuenta de Banco', 'required' => false ));
                echo $this->Form->input('Company.rfc', array( 'label' => 'RFC', 'required' => false ));
            ?>
        </div>
        <div style="display: none;" id="userAdd">
            <legend><?php echo __('Datos de Comprador/Proveedor'); ?></legend>
            <?php
                echo $this->Form->input('Buyer.company_id', array('empty' => 'Elige Comapñia', 'label' => 'Compañia', 'required' => false));
            ?>
        </div>
    </fieldset>

<?php echo $this->Form->end(__('Registrar')); ?>

这是我的控制器:

public function register(){
    $this->layout = 'generalLayout'; 
    if ($this->request->is('post')) {
        if($this->request->data['User']['group_id'] == 1){
            $this->User->create();
            if(!empty($this->data))
            {
                //Check if image has been uploaded
                if(!empty($this->data['User']['user_image']['name']))
                {
                    $file = $this->data['User']['user_image']; //put the data into a var for easy use

                    $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
                    $arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions

                    //only process if the extension is valid
                    if(in_array($ext, $arr_ext))
                    {
                        //do the actual uploading of the file. First arg is the tmp name, second arg is
                        //where we are putting it
                        $destinationPath = 'images\users\\';
                        $randomCode = substr(md5(uniqid(rand(), true)), 5, 5);
                        $filename = $this->data['User']['name'].'_'.$randomCode."_".$file['name'];
                        move_uploaded_file($file['tmp_name'], WWW_ROOT . $destinationPath . $filename);

                        //prepare the filename for database entry
                        $this->request->data['User']['user_image'] = $filename;
                    }
                }
                $this->request->data['User']['created_ip_connection'] = $this->request->clientIp();
                $this->request->data['User']['last_ip_connection'] = $this->request->clientIp();
                if ($this->User->saveAll($this->request->data['User'])) {
                    $this->Session->setFlash(__('The user has been saved.'));
                    return $this->redirect(array('action' => 'register'));
                } else {
                    $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
                }
                //now do the save
                //$this->products->save($this->data) ;
            }
        }
        if($this->request->data['User']['group_id'] == 2){
            $this->User->create();
            if(!empty($this->data))
            {
                //Check if image has been uploaded
                if(!empty($this->data['User']['user_image']['name']))
                {
                    $file = $this->data['User']['user_image']; //put the data into a var for easy use

                    $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
                    $arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions

                    //only process if the extension is valid
                    if(in_array($ext, $arr_ext))
                    {
                        //do the actual uploading of the file. First arg is the tmp name, second arg is
                        //where we are putting it
                        $destinationPath = 'images\users\\';
                        $randomCode = substr(md5(uniqid(rand(), true)), 5, 5);
                        $filename = $this->data['User']['name'].'_'.$randomCode."_".$file['name'];
                        move_uploaded_file($file['tmp_name'], WWW_ROOT . $destinationPath . $filename);

                        //prepare the filename for database entry
                        $this->request->data['User']['user_image'] = $filename;
                    }
                }
                $this->request->data['User']['created_ip_connection'] = $this->request->clientIp();
                $this->request->data['User']['last_ip_connection'] = $this->request->clientIp();
                if ($this->User->saveAll($this->request->data)) {
                    $this->Session->setFlash(__('The user has been saved.'));
                    return $this->redirect(array('action' => 'register'));
                } else {
                    $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
                }
                //now do the save
                //$this->products->save($this->data) ;
            }
        }
        if($this->request->data['User']['group_id'] == 3){
            $this->Session->setFlash(__('Group 3 Happened'));
            return $this->redirect(array('action' => 'register'));
        }
        /*$this->Session->setFlash(__('Nothing Happened'));
        return $this->redirect(array('action' => 'register'));*/

    }
    $groups = $this->User->Group->find('list');
    $this->set(compact('groups'));
    $companies = $this->User->Company->find('list');
    $this->set(compact('companies'));
}

和我的模型关系

public $hasOne = array(
    'Buyer' => array(
        'className' => 'Buyer',
        'foreignKey' => 'user_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),
    'Company' => array(
        'className' => 'Company',
        'foreignKey' => 'user_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),
    'Provider' => array(
        'className' => 'Provider',
        'foreignKey' => 'user_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

我想只发送所需的信息形式到控制器。或者在控制器中只使用发送的模型来保存我想要的模型。我如何使这项工作。 saveAll不工作,因为我通过表单发送没有信息的其他模型。我如何使这项工作?

I want to either send only the information needed (Meaning the models depending on the group chosen.) through the form to the controller. or in the controller use only the models sent to save the models that I want. How could I make this work. saveAll does not work cause Im sending other models with no information through the form as well. How could I make this work ?

此外,如何获取刚刚保存的用户的ID?

Also how do I get the id of the user I just saved?

推荐答案

Ok我找到了如何做。我使用了保存相关模型数据方法。我只是使用我想从数据发送的信息根据正在创建的用户的类型的形式。我离开了视图和模型不变。我只更改了group_id为2(正常用户)和3(半管理员用户)时的部分的控制器。使用模型关系和发送的信息我可以使用save()方法,每个模型取决于我给出的信息。这里是代码我希望它帮助某人:

Ok I found out how to do it. I used the Saving Related Model Data method. I just use the information I want from the data send by the form depending on the type of the user being created. I left the view and the model untouched. I only changed the controller for the parts of when the group_id is 2(Normal User) and 3(Semi-Admin User). Using the model relations and the information being sent I could use the save() method with each model depending on the information I was given. Here is the code I hope It helps someone:

$this->layout = 'generalLayout'; 
    if ($this->request->is('post')) {
        if($this->request->data['User']['group_id'] == 1){
            $this->User->create();
            if(!empty($this->data))
            {
                //Check if image has been uploaded
                if(!empty($this->data['User']['user_image']['name']))
                {
                    $file = $this->data['User']['user_image']; //put the data into a var for easy use

                    $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
                    $arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions

                    //only process if the extension is valid
                    if(in_array($ext, $arr_ext))
                    {
                        //do the actual uploading of the file. First arg is the tmp name, second arg is
                        //where we are putting it
                        $destinationPath = 'images\users\\';
                        $randomCode = substr(md5(uniqid(rand(), true)), 5, 5);
                        $filename = $this->data['User']['name'].'_'.$randomCode."_".$file['name'];
                        move_uploaded_file($file['tmp_name'], WWW_ROOT . $destinationPath . $filename);

                        //prepare the filename for database entry
                        $this->request->data['User']['user_image'] = $filename;
                    }
                }
                $this->request->data['User']['created_ip_connection'] = $this->request->clientIp();
                $this->request->data['User']['last_ip_connection'] = $this->request->clientIp();
                if ($this->User->saveAll($this->request->data['User'])) {
                    $this->Session->setFlash(__('The user has been saved.'));
                    return $this->redirect(array('action' => 'register'));
                } else {
                    $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
                }
                //now do the save
                //$this->products->save($this->data) ;
            }
        }
        if($this->request->data['User']['group_id'] == 2){
            $this->User->create();
            if(!empty($this->data))
            {
                //Check if image has been uploaded
                if(!empty($this->data['User']['user_image']['name']))
                {
                    $file = $this->data['User']['user_image']; //put the data into a var for easy use

                    $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
                    $arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions

                    //only process if the extension is valid
                    if(in_array($ext, $arr_ext))
                    {
                        //do the actual uploading of the file. First arg is the tmp name, second arg is
                        //where we are putting it
                        $destinationPath = 'images\users\\';
                        $randomCode = substr(md5(uniqid(rand(), true)), 5, 5);
                        $filename = $this->data['User']['name'].'_'.$randomCode."_".$file['name'];
                        move_uploaded_file($file['tmp_name'], WWW_ROOT . $destinationPath . $filename);

                        //prepare the filename for database entry
                        $this->request->data['User']['user_image'] = $filename;
                    }
                }
                $this->request->data['User']['created_ip_connection'] = $this->request->clientIp();
                $this->request->data['User']['last_ip_connection'] = $this->request->clientIp();
                if ($this->User->save($this->request->data['User'])) {
                    //Obtener el Id de user guardado
                    $userId = $this->User->id;
                    $this->request->data['Buyer']['user_id'] = $userId;
                    $this->request->data['Provider'] = $this->request->data['Buyer'];
                    if ($this->User->Buyer->save($this->request->data['Buyer']) && $this->User->Provider->save($this->request->data['Provider'])){
                        $this->Session->setFlash(__('The user has been saved.'));
                        return $this->redirect(array('action' => 'register'));
                    } else {
                        $this->Session->setFlash(__('The Buyer or Provider could not be saved. Please, try again.'));
                    }

                } else {
                    $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
                }
                //now do the save
                //$this->products->save($this->data) ;
            }
        }
        if($this->request->data['User']['group_id'] == 3){
            /*echo print_r($this->request->data);
            return false;*/
            $this->User->create();
            if(!empty($this->data))
            {
                //Check if image has been uploaded
                if(!empty($this->data['User']['user_image']['name']))
                {
                    $file = $this->data['User']['user_image']; //put the data into a var for easy use

                    $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
                    $arr_ext = array('jpg', 'jpeg', 'gif'); //set allowed extensions

                    //only process if the extension is valid
                    if(in_array($ext, $arr_ext))
                    {
                        //do the actual uploading of the file. First arg is the tmp name, second arg is
                        //where we are putting it
                        $destinationPath = 'images\users\\';
                        $randomCode = substr(md5(uniqid(rand(), true)), 5, 5);
                        $filename = $this->data['User']['name'].'_'.$randomCode."_".$file['name'];
                        move_uploaded_file($file['tmp_name'], WWW_ROOT . $destinationPath . $filename);

                        //prepare the filename for database entry
                        $this->request->data['User']['user_image'] = $filename;
                    }
                }
                //Save the user 
                $this->request->data['User']['created_ip_connection'] = $this->request->clientIp();
                $this->request->data['User']['last_ip_connection'] = $this->request->clientIp();
                if ($this->User->save($this->request->data['User'])) {
                    //Get the id of the user I just saved
                    $userId = $this->User->id;
                    if ($this->User->Company->Address->save($this->request->data["Address"])) {
                        $addressId = $this->User->Company->Address->id;
                        $this->request->data['Company']['user_id'] = $userId;
                        $this->request->data['Company']['address_id'] = $addressId;
                        $this->request->data['Company']['permision'] = true;
                        if ($this->User->Company->save($this->request->data["Company"])) {
                            $companyId = $this->User->Company->id;
                            $this->request->data['Buyer']['user_id'] = $userId;
                            $this->request->data['Buyer']['company_id'] = $companyId;
                            $this->request->data['Provider'] = $this->request->data['Buyer'];
                            if ($this->User->Buyer->save($this->request->data['Buyer']) && $this->User->Provider->save($this->request->data['Provider'])){
                                $this->Session->setFlash(__('The user has been saved.'));
                                return $this->redirect(array('action' => 'register'));
                            } else {
                                $this->Session->setFlash(__('The Buyer or Provider could not be saved. Please, try again.'));
                            }
                        } else {
                            $this->Session->setFlash(__('The company could not be saved. Please, try again.'));
                        }
                    } else {
                        $this->Session->setFlash(__('The Address could not be saved. Please, try again.'));
                    }
                } else {
                    $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
                }



                //now do the save
                //$this->products->save($this->data) ;
            }
        }
        /*$this->Session->setFlash(__('Nothing Happened'));
        return $this->redirect(array('action' => 'register'));*/

    }
    $groups = $this->User->Group->find('list');
    $this->set(compact('groups'));
    $companies = $this->User->Company->find('list');
    $this->set(compact('companies'));

这篇关于Cakephp使用saveAll并指定只有哪些型号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆