Welcome Guest, Not a member yet? Register   Sign In
Datamapper new records and updated records
#1

[eluser]Iverson[/eluser]
Does anyone see a problem with this? I think this will be a great way for me to register a customer and update their data without making separate functions. I also only have to specify the fields once and let the function handle the rest.

Code:
function manage($data, $action='register')
    {
        $this->load->helper('array');
        $c = new Customer();
        
        $fields[] = 'username';
        $fields[] = 'email';
        $fields[] = 'city';
        $fields[] = 'state';
        $fields[] = 'zip';
        $fields[] = 'phone';

        if($action == 'update')
        {
            if(element('id', $data))
            {
                $c->where('id', element('id', $data))->get();
            }
        }

        foreach($fields as $field)
        {
            if(element($field, $data))
            {
                $c->$field = addslashes(element($field, $data));
            }
        }

        if($action == 'register')
        {
            $c->registered_timestamp = mktime();
        }
        
        if($c->save())
        {
            return TRUE;
        }
        return FALSE;
    }
#2

[eluser]stensi[/eluser]
I'd remove the addslashes() as it's not needed. DataMapper uses CodeIgniter's Active Record class for database interaction and the data is automatically escaped by it.

Instead of setting "registered_timestamp", you could use DataMapper's automatic timestamp handling. If you're using a UNIX timestamp and you want to store it in a field named "registered_timestamp", you modify the datamapper config file like so:

Code:
$config['created_field'] = 'registered_timestamp';
$config['unix_timestamp'] = TRUE;

Alternatively, you can set those directly in your Customer model so it only applies to it. That way, you can get rid of this block of code:

Code:
if($action == 'register')
{
    $c->registered_timestamp = mktime();
}

Another thing you could do, instead of having to specify the fields the way you are, is use the fields stored in the customer object (for DataMapper 1.5.3):

Code:
foreach ($c->fields as $field)
{
    // ...
}




Theme © iAndrew 2016 - Forum software by © MyBB