tags:

views:

317

answers:

1

I'm using URIs to direct a function in a library... View File (It's huge, so I'm just posting the opening line):

<?php print form_open('survey',array('class'=>'horizontal','id'=>'form_survey'))?>

Library:

function survey_form($container)
{
    $id = $this->CI->session->userdata('id');
    // Setup fields
    for($i=1;$i<18;$i++){
      $fields["a_".$i] = 'Question '.$i;
    }
    for($i=1;$i<24;$i++){
      $fields["b_".$i] = 'Question '.$i;
    }
    $fields["firstname"] = "First Name";
    $fields["lastname"] = "Last Name";
    $fields["phone"] = "Phone";
    $fields["company_name"] = "Company Name";
    $fields['company_address'] = "company_address";
    $fields['company_phone'] = "company_phone";
    $fields['company_state'] = "company_state";
    $fields['company_city'] = "company_city";
    $fields['company_zip'] = "company_zip";
    $fields['job_title'] = "job_title";
    $fields['job_type'] = "job_type";
    $fields['job_time'] = "job_time";
    $fields['department'] = "department";
    $fields['supervisor'] = "supervisor";
    $fields['vision'] = "vision";
    $fields['height'] = "height";
    $fields['weight'] = "weight";
    $fields['hand_dominance'] = "hand_dominance";
    $fields['areas_of_fatigue'] = "areas_of_fatigue";
    $fields['job_description'] = "job_description";
    $fields['injury_review'] = "injury_review";
    $fields['job_positive'] = "job_positive";
    $fields['risk_factors'] = "risk_factors";
    $fields['job_improvement_short'] = "job_improvement_short";
    $fields['job_improvement_long'] = "job_improvement_long";
    $fields["c_1"] = "Near Lift";
    $fields["c_2"] = "Middle Lift";
    $fields["c_3"] = "Far Lift";
    $this->CI->validation->set_fields($fields);

    // Set Rules

    for($i=1;$i<18;$i++){
      $rules["a_".$i]= 'hour|integer|max_length[2]';
    }
    for($i=1;$i<24;$i++){
      $rules["b_".$i]= 'hour|integer|max_length[2]';
    }
    // Setup form default values
    $this->CI->validation->set_rules($rules);

        if ( $this->CI->validation->run() === FALSE )
        {
            // Output any errors
            $this->CI->validation->output_errors();
        }
        else
        {
            // Submit form
            $this->_submit();
        }
    //Tool for current user
    if ($method == 'update') {
        // Modify form, first load
        $this->CI->db->from('be_user_profiles');
        $this->CI->db->where('user_id' , $id);
        $user = $this->CI->db->get();
        $this->CI->db->from('be_survey');
        $this->CI->db->where('user_id' , $id);
        $survey =   $this->CI->db->get();
        $user = array_merge($user->row_array(),$survey->row_array());
        $this->CI->validation->set_default_value($user);

        // Display page
        $data['user'] = $user;
    }
    $data['header'] = 'Risk Assessment Survey';
    $data['page'] = $this->CI->config->item('backendpro_template_public') . 'form_survey';
    $this->CI->load->view($container,$data);
}

Submit function:

