简体   繁体   English

可选表单字段和CodeIgniter中的更新

[英]Optional form fields and updating in CodeIgniter

I have an edit user information -form where user can change their email address, phone number or their password. 我有一个编辑用户信息表格,用户可以在其中更改其电子邮件地址,电话号码或密码。 The problem is that some of these changes should be optional. 问题是这些更改中的一些应该是可选的。 Let's say that user wants only to change his/her email, and leave new password field empty. 假设用户只想更改他/她的电子邮件,并将新密码字段留空。 After submitting, it should only affect and update his/her email, but right now it'll also affect on the password field and updates it as an empty field. 提交后,它只会影响并更新他/她的电子邮件,但现在它还会影响密码字段并将其更新为空字段。

Here's what I've done so far. 到目前为止,这是我所做的。

View: 视图:

<?php $this->load->helper('form'); ?>
<?php $attributes = array(
        'id' => 'update_user_form'
    );
?>

<?php echo form_open('users/edit_profile', $attributes); ?>

    <div class="loading_spinner" id="loading_spinner_add_user" style="display:none;"></div>
    <div class="login_error" id="new_user_error" style="display:none">
    <span class="close_error">&times;</span>
    </div>
    <div class="front_success" id="new_user_success" style="display:none"></div>

    <div class="rowi">

        <div class="rowi1">
        <label for="email">Sähköpostiosoite</label>
        <input type="email" name="email" value="<?=$userinfo['email']?>" />
        </div>

        <div class="rowi2">
        <label for="phone_number">Puhelinnumero</label>
        <input type="text" name="phone_number" value="<?=$userinfo['phone_number']?>"/>            
        </div>
    </div>

    <div class="rowi">
        <div class="rowi1">
        <label for="password">Uusi salasana</label>
        <input type="password" name="new_password" />
        </div>

        <div class="rowi2">
        <label for="new_password_again">Uusi salasana uudelleen</label>
        <input type="password" name="new_password_again" />
        </div>
    </div>

    <div class="rowi">
        <p>Vahvista mahdolliset muutokset kirjoittamalla salasanasi allolevaan tekstikenttään.</p>

       <div class="rowi1">
       <input type="password" name="password_to_confirm" placeholder="Salasana" />
       </div>

       <div class="rowi2">
       <input type="submit" name="update_info" value="Muokkaa tietojani" class="login_submit">
       </div>
    </div>

<?php echo form_close(); ?>

Model: 模型:

public function edit_user($data, $user_id) 
{
    $data = array(
        'email' => $data['email'],
        'phone_number' => $data['phone_number'],
        'password' => $data['new_password']
        );

        $this->db->where('id', $user_id);
        $this->db->update('users', $data);
}

Controller: 控制器:

public function edit_profile()
{

   if(!$_POST)
   {
       return false;
   }

   $password_to_confirm = $this->input->post('password_to_confirm');
   $db_password = $this->user_model->password_db_check($this->session>userdata('user_id'));

        if(!$this->phpass->check($password_to_confirm, $db_password['password']))
        {

            $this->output->set_content_type('application_json');
            $this->output->set_output(json_encode(array('result'=>0, 'error' => 'Antamasi salasana ei täsmännyt käyttäjätunnuksesi salasanaan')));
            return false;
        }   

        $this->form_validation->set_rules('email', 'Sähköpostiosoite', 'valid_email|required');
        $this->form_validation->set_rules('phone_number', 'Puhelinnumero', 'min_length[7]|max_length[10]');
        $this->form_validation->set_rules('new_password', 'Salasana', 'matches[new_password_again]|min_length[8]');
        $this->form_validation->set_rules('new_password_again', 'Salasana', 'min_length[8]');

        $this->form_validation->set_message('min_length', '%s - kentässä on liian vähän merkkejä');
        $this->form_validation->set_message('matches', 'Uudet salasanat eivät täsmää');
        $this->form_validation->set_message('required', '%s - kenttä on pakollinen');
        $this->form_validation->set_message('is_unique', '%s on jo rekisteröity');

        if($this->form_validation->run() == FALSE)
        {
            $this->output->set_content_type('application_json');
            $this->output->set_output(json_encode(array('result'=>0, 'error' => $this->form_validation->error_array())));
            return false;

        }

        $edit_data = array();

           if($this->input->post('email')) 
                $edit_data['email'] = $this->input->post('email');

            if($this->input->post('phone_number'))
                $edit_data['phone_number'] = $this->input->post('phone_number');

            if($this->input->post('new_password'))
                $edit_data['new_password'] = $this->phpass->hash($this->input->post('new_password'));

        $edit_info = $this->user_model->edit_user($edit_data, $this->session->userdata('user_id'));


        if($edit_info)
        {

            $this->output->set_content_type('application_json');
            $this->output->set_output(json_encode(array('result'=>1, 'success' => 'Uusi käyttäjä lisätty')));

        } else {

            $this->output->set_content_type('application_json');
            $this->output->set_output(json_encode(array('result'=>0, 'error' => 'Tietojen päivittäminen epäonnistui')));
        }

 }

