简体   繁体   中英

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. 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.


Solution:

Use isset() and empty() functions as conditions in an if-statement

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


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

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);
}

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