function _submit()
{
    $URI = $this->CI->uri->uri_string();
    $new = "new";
    if(strpos($URI, $new) === FALSE){
        $method = "update";
    }
    elseif(strpos($URI, $new) !== FALSE){
        $method = "create";
    }

    //Submit and Update for current User
    $id = $this->CI->session->userdata('id');
    $this->CI->db->select('users.id, users.username, users.email, profiles.firstname, profiles.manager_id');
    $this->CI->db->from('be_users' . " users");
    $this->CI->db->join('be_user_profiles' . " profiles",'users.id=profiles.user_id');
    $this->CI->db->having('id', $id);
    $email_data['user'] = $this->CI->db->get();
    $email_data['user'] = $email_data['user']->row();
    $manager_id = $email_data['user']->manager_id;
    $this->CI->db->select('firstname','email')->from('be_user_profiles')->where('user_id', $manager_id);

    $email_data['manager'] = $this->CI->db->get();
    $email_data['manager'] = $email_data['manager']->row();


    // Fetch what they entered in the form

    for($i=1;$i<18;$i++){
      $survey["a_".$i]= $this->CI->input->post('a_'.$i);
    }
    for($i=1;$i<24;$i++){
      $survey["b_".$i]= $this->CI->input->post('b_'.$i);
    }
    for($i=1;$i<12;$i++){
      $survey["c_".$i]= $this->CI->input->post('c_'.$i);
    }
    $profile['firstname'] = $this->CI->input->post('firstname');
    $profile['lastname'] = $this->CI->input->post('lastname');
    $profile['test_date'] = date ("Y-m-d H:i:s");
    $profile['company_name'] = $this->CI->input->post('company_name');
    $profile['company_address'] = $this->CI->input->post('company_address');
    $profile['company_city'] = $this->CI->input->post('company_city');
    $profile['company_phone'] = $this->CI->input->post('company_phone');
    $profile['company_state'] = $this->CI->input->post('company_state');
    $profile['company_zip'] = $this->CI->input->post('company_zip');
    $profile['job_title'] = $this->CI->input->post('job_title');
    $profile['job_type'] = $this->CI->input->post('job_type');
    $profile['job_time'] = $this->CI->input->post('job_time');
    $profile['department'] = $this->CI->input->post('department');
    $profile['vision'] = $this->CI->input->post('vision');
    $profile['height'] = $this->CI->input->post('height');
    $profile['weight'] = $this->CI->input->post('weight');
    $profile['hand_dominance'] = $this->CI->input->post('hand_dominance');
    $profile['areas_of_fatigue'] = $this->CI->input->post('areas_of_fatigue');
    $profile['job_description'] = $this->CI->input->post('job_description');
    $profile['injury_review'] = $this->CI->input->post('injury_review');
    $profile['job_positive'] = $this->CI->input->post('job_positive');
    $profile['risk_factors'] = $this->CI->input->post('risk_factors');
    $profile['job_improvement_short'] = $this->CI->input->post('job_improvement_short');
    $profile['job_improvement_long'] = $this->CI->input->post('job_improvement_long');      

    if ($method == "update") {
        //Begin db transmission
        $this->CI->db->trans_begin();

        $this->CI->home_model->update('Survey',$survey, array('user_id' => $id));
        $this->CI->db->update('be_user_profiles',$profile, array('user_id' => $id));        
        if ($this->CI->db->trans_status() === FALSE)
        {
            flashMsg('error','There was a problem entering your test! Please contact an administrator.');
            redirect('survey','location');
        }
        else
        {
            //Get credits of user and subtract 1        
            $this->CI->db->set('credits', 'credits -1', FALSE);
            $this->CI->db->update('be_user_profiles',$profile, array('user_id' => $manager_id));

            //Mark the form completed.
            $this->CI->db->set('test_complete', '1');
            $this->CI->db->where('user_id', $id)->update('be_user_profiles');
            // Stuff worked...
            $this->CI->db->trans_commit();



            //Get Manager Information
            $this->CI->db->select('users.id, users.username, users.email, profiles.firstname');
            $this->CI->db->from('be_users' . " users");
            $this->CI->db->join('be_user_profiles' . " profiles",'users.id=profiles.user_id');
            $this->CI->db->having('id', $email_data['user']->manager_id);
            $email_data['manager'] = $this->CI->db->get();
            $email_data['manager'] = $email_data['manager']->row();

            //Email User
            $this->CI->load->library('User_email');
            $data_user = array(
                    'firstname'=>$email_data['user']->firstname,
                    'email'=> $email_data['user']->email,
                    'user_completed'=>$email_data['user']->firstname,
                    'site_name'=>$this->CI->preference->item('site_name'),
                    'site_url'=>base_url()
            );

            //Email Manager     
            $data_manager = array(
                    'firstname'=>$email_data['manager']->firstname,
                    'email'=> $email_data['manager']->email,
                    'user_completed'=>$email_data['user']->firstname,
                    'site_name'=>$this->CI->preference->item('site_name'),
                    'site_url'=>base_url()
            );
            $this->CI->user_email->send($email_data['manager']->email,'Completed the Assessment Tool','public/email_manager_complete',$data_manager);
            $this->CI->user_email->send($email_data['user']->email,'Completed the Assessment Tool','public/email_user_complete',$data_user);

            flashMsg('success','You finished the assessment successfully!');
            redirect('home','location');
        }
    }
    //Create New User
    elseif ($method == "create") {
            // Build
            $profile['user_id'] = $id;
            $profile['manager_id'] = $manager_id;
            $profile['test_complete'] = '1';
            $survey['user_id'] = $id;
            $this->CI->db->trans_begin();

            // Add user_profile details to DB
            $this->CI->db->insert('be_user_profiles',$profile);
            $this->CI->db->insert('be_survey',$survey);

            if ($this->CI->db->trans_status() === FALSE)
            {
                // Registration failed
                $this->CI->db->trans_rollback();

                flashMsg('error',$this->CI->lang->line('userlib_registration_failed'));
                redirect('auth/register','location');
            }
            else
            {
                // User registered
                $this->CI->db->trans_commit();

                flashMsg('success',$this->CI->lang->line('userlib_registration_success'));
                redirect($this->CI->config->item('userlib_action_register'),'location');
            }

    }
}

