How to add custom filed to customers table in OpenCart?
OpenCart has many flaws, at least in version <2. Unlike WordPress for example there is no easy way to change core functionality with custom plugin without changing the source code. There is no pub/sub architecture for interrupting system events…
But if you need to add custom fields to custumer, here is code simple example for that in five simple steps.
Step 1
Add form html in admin panel :
// admin/view/template/sale/customer_form.tpl
// find <input name="firstname" type="text" value="<?php echo $firstname; ?>" />
// and add before :
<input name="#field_name#" type="text" value="<?php echo #field_name#; ?>" />
Step 2
Add translation for field :
// admin/language/english/sale/customer.php
// find 'Entry' part
// Add
$_['entry_#field_name#'] = 'Some text :';
Step 3
Pull language translation :
// admin/controller/sale/customer.php
// find : $this->data['entry_firstname'] = $this->language->get('entry_firstname');
// add before
$this->data['entry_#field_name#'] = $this->language->get('entry_#field_name#');
Step 4
Retrive custom field from POST
// admin/controller/sale/customer.php
// find : if (isset($this->request->post['firstname'])) {
// add before
if (isset($this->request->post['#field_name#'])) {
$this->data['#field_name#'] = $this->request->post['#field_name#'];
} elseif (isset($customer_info)) {
$this->data['#field_name#'] = $customer_info['#field_name#'];
} else {
$this->data['#field_name#'] = '';
}
Step 5
Insert and update database custom field
// admin/model/sale/customer.php
// Find insert query in addCustomer function
// add at the end of query
', #field_name# = '" . $this->db->escape($data['#field_name#']) . "'");
// find update function and add custom field :
', #field_name# = '" . $this->db->escape($data['#field_name#']) . "' WHERE customer_id = '" . (int)$customer_id . "'");
Step 6
Alter customer table with SQL
ALTER TABLE `table_prefix_customer` ADD `#field_name#` VARCHAR (250) NOT NULL
Replace #field_name# with real name.
Note: this modification will be overridden when you upgrade your OpenCart version. To add automated process of upgrade use vQmod. Here is exmaple of that : http://itechtuts.com/custom-fields-opencart-administration-panel-using-vqmod/