Skip to content

Commit

Permalink
Create unique slug for new fields in schemawidget.
Browse files Browse the repository at this point in the history
  • Loading branch information
robgietema committed Nov 25, 2024
1 parent e708225 commit 57d3017
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -949,7 +949,7 @@ class SchemaWidget extends Component {
* @returns {undefined}
*/
onAddField(values) {
const fieldId = slugify(values.title);
const fieldId = slugify(values.title, keys(this.props.value.properties));
const currentFieldsetFields =
this.props.value.fieldsets[this.state.currentFieldset].fields;
const hasChangeNote = currentFieldsetFields.indexOf('changeNote') > -1;
Expand Down
25 changes: 22 additions & 3 deletions packages/volto/src/helpers/Utils/Utils.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { cloneDeepWith, flatten, isEqual, isObject, transform } from 'lodash';
import {
cloneDeepWith,
flatten,
includes,
isEqual,
isObject,
transform,
} from 'lodash';
import React from 'react';
import { matchPath } from 'react-router';
import config from '@plone/volto/registry';
Expand Down Expand Up @@ -297,13 +304,25 @@ export function normalizeString(str) {
/**
* Slugify a string: remove whitespaces, special chars and replace with _
* @param {string} string String to be slugified
* @param {Array} slugs Array with slugs already taken
* @returns {string} Slugified string
*/
export const slugify = (string) => {
return string
export const slugify = (string, slugs = []) => {
let slug = string
.toLowerCase()
.replace(/[\s-]+/g, '_')
.replace(/[^\w]+/g, '');
let i = 1;

if (includes(slugs, slug)) {
while (includes(slugs, `${slug}_${i}`)) {
i++;
}

slug = `${slug}_${i}`;
}

return slug;
};

/**
Expand Down

0 comments on commit 57d3017

Please sign in to comment.