Is there a way to prevent deleting the last remaining rule (e.g. disable remove button) #675
-
I can't find any documentation about this so I figured maybe this is the best place to ask this question. The requirement is to have at least ONE rule. It seems that you can delete all rules and group until there's none left. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
There are a few ways you could go with this. The code below demonstrates a "remove rule" button that won't render if the rule is at the top level and is the only rule at that level. It doesn't really take subgroups into account, i.e. it lets them be removed even if they're the only thing left in the query. As long as the initial query has at least one rule that shouldn't be an issue but it's an edge case you should keep in mind. You might want to do something similar for import { useState } from 'react';
import type {
ActionWithRulesAndAddersProps,
Field,
RuleGroupType,
} from 'react-querybuilder';
import {
ActionElement,
QueryBuilder,
formatQuery,
getQuerySelectorById,
isRuleGroup,
useQueryBuilderSelector,
} from 'react-querybuilder';
import './styles.scss';
const fields: Field[] = [
{ name: 'firstName', label: 'First Name' },
{ name: 'lastName', label: 'Last Name' },
];
const initialQuery: RuleGroupType = {
combinator: 'and',
rules: [
{ field: 'firstName', operator: 'beginsWith', value: 'Stev' },
{ field: 'lastName', operator: 'in', value: 'Vai,Vaughan' },
],
};
const RemoveButton = (props: ActionWithRulesAndAddersProps) => {
const query = useQueryBuilderSelector(
getQuerySelectorById(props.schema.qbId)
);
if (
props.path.length === 1 &&
query?.rules.filter(r => !isRuleGroup(r)).length === 1
) {
return null;
}
return <ActionElement {...props} />;
};
export const App = () => {
const [query, setQuery] = useState(initialQuery);
return (
<div>
<QueryBuilder
fields={fields}
query={query}
onQueryChange={setQuery}
controlElements={{
removeRuleAction: RemoveButton,
}}
/>
<h4>Query</h4>
<pre>
<code>{formatQuery(query, 'json')}</code>
</pre>
</div>
);
}; |
Beta Was this translation helpful? Give feedback.
There are a few ways you could go with this. The code below demonstrates a "remove rule" button that won't render if the rule is at the top level and is the only rule at that level.
It doesn't really take subgroups into account, i.e. it lets them be removed even if they're the only thing left in the query. As long as the initial query has at least one rule that shouldn't be an issue but it's an edge case you should keep in mind. You might want to do something similar for
removeGroupAction
just in case.Working sandbox