Jump to content


waqar

Member Since 08 Sep 2012
Offline Last Active Sep 12 2012 09:58 AM
-----

#3354 How to add custom field in edit/add view that doesn't exist in database?

Posted waqar on 11 September 2012 - 12:01 PM

SOLVED :)

I added a field of amount with $crud->fields, I hid the fields of deposit and withdraw on add/edit form, displayed an input field for amount manually through a callback function, and then through another callback before insert I set the field values for deposit/withdraw and unset the amount field so it didn't cause issues with CRUD. Here's the updated code snippet, hope this helps someone :)

// Fields for add/edit form
   $crud->fields('date','title','deposit','withdraw','amount','category_id');
   // Hide some fields from add/edit form from user
   $crud->change_field_type('deposit','invisible');
   $crud->change_field_type('withdraw','invisible');
  
   // Required fields
   $crud->required_fields('date','title','category_id','amount');
  
   // Callbacks
   $crud->callback_add_field('amount',array($this,'amount_field_add_callback'));
   $crud->callback_before_insert(array($this,'amount_callback'));
   // Render Crud
   $output = $crud->render();

And the callback functions are as follows:
function amount_field_add_callback()
{
  return '<input type="text" maxlength="50" value="" name="amount">';
}

function amount_callback($post_array) {
  // category id
  $category_id = $post_array['category_id'];
  // get category type whether income or expense
  $category_type = $this->Transactions_model->get_category_type($category_id);
  // if type "income"
  if ($category_type->title == 'income') {
   // set deposit field
   $post_array['deposit'] = $post_array['amount'];
  } else { // else if type "expense"
   // set withdraw field
   $post_array['withdraw'] = $post_array['amount'];
  }
  // Unset field of amount as that does not exist in database.
  unset($post_array['amount']);
  //array_splice(1, count($post_array), $post_array['amount']);
  // return field variables with updated information for insertion
  return $post_array;
}


Thanks
Waqar

We build great Web and Software Applications and Software Products for you @ 4 Ace Technologies