/**
  * @throws \Exception
  */
 private function defaultOrderSettings()
 {
     $orderSettings = new Market_OrderSettingsModel();
     $orderSettings->name = 'Order';
     $orderSettings->handle = 'order';
     // Set the field layout
     $fieldLayout = \Craft\craft()->fields->assembleLayout([], []);
     $fieldLayout->type = 'Market_Order';
     $orderSettings->setFieldLayout($fieldLayout);
     $data = ['name' => 'New', 'handle' => 'new', 'color' => 'green', 'default' => true];
     $state = Market_OrderStatusModel::populateModel($data);
     \Craft\craft()->market_orderSettings->save($orderSettings);
     \Craft\craft()->market_orderStatus->save($state, []);
 }
 public function save(Market_OrderSettingsModel $orderSettings)
 {
     if ($orderSettings->id) {
         $orderSettingsRecord = Market_OrderSettingsRecord::model()->findById($orderSettings->id);
         if (!$orderSettingsRecord) {
             throw new Exception(Craft::t('No order settings exists with the ID “{id}”', ['id' => $orderSettings->id]));
         }
         $oldOrderSettings = Market_OrderSettingsModel::populateModel($orderSettingsRecord);
         $isNewOrderSettings = false;
     } else {
         $orderSettingsRecord = new Market_OrderSettingsRecord();
         $isNewOrderSettings = true;
     }
     $orderSettingsRecord->name = $orderSettings->name;
     $orderSettingsRecord->handle = $orderSettings->handle;
     $orderSettingsRecord->validate();
     $orderSettings->addErrors($orderSettingsRecord->getErrors());
     if (!$orderSettings->hasErrors()) {
         MarketDbHelper::beginStackedTransaction();
         try {
             if (!$isNewOrderSettings && $oldOrderSettings->fieldLayoutId) {
                 // Drop the old field layout
                 craft()->fields->deleteLayoutById($oldOrderSettings->fieldLayoutId);
             }
             // Save the new one
             $fieldLayout = $orderSettings->getFieldLayout();
             craft()->fields->saveLayout($fieldLayout);
             // Update the calendar record/model with the new layout ID
             $orderSettings->fieldLayoutId = $fieldLayout->id;
             $orderSettingsRecord->fieldLayoutId = $fieldLayout->id;
             // Save it!
             $orderSettingsRecord->save(false);
             // Now that we have a calendar ID, save it on the model
             if (!$orderSettings->id) {
                 $orderSettings->id = $orderSettingsRecord->id;
             }
             MarketDbHelper::commitStackedTransaction();
         } catch (\Exception $e) {
             MarketDbHelper::rollbackStackedTransaction();
             throw $e;
         }
         return true;
     } else {
         return false;
     }
 }