Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -388,13 +388,100 @@ export default EditFormController.extend({
Если необходима дополнительная логика при изменении значения лукапа, то в контроллере формы, на которой расположен лукап, следует переопределить экшен `updateLookupValue`:

```js
actions: {
updateLookupValue() {
// Базовая логика
this._super(...arguments);
actions: {
updateLookupValue(updateData) {
// Базовая логика
this._super(...arguments);

// Дополнительная логика
// ...
}
}
```

Объект `updateData` имеет формат:

```js
{
relationName: /* Значение атрибута relationName. Название связи в модели, куда записывается выбранное значение. */,
modelToLookup: /* Значение атрибута relatedModel. Модель, чей атрибут отображает данный компонент. */,
newRelationValue: /* Значение атрибута value. Новое значение мастера. */,
componentName: /* Значение атрибута componentName. Имя компонента. */
}
```

Данное событие срабатывает каждый раз когда меняется значение атрибута `value` лукапа:

* Выбор значения в лукапе;
* Выбор значения по autocomplete;
* Выбор значения в DropDown режиме.

## Возможность переопределить поведение при очистке значения лукапа

Если необходима дополнительная логика при очистке значения лукапа, то в лукапе следует указать событие или функцию в свойстве `remove`. Обычно это `removeLookupValue`:

```js
{% raw %}{{flexberry-lookup
...
remove="removeLookupValue"
...
}}{% endraw %}
```

// Дополнительная логика
// ...
Тогда функция будет выглядеть так:

```js
removeLookupValue(removeData) {
// Дополнительная логика
// ...
}
```
Comment on lines +433 to +438
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Дополните пример обработкой ошибок

Рекомендуется расширить пример:

  • Добавить обработку ошибок
  • Указать возвращаемое значение
  • Показать как правильно обновить модель
 removeLookupValue(removeData) {
+  try {
     // Дополнительная логика
     // ...
+    this.set(`model.${removeData.relationName}`, null);
+    return true;
+  } catch (error) {
+    console.error('Ошибка при очистке значения:', error);
+    return false;
+  }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
```js
removeLookupValue(removeData) {
// Дополнительная логика
// ...
}
```
```js
removeLookupValue(removeData) {
try {
// Дополнительная логика
// ...
this.set(`model.${removeData.relationName}`, null);
return true;
} catch (error) {
console.error('Ошибка при очистке значения:', error);
return false;
}
}
```


Объект `removeData` имеет формат:

```js
{
relationName: /* Значение атрибута relationName. Название связи в модели, куда записывается выбранное значение. */,
modelToLookup: /* Значение атрибута relatedModel. Модель, чей атрибут отображает данный компонент. */
}
```

Данное событие срабатывает каждый раз когда очищается значение атрибута `value` лукапа:

* Очистка значения в лукапе. Например, по кнопке "Очистить";
* Выбор значения по autocomplete, которое не соответствует никакому объекту лукапа;

## Настройка событий лукапа для groupEdit

Для возможности настройки событий лукапа, находящегося внутри `flexberry-gropedit`, необходимо в контроллер добавить метод `getCellComponent`.

Пример:

```js
getCellComponent(attr, bindingPath, model) {
let cellComponent = this._super(...arguments);

// Признак мастеровой связи.
if (attr.kind === 'belongsTo') {
let updateLookupValue = this.get('actions.updateLookupValue').bind(this);

switch (`${model.modelName}+${bindingPath}`) {
// ${Имя модели лукапа}+${Имя свойства, которое редактирует лукап}
case 'test-project-test-model+testAttr':
cellComponent.componentProperties = {
...
remove: 'removeLookupValue',
updateLookupValue: updateLookupValue
...
};
break;

...
}
}
```

...

return cellComponent;
},
```
Comment on lines +461 to +487
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Улучшите пример метода getCellComponent

Рекомендуется:

  • Добавить проверку входных параметров
  • Улучшить обработку ошибок
  • Дополнить документацию примерами использования
 getCellComponent(attr, bindingPath, model) {
+  if (!attr || !bindingPath || !model) {
+    console.warn('getCellComponent: missing required parameters');
+    return null;
+  }
+
   let cellComponent = this._super(...arguments);
   
   // Признак мастеровой связи.
   if (attr.kind === 'belongsTo') {
     let updateLookupValue = this.get('actions.updateLookupValue').bind(this);
 
     switch (`${model.modelName}+${bindingPath}`) {
       // ${Имя модели лукапа}+${Имя свойства, которое редактирует лукап}
       case 'test-project-test-model+testAttr':
         cellComponent.componentProperties = {
           ...
           remove: 'removeLookupValue',
           updateLookupValue: updateLookupValue
           ...
         };
         break;
 
+      default:
+        console.warn(`Unexpected model+bindingPath: ${model.modelName}+${bindingPath}`);
+        break;
     }
   }
 
   return cellComponent;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
getCellComponent(attr, bindingPath, model) {
let cellComponent = this._super(...arguments);
// Признак мастеровой связи.
if (attr.kind === 'belongsTo') {
let updateLookupValue = this.get('actions.updateLookupValue').bind(this);
switch (`${model.modelName}+${bindingPath}`) {
// ${Имя модели лукапа}+${Имя свойства, которое редактирует лукап}
case 'test-project-test-model+testAttr':
cellComponent.componentProperties = {
...
remove: 'removeLookupValue',
updateLookupValue: updateLookupValue
...
};
break;
...
}
}
```
...
return cellComponent;
},
```
getCellComponent(attr, bindingPath, model) {
if (!attr || !bindingPath || !model) {
console.warn('getCellComponent: missing required parameters');
return null;
}
let cellComponent = this._super(...arguments);
// Признак мастеровой связи.
if (attr.kind === 'belongsTo') {
let updateLookupValue = this.get('actions.updateLookupValue').bind(this);
switch (`${model.modelName}+${bindingPath}`) {
// ${Имя модели лукапа}+${Имя свойства, которое редактирует лукап}
case 'test-project-test-model+testAttr':
cellComponent.componentProperties = {
...
remove: 'removeLookupValue',
updateLookupValue: updateLookupValue
...
};
break;
default:
console.warn(`Unexpected model+bindingPath: ${model.modelName}+${bindingPath}`);
break;
}
}
return cellComponent;
},