Answer the question
In order to leave comments, you need to log in
How to generate a unique string before saving to the database (D7 bitrix)?
Hello.
Edition start.
Wrote my module and lie in local/modules/my.name/Order/OrderTable.php
This is the described table model with orders.
Those we have a table in which there are fields id, user_id, delivery_id .... in general,
there are many fields of all sorts and one of these fields is called order_num and has a string format.
As you may have guessed, this is the order number and it must be unique (exactly number and not id in the database)
class OrderTable extends Entity\DataManager
{
public static function getTableName()
{
return 'dch_order';
}
public static function getMap()
{
return array(
new Entity\IntegerField('ID', array(
'primary' => true,
'autocomplete' => true
)),
new Entity\StringField('ORDER_NUM', array(
'required' => false
)),
.......
}
public static function onBeforeAdd(Entity\Event $event)
{
$result = new Entity\EventResult;
$data = $event->getParameter("fields");
if (!$data['ORDER_NUM']) {
$resOrders = OrderTable::getList([
'select' => ['ID', 'DATE_CREATE', 'ORDER_NUM'],
'order' => ['ORDER_NUM' => "DESC"],
'filter' => ['!ORDER_NUM' => false],
'limit' => 1
]);
if ($arOrder = $resOrders->fetch()) {
$newOrderNum = (int)$arOrder['ORDER_NUM'] + 1;
$result->modifyFields(['ORDER_NUM' => $newOrderNum]);
}
}
return $result;
}
$res = OrderTable:add([...]);
$orderId = res->getId();
Answer the question
In order to leave comments, you need to log in
searches in the table with the order for the order with the last number
gets it (number) and assigns +1 to it - this is the number for the new order
There can be only one case when you need to generate an identifier before entering into the database, and this is when the client is forced to perform operations related to a record not made in the database with an unlinked state.
Example - you create a to-do list on the client and add new items to this new list. And you need it all to work, even while there is no connection to the database, and it will be synchronized later. In this case, UUIDs are invented.
In your case, there is nothing of the kind, so it's correct - an auto-incrementing field.
In the simplest case, +1 in other cases (wholesale order, individual delivery, distant warehouse), order numbers can take the form AA-02-1122, AA-02-1123, AA-02-1124.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question