SCENARIO
Grocerycrud by default dose not provide a solution for adding default values that can be utilized at the time of add form. But there are many a times a developer likes to have a default value set to the form.
SOLUTION
To achieve the same, one needs to either alter the base library to add the function or create one’s own extension. We at this solution will work on altering the base library to provide the same solution.
Open the GroceryCrud library file, find the following in the code ..
protected $callback_after_upload = null;
……there below the codes — add the following
protected $field_default_values = array();
Then u can find in for the following function ..
public function display_as($field_name,$display_as= null)
just before that or after – wherever you feel comfirtable, add the following
/**
*
* Function allows the user to set a default value to the the field set
* @param string $field
* @param string $value
*/
public function field_set_defaults($field,$value){
$this->field_default_values[$field]=$value;
}
There you are now set to go with adding the mask to the fields you want.
Now post this…
Find the following….
protected function showAddForm()
……in here – add the following line
$data->field_values = $this->get_add_values(null);
$data->input_fields = $this->get_add_input_fields($data->field_values);
Now you need to replace the existing get_add_input_fields function with the code below.
protected function get_add_input_fields($field_values = null)
{
$fields = $this->get_add_fields();
$types = $this->get_field_types();
$input_fields = array();
foreach($fields as $field_num => $field)
{
$field_info = $types[$field->field_name];
$field_value = !empty($field_values) && isset($field_values->{$field->field_name}) ? $field_values->{$field->field_name} : null;
if(!isset($this->callback_add_field[$field->field_name]))
{
$field_input = $this->get_field_input($field_info, $field_value);
}
else
{
$field_input = $field_info;
$field_input->input = call_user_func($this->callback_add_field[$field->field_name], $field_value, null, $field_info);
//make our little change
//allow default field rendering behaviour if user returns false
//in the callback
if ($field_input->input === False) {
$field_input = $this->get_field_input($field_info, $field_value);
}
}
switch ($field_info->crud_type) {
case 'invisible':
unset($this->add_fields[$field_num]);
unset($fields[$field_num]);
continue;
break;
case 'hidden':
$this->add_hidden_fields[] = $field_input;
unset($this->add_fields[$field_num]);
unset($fields[$field_num]);
continue;
break;
}
$input_fields[$field->field_name] = $field_input;
}
return $input_fields;
}
Now, how do we use it? Simple..
$crud->field_set_defaults('favorite_forum', "GroceryCrud");
Happy GCing:)