Question
It is necessary to perform a uniqueness check of the SKU before saving the product in the products table from another table to prevent duplicates in the products table. How should this be done correctly? Additionally, it is necessary to remove all unnecessary characters from the SKU, leaving only the allowed ones. Ideally, the process should involve removing the unnecessary characters, then checking for duplicates in the products table, and finally saving the product.
Answer
This can be done by adding an action code when adding to the field with the SKU. It checks for duplicates and blocks the action if it finds any.
Action code when adding to the field with the SKU in the table where we add rows:
ad1=: if(condition: $select != ""; then: $err)
select: select(table: $#ntn; field: 'id'; where: 'id' != #id; where: $#nf = $#nfv)
err: errorException(text: "Already have this SKU")
only_numbers: if(condition: $matches = true; then: $replace; else: #sku_data)
matches: strRegAllMatches(str: #sku_data; template: "([^a-zA-Z0-9a-zA-Z .,\-+{}()]+)"; matches: "matches"; flags: "u")
replace: strReplace(str: #sku_data; from: $#matches[0]; to: "")
In only_numbers, we search for a list of all characters not included in the allowed list. Then we replace everything that is not a-zA-Z0-9a-zA-Z .,\-+{}()
with "".
Next, we search for a row in the current table where the current field equals the value of the current field in the new row. Since action codes are executed after codes, the row already exists and is recorded in the database, so we need to specify that we exclude the current row where: 'id' != #id;
to avoid false triggering on itself.