'How to use grocery set_relation function to display content from two different tables in different columns
I have to tables with these schema:
users(id, name, email)
user_details (id, user_id, physical_address, otherinfo)
I would like to display all contents of both tables in one grid using grocery crud when i try to use set relation on the first table as shown: Note: I have reducted the part that does the rendering of the view;
$crud = new grocery_CRUD();
$crud->set_table('users');
$crud->set_relation('id', 'user_details', '{physical_address} + {otherinfo}');
the values of the id field as well as the referenced table don't appear in the grid, so it does not seem to work when using primary keys.
So I decided to start with the contents of the second table like so:
$crud = new grocery_CRUD();
$crud->set_table('user_details');
$crud->set_relation('user_id', 'users', '{name} + {email}');
This works, but the problem is that the values appear in one column in the grid. I would like to know how i can separate them to different columns and make them editable in separate input fields.
Solution 1:[1]
my way kinda ridiculous,
if i were really need the field to be separated, i might use callback_column then use active records to return the value using $row->user_id, and callback each record
just like:return $this->some_model->get_name($row->user_id); for name field
andreturn $this->some_model->get_name($row->user_id); for email field
but, as i tested with some dummy records, it can't be sorted, (i dont know if anyone could)
Solution 2:[2]
There is no direct way to show multiple columns but i found an work around for this problem. here is how set name column as follows.
$crud->columns('name','email'); // define all required columns
$crud->callback_column(unique_field_name('user_id'),array($this,'callback_set_user_name'));
function unique_field_name($field_name)
{
return 's'.substr(md5($field_name),0,8);
}
public function callback_set_user_name($value, $row)
{
$row->full_name = $row->s447d3092; // before getting to know s447d3092 key return json_encode($row); you will key pair with {name} + {email} ex: {"s447d3092":"shiva + [email protected]"}
return explode("+",$value)[0]; // here you will have only name
}
$crud->callback_column('email',array($this,'callback_set_email'));
public function callback_set_email($value, $row)
{
return explode("+",$row->full_name)[1];
}
I am 100% sure this will help you
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Henry J |
| Solution 2 | SHIVAPUTRA UDAGATTI |