Controller function:

function survey()
{
    $id = $this->session->userdata('id');
    $data['member'] = $this->home_model->getUsers(array('user_id'=>$id));

    //Convert the db Object to a row array
    $data['manager'] = $data['member']->row();
    $manager_id = $data['manager']->manager_id;
    $data['manager'] = $this->home_model->getUsers(array('manager_id'=>$id));
    $data['manager'] = $data['manager']->row();
    if ($data['manager']->credits == '0')   {
        flashMsg('warning',"You can't complete the assessment until your manager has purchased credit.");
        redirect('home','location');
    }
    elseif ($data['manager']->test_complete == '3'){
        flashMsg('warning',"You already completed the Assessment.");
        redirect('home','location');                        
    }
    else{
        $data['header'] = "Home";
        $this->survey_form_processing->survey_form($this->_container,$data);
    }
}

The submit function is similar, updating the db if $method == "update", and inserting if the method == "create".

The problem is, when the form is submitted, it doesn't take into account the url b/c the form submits to the function "survey", which passes data to the lib function, so things are always updated, never created.

*How can I pass $method to the _submit() function correctly?!*

+2  A: 

Hi Kevin,

I have a better understanding of your problem now - thanks for posting the updates to your code. I'm updating and elaborating on my answer to explain your problem and offer some solutions.

I'm sure you know, but it won't hurt to preface this with a basic review of the general MVC pattern as it relates to URI structure. That is, in the example of site.com/home/survey/new, the first segment home is the controller class name, the second segment survey is the controller function name, and the third segment new (and any segments after this) is an ID or variable passed to survey(). More here.

Your code isn't working because you never pass a variable to survey() via the URI when you submit the form, so "new" never exists in the URL, and therefore $method is always set to "update". So,

"How can I pass $method to the _submit() function correctly?"

There are a couple of options for doing this. Each one simply requires that you determine whether a user->survey relationship exists in order to set $method. You can then pass $method on to the appropriate functions. For my example below, I'm going to assume that a user can only have one survey. If that's not the case you'll just have to account for a unique survey ID associated with a unique user ID.

One possible scenario goes like this (again, this assumes that a user can be associated with only one survey):

  1. User submits survey
  2. Upon form submission, check to see if a survey already exists for that user
  3. If so, set $method="update" otherwise set $method="create"
  4. Proceed to pass $method to the other necessary functions

An alternative solution might look like this:

  1. In your controller function that calls the view file of your survey, determine if a record already exists for the user.
  2. Pass that data to your survey view
  3. In the view, modify the form action so that it passes that data (either "create" or "update") to the survey() function when the form is submitted.
  4. In survey(), set $method based on the data supplied
  5. Proceed to pass $method to the other necessary functions

I'll use the first option as an example and outline the logic you would need (forgive the somewhat pseudo-code, but you'll get the idea):

survey() function:

function survey() {

    // instead of determining whether "new" is part of the URI (which it never is),
    // check for an existing survey associated with the logged in user's ID
    $id = $this->session->userdata('id');
    $query = $this->db->get_where('Survey', array('user_id' => $id));

    // if the above query returns a result, set $method="update"
    // otherwise set $method="create"
    if ($query->num_rows() > 0) {
        $method="update";
    } else {
        $method="create";
    }

    // whatever other logic you need here

    // pass $method to survey_form()
    $this->survey_form_processing->survey_form($this->_container, $data, $method);
}

survey_form() function:

function survey_form($container, $data, $method) {

    // your other code here

    if ( $this->CI->validation->run() === FALSE ) {
        // Output any errors
        $this->CI->validation->output_errors();
    } else {
        // Submit form (w/ $method parameter - this comes from survey())
        $this->_submit($method);
    }

}

