Create.php 2.11 KB
Newer Older
colemanw's avatar
colemanw committed
1
2
3
4
5
6
7
8
9
10
<?php

namespace Civi\Api4\Action\Example;

/**
 * Example Create action.
 *
 * We could have simply implemented this by returning a BasicCreateAction from our Example entity, passing in 'writeApi4exampleRecord',
 * just like we did with Update, Save, etc. But for demonstration purposes, this is the other way to do it.
 *
11
12
 * Here we override the `writeRecord` method. By default that function simply invokes `$this->setter`,
 * but by overriding this class we don't need to pass in a setter and can do the work directly in `writeRecord`.
colemanw's avatar
colemanw committed
13
14
 *
 * Our writeRecord/setter function takes an array of the record to create. It is responsible for storing the record and,
15
16
 * since we did not mark the `id` field "required" in getFields, it must generate a new `id` if not supplied.
 * It should return the created record as an array, including the `id`.
colemanw's avatar
colemanw committed
17
 *
18
19
 * Note: One reason to use a callback function rather than putting the save logic directly in `$this->writeRecord`
 * is because the callback can be reused between Create/Update/Save actions, which all use the exact same `writeRecord` function.
colemanw's avatar
colemanw committed
20
 *
21
 * Read more about how to implement your own `Create` action:
colemanw's avatar
colemanw committed
22
23
24
25
26
27
28
 * @see \Civi\Api4\Generic\BasicCreateAction
 *
 * @package Civi\Api4\Action\Example
 */
class Create extends \Civi\Api4\Generic\BasicCreateAction {

  /**
colemanw's avatar
colemanw committed
29
30
   * We can override the default value of params, or add docblocks to them,
   * by redeclaring them in our action override.
colemanw's avatar
colemanw committed
31
   *
colemanw's avatar
colemanw committed
32
33
   * For the parent's docblock contents to appear in the _API Explorer_ as well,
   * we add the `@inheritDoc` annotation and get this:
colemanw's avatar
colemanw committed
34
35
36
37
38
39
40
41
   * @inheritDoc
   */
  protected $debug = TRUE;

  /**
   * Override writeRecord.
   *
   * This example is a little silly because the parent function would have done exactly the same thing had we passed
42
   * `'writeApi4exampleRecord'` into this action's constructor. But if you do need to override that method
colemanw's avatar
colemanw committed
43
44
45
46
47
48
49
50
51
52
53
54
   * instead of just invoking a callback, this is how to do it.
   *
   * @see BasicCreateAction::writeRecord
   *
   * @param array $item
   * @return array
   */
  protected function writeRecord($item) {
    return writeApi4exampleRecord($item, $this);
  }

}