Is it possible to use ternary operators or something to check if the fields are left empty and if so, update part should ignore the blank fields. 是否可以使用三元运算符或其他方法检查字段是否为空,如果是,则更新部分应忽略空白字段。

EDIT 编辑

The only way to actually not getting that return in write context is this: 实际上在写上下文中未获得该回报的唯一方法是:

if($this->input->post('email') != "")
{
    $update_data['email'] = $this->input->post('email');
}

if($this->input->post('phone_number') != "")
{
    $update_data['phone_number'] = $this->input->post('phone_number');
}
if($this->input->post('new_password') != "")
{
    $update_data['password'] = $this->input->post('new_password');
}

But it still updates all of the fields, including those that are empty. 但是它仍然会更新所有字段,包括那些为空的字段。

Answer is No. You can't use ternary operator in your case. 答案是否定的。在这种情况下,您不能使用三元运算符。 Checkout the following code if you use ternary operator: 如果使用三元运算符,请检查以下代码:

$edit_data['email'] = ($this->input->post('email') && !empty($this->input->post('email'))) ? $this->input->post('email') : NULL;

$edit_data['phone_number'] = ($this->input->post('phone_number') && !empty($this->input->post('phone_number'))) ? $this->input->post('phone_number') : NULL;

$edit_data['new_password'] = ($this->input->post('new_password') && !empty($this->input->post('new_password'))) ? $this->input->post('new_password') : NULL;


Explanation: 说明:

If we use ternary operator, we'll force to create a $edit_data['password'] data even if the password is blank, which we don't want to. 如果使用三元运算符,即使密码为空,我们也将强制创建$edit_data['password']数据,这是我们不希望的。 If user enters the password then it'll store the password in $edit_data['password'] , but if the user leave it blank, null will get stored in $edit_data['password'] which in turn leave a blank field update. 如果用户输入密码,则它将密码存储在$edit_data['password'] ,但是如果用户将其保留为空白,则将空null存储在$edit_data['password'] ,这又将保留空白字段更新。


Solution: 解:

Use isset() and empty() functions as conditions in an if-statement if-statement使用isset()empty()作为条件

if(!empty($this->input->post('new_password')))
{
    $edit_data['new_password'] = $this->input->post('new_password');
}


UPDATE UPDATE

Send the array which you use while updating from controller and directly use it in your query. 发送从控制器进行更新时使用的数组,并在查询中直接使用它。 Check this, if user inputs email and phone_number , but not new_password 如果用户输入emailphone_number ,但不输入new_password ,请检查此选项

In Controller 在控制器中

if($this->input->post('email') != "")
{
   $update_data['email'] = $this->input->post('email');
}

if($this->input->post('phone_number') != "")
{
   $update_data['phone_number'] = $this->input->post('phone_number');
}

if($this->input->post('new_password') != "")
{
   $update_data['password'] = $this->input->post('new_password');
}

$edit_info = $this->user_model->edit_user($edit_data, $this->session->userdata('user_id'));

// Since email, phone_number, password are the column names of the table
// you can directly use $update_data array in your query
// which prevent from inserting blank values in unfilled fields 

Your array 你的数组

Array(
[email] => abc@gmail.com
[phone_number] => 9999999999
)

In Model 在模型中

public function edit_user($data, $user_id) 
{
    $this->db->where('id', $user_id);
    $this->db->update('users', $data);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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