_submit() function:

function _submit($method) {

    // your other code here

    if ($method == "update") {
        // do something
    } elseif ($method == "create") {
        // do something else
    }

}

As a side note, there are probably better ways to structure what you're doing. For example, in my pseudo-code above, the database interactions should probably be happening in a model. For clarity, though, they are included in the controller. I hope that helps!

Colin
That's not working... I also added $method as a parameter in the lib: survey_form. It's not getting that data.
Kevin Brown
I need to pass these parameters to the _submit function...
Kevin Brown
@Kevin: Where are you loading the library that calls _submit()?
Colin
If you'll look at my code above: First chunk = first_part_of_the_library, Second Chunk = second part of the library, Third Chunk = submit function, and Last chunk is the controller.
Kevin Brown
@Kevin: Would it be possible to post your survey_form() function? It would be helpful to see the entire path the data will take from the controller to, ultimately, the _submit() function. Can you also confirm that $method is getting assigned a value in your controller before being passed on to survey_form()?
Colin
I've updated all my code to match exactly what I have right now. It's SUBMITTING correctly, but the form loads correctly when "new" is in (or not in) the url...
Kevin Brown
Warmer. Things are working like they should in the survey_form function, but it will only do ONE, not both, of create/update. (it will only create, or only update, depending on the order that I put the if statement). This means that $method isn't being called in the _submit function...I think.
Kevin Brown
@Kevin: What is the full URL that is calling your submit() controller? Also, what happens when you var_dump($method) in survey(), survey_form(), and _submit()? Can you track its value that way and report back?
Colin
@Colin: site.com/home/survey/$method, or site.com/survey/$method. $method is either nothing (thus updating), or /new (thus creating). How would I track this value? It works all the way up to the submit function...I could create two separate submit functions...
Kevin Brown
@Kevin: I'm confused why $method wouldn't be available in your _submit() function. Can you add var_dump($method); at the beginning of your _submit() function? It will display information about the $method variable. Are you still doing your URI check in your submit() function? Is the code you posted still in line with what you have locally?
Colin
I'll try var_dump. The URI check is still in my submit function.
Kevin Brown
var_dump says, "Cannot modify header information. Headers already sent..."
Kevin Brown
@Kevin: Try rearranging your code like in my examples (I outlined the 3 steps above). IMO, this is a little more straight-forward way to do it and will make troubleshooting easier. Once you're setting $method in your survey() function, you can use var_dump($method) to ensure its value from there, then simply pass it to surver_form(), which in turn passes it to _submit(). Give that a shot and let me know the results. Don't worry, we'll figure it out :)
Colin
@Colin! I figured out that the URI isn't getting passed properly. I think the problem lies in the uri_string...maybe?
Kevin Brown
@Kevin: Can you elaborate a bit? How is it not being passed properly? Did you make any changes to your code that aren't reflected above?
Colin
When the form submits, it submits to the function "survey", right? This means, that the URI passed is simply "survey", not "survey/new" or anything else, so the method is ALWAYS "update". That is what I think I am experiencing.
Kevin Brown
@Kevin: If you never include "new" in the URL then yes, your code will always set $method to "update". Are you never including "new" in any of your URLs?
Colin
Yeah, yeah. I'm setting new, but when it submits, (since my form view file submits to "survey"), doesn't it change the uri when submit is clicked?
Kevin Brown
@Kevin: If you submit the form to your survey() controller, any URI segment is available to that function. So, you can pass your $method to survey() by submitting the form to "site.com/home/survey/new" for new records, or submitting the form to "site.com/home/survey" for record updates. How and where are you adding (or not adding) "new" to the URL? Can you post your form view file?
Colin
@Colin: Doing exactly what you say. See my edit.
Kevin Brown
@Kevin: Thanks. This makes more sense now. What/where is the logic for determining if a survey is "new" or not? If you can let me know and post it, I think I can update my answer to solve your problem.
Colin
@Colin: The logic determining if it's "new" is in your function "survey", and is utilized further in my submit function (see above). If we can get this to work, awesome, but if not I need to use hidden forms and just do it that way.
Kevin Brown
@Kevin: I updated my answer to try to explain your problem and offer a solution.
Colin
@Colin: Thanks for the assistance!
Kevin Brown