I'm building a plugin and have a form in the plugin's CP page that allows admins to save access codes. The form is a simple textarea
where each line is a separate access code.
I'm wondering what the best practice is in terms of inserting these records into the database?
Controller:
// This returns an array of codes to be inserted
$codes = explode("\r\n", craft()->request->getPost('codes'));
foreach($codes as $code) {
$codeModel = new Portal_CodeModel();
$codeModel->code = $code;
$codeModels[] = $codeModel;
}
$success = craft()->portal_code->addCodes($codeModels);
Service:
public function addCodes($codes) {
foreach($codes as $code) {
Portal_CodeRecord::model()->insert(array(
'code' => $code,
'code_used' => 0
));
}
}
Record:
class Portal_CodeRecord extends BaseRecord {
public function getTableName() {
return 'portal_codes';
}
protected function defineAttributes() {
return array(
'code' => AttributeType::String,
'code_used' => AttributeType::Bool
);
}
}