0
public function saveGoal(Logic_GoalModel &$model)
{
    // New goal
    $isNewGoal = !$model->id;

    // Populate record
    $record = $this->getGoalRecordById($model->id);
    $record->userId = $model->userId;
    $record->goal = $model->goal;
    $record->complete = $model->complete;           

    // Save record
    if($record->save(false))
    {
        // Populate id
        if($isNewGoal)
        {
            $model->id = $record->id;
        }

        return true;
    }
    else
    {
        return false;
    }
}

private function getGoalRecordById($id = null)
{
    if($id)
    {
        $record = Logic_GoalRecord::model()->findById($id);

        if (!$record)
        {
            throw new Exception(Craft::t('No record exists with the ID “{id}”', array('id' => $id)));
        }
    }
    else
    {
        $record = new Logic_GoalRecord();
    }

    return $record;
}
1

It is definitely a way to save record. :)

You might want to be more explicit with validation, though. i.e.

if ($record->validate())
{
    // Save record
    if ($record->save(false))
    {
        // Populate id
        if($isNewGoal)
        {
            $model->id = $record->id;
        }

        return true;
    }
    else
    {
        return false;
    }
}
else
{
    $model->addErrors($record->getErrors());
}
4
  • Makes sense, I'm validating the model before calling saveGoal. Need to validate both? Apr 7 '15 at 16:52
  • If the attributes for each are identical, then probably not.
    – Brad Bell
    Apr 7 '15 at 16:53
  • They are. Still trying to get my head around models and records and all the different ways of working with them. So the model passed from the controller is available in both controller and services? Apr 7 '15 at 16:57
  • Right - think of a model as a the thing that you can freely pass between the different layers of your application (controllers, services, etc.).
    – Brad Bell
    Apr 7 '15 at 18:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.