Answers.Body: <p>Go with #1.  It looks like you've already got a <code>Portal_CodeModel</code> created, you just need to populate them from the controller, perform validation (if any), then pass the array of <code>Portal_CodeModel</code> objects to your service.</p>
  
  <p>You'll want to remove the <code>Portal_CodeModel</code> type hint from your service's <code>addCodes</code> signature (or change it to <code>array</code>) since you're passing in an array of objects, instead of a single one.</p>
  
  <p>Here's an example in your controller with any code validation:</p>
  
  <pre><code>$codeModels = array();
  $codes = explode("\r\n", craft()-&gt;request-&gt;getPost('codes'));
  
  $success = craft()-&gt;portal_code-&gt;addCodes($codes);
  </code></pre>
  
  <p>And in your service:</p>
  
  <pre><code>public function addCodes($codes)
  {
  
      foreach($codes as $code)
      {
          $existingCode = Portal_CodeRecord::model()-&gt;findByAttributes(array(
              'code' =&gt; $code,
          ));
  
          if ($existingCode)
          {
              $existingCode-&gt;code_used = 1;
              $existingCode-&gt;save();
  
              {# or whatever else you want to do when the code already exists in the database #}
          }
          else
          {
              $codeRecord = new Portal_CodeRecord();
              $codeRecord-&gt;code = $code;
              $codeRecord-&gt;code_used = 0;
              $codeRecord-&gt;save();
          }
      }
  </code></pre>
  
  <p>}</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-03-10T03:54:22.827Z
Answers.Text: I get the following error with this setup:  `The active record cannot be inserted to database because it is not new.`
Answers.UserDisplayName: Brett DeWoody
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-03-10T03:56:49.530Z
Answers.Text: You'll have to share the actual PHP service code you're using when you get that error, but most likely you're calling `insert` on a code that already exists in the database when you should be calling `update`.
Answers.UserDisplayName: Brad Bell
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-03-10T04:16:26.660Z
Answers.Text: I updated the question based on comments.
Answers.UserDisplayName: Brett DeWoody
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-03-10T16:30:11.187Z
Answers.Text: From all the examples I've seen it shows the instance being created in the service, and then using `instanceName->save();`
Answers.UserDisplayName: Brett DeWoody
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-03-10T16:45:21.167Z
Answers.Text: Updated answer.
Answers.UserDisplayName: Brad Bell
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-03-10T16:50:58.290Z
Answers.Text: My db table is empty so there's no chance of the record already existing. Running just the `insert()` portion of your above code should work. The error I still get is `The active record cannot be inserted to database because it is not new.`
Answers.UserDisplayName: Brett DeWoody
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-03-10T16:53:06.680Z
Answers.Text: Updated again...
Answers.UserDisplayName: Brad Bell
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-03-10T17:03:08.007Z
Answers.Text: Close. We were passing in an array of models. I updated the answer to make it correct.
Answers.UserDisplayName: Brett DeWoody
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2015-03-10T03:08:51.533Z
Answers.LastActivityDate: 2015-03-10T17:04:25.047Z
Answers.LastEditDate: 2015-03-10T17:04:25.047Z
Answers.UserDisplayName: Brad Bell
Body: <p>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 <code>textarea</code> where each line is a separate access code. </p>
  
  <p>I'm wondering what the best practice is in terms of inserting these records into the database?</p>
  
  <p><strong>Controller:</strong></p>
  
  <pre><code>// This returns an array of codes to be inserted
  $codes = explode("\r\n", craft()-&gt;request-&gt;getPost('codes'));
  
  foreach($codes as $code) {
      $codeModel = new Portal_CodeModel();
      $codeModel-&gt;code = $code;
      $codeModels[] = $codeModel;
  }
  
  $success = craft()-&gt;portal_code-&gt;addCodes($codeModels);
  </code></pre>
  
  <p><strong>Service:</strong></p>
  
  <pre><code>public function addCodes($codes) {
  
      foreach($codes as $code) {
  
        Portal_CodeRecord::model()-&gt;insert(array(
            'code'        =&gt; $code,
            'code_used'   =&gt; 0
        ));
  
      }
  
  }
  </code></pre>
  
  <p><strong>Record:</strong></p>
  
  <pre><code>class Portal_CodeRecord extends BaseRecord {
  
      public function getTableName() {
          return 'portal_codes';
      }
  
      protected function defineAttributes() {
          return array(
              'code'          =&gt; AttributeType::String,
              'code_used'     =&gt; AttributeType::Bool
          );
      }
  }
  </code></pre>
  
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2015-03-09T22:12:34.123Z
Comments.Text: I know there are probably several issues with the above code. If there are any good examples on how to insert multiple records that'd be a huge help.
Comments.UserDisplayName: Brett DeWoody
Tags: <plugin-development><database><services>
Title: Inserting multiple records in a plugin
ThreadText: # Inserting multiple records in a plugin
  
  (Asked by: username_0 on 2015-03-09)
  
  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
          );
      }
  }
  
  ```
  
  **Tags:** plugin-development, database, services
  
  > **Comments:**
  > **username_0**: I know there are probably several issues with the above code. If there are any good examples on how to insert multiple records that'd be a huge help.  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_1 on 2015-03-10. Score: 1 | Accepted answer
  
  Go with #1. It looks like you've already got a `Portal_CodeModel` created, you just need to populate them from the controller, perform validation (if any), then pass the array of `Portal_CodeModel` objects to your service.
  
  You'll want to remove the `Portal_CodeModel` type hint from your service's `addCodes` signature (or change it to `array`) since you're passing in an array of objects, instead of a single one.
  
  Here's an example in your controller with any code validation:
  
  ```
  $codeModels = array();
  $codes = explode("\r\n", craft()->request->getPost('codes'));
  
  $success = craft()->portal_code->addCodes($codes);
  
  ```
  
  And in your service:
  
  ```
  public function addCodes($codes)
  {
  
      foreach($codes as $code)
      {
          $existingCode = Portal_CodeRecord::model()->findByAttributes(array(
              'code' => $code,
          ));
  
          if ($existingCode)
          {
              $existingCode->code_used = 1;
              $existingCode->save();
  
              {# or whatever else you want to do when the code already exists in the database #}
          }
          else
          {
              $codeRecord = new Portal_CodeRecord();
              $codeRecord->code = $code;
              $codeRecord->code_used = 0;
              $codeRecord->save();
          }
      }
  
  ```
  
  }
  
  > **Comments:**
  > **username_0**: I get the following error with this setup:  `The active record cannot be inserted to database because it is not new.`  
  > **username_1**: You'll have to share the actual PHP service code you're using when you get that error, but most likely you're calling `insert` on a code that already exists in the database when you should be calling `update`.  
  > **username_0**: I updated the question based on comments.  
  > **username_0**: From all the examples I've seen it shows the instance being created in the service, and then using `instanceName->save();`  
  > **username_1**: Updated answer.  
  > **username_0**: My db table is empty so there's no chance of the record already existing. Running just the `insert()` portion of your above code should work. The error I still get is `The active record cannot be inserted to database because it is not new.`  
  > **username_1**: Updated again...  
  > **username_0**: Close. We were passing in an array of models. I updated the answer to make it correct.  
  
  ---
  
  