+ /**
+ * When creating a record without a supplied name,
+ * create a unique, clean name derived from the label.
+ *
+ * Note: this function does nothing unless a unique index exists for "name" column.
+ */
+ private function makeNameFromLabel() {
+ $indexNameWith = NULL;
+ // Look for a unique index which includes the "name" field
+ if (method_exists($this, 'indices')) {
+ foreach ($this->indices(FALSE) as $index) {
+ if (!empty($index['unique']) && in_array('name', $index['field'], TRUE)) {
+ $indexNameWith = $index['field'];
+ }
+ }
+ }
+ if (!$indexNameWith) {
+ // No unique index on "name", do nothing
+ return;
+ }
+ $name = CRM_Utils_String::munge($this->label, '_', 252);
+
+ // Find existing records with the same name
+ $sql = new CRM_Utils_SQL_Select($this::getTableName());
+ $sql->select(['id', 'name']);
+ $sql->where('name LIKE @name', ['@name' => $name . '%']);
+ // Include all fields that are part of the index
+ foreach (array_diff($indexNameWith, ['name']) as $field) {
+ $sql->where("`$field` = @val", ['@val' => $this->$field]);
+ }
+ $query = $sql->toSQL();
+ $existing = self::executeQuery($query)->fetchMap('id', 'name');
+ $dupes = 0;
+ $suffix = '';
+ while (in_array($name . $suffix, $existing)) {
+ $suffix = '_' . (++$dupes);
+ }
+ $this->name = $name . $suffix;
+ }
+