Script for Javascript Field

264 views
Skip to first unread message

Mr. A. SMITH

unread,
Oct 11, 2025, 2:53:34 AMOct 11
to mementodatabase
In my Memento Database library "SALES REPORT" I have an embedded object field named "DEBIT ACCOUNT" with two attributes: "ACCOUNT NAME" and "AMOUNT". This library also includes a JavaScript field called "BALANCE" I have another library, "ACCOUNT REPORT" with the fields "ACCOUNT NAME", "OPENING BALANCE" , "Dr", "Cr" and "CLOSING BALANCE".

    I want the JavaScript field ( " BALANCE" ) in  the "SALES REPORT" library to retrieve and display the most recent "Closing Balance" from the "Account Report" library for the account selected in the "Debit Account" field. If multiple accounts are selected, the "Balance" field should show the balances for all chosen accounts.

Script :

// Get the embedded object field "Debit Account"
var debitAccounts = entry().field("DEBIT ACCOUNT")

// Initialize an array to store balance information
var balances = [];

// Access the "Account Report" library
var accountLib = libByName("ACCOUNT REPORT");

// Check if debitAccounts is not empty
if (debitAccounts && debitAccounts.length > 0) {
    // Iterate through each selected debit account
    for (var i = 0; i < debitAccounts.length; i++) {
        var accountName = debitAccounts[i].field("ACCOUNT NAME");
        
        // Find the latest entry in "Account Report" for this account name
        var accountEntries = accountLib.entries()
            .filter(function(e) { return e.field("ACCOUNT NAME") === accountName; })
            .sort(function(a, b) { return b.getCreatedAt() - a.getCreatedAt(); });
        
        // Get the closing balance from the latest entry
        if (accountEntries.length > 0) {
            var closingBalance = accountEntries[0].field("CLOSING BALANCE");
            balances.push(accountName + ": " + closingBalance);
        } else {
            balances.push(accountName + ": No balance found");
        }
    }
    
    // Return the balances as a formatted string
    result = balances.join("\n");
} else {
    result = "No accounts selected";
}

// Output the result
result;

I have tried this script generated from AI. But it is showing an error "libByName is not defined" . Please help me with the script if possible. 

Thanks.




Taeke

unread,
Oct 11, 2025, 7:42:44 AMOct 11
to mementodatabase
Hello Mister A.S. 

libByName might not be available in  JavaScript fields. From the documenation:

The JavaScript field is similar to a calculated field, but uses JavaScript expressions for calculations. Unlike other scripts in Memento Database, this field executes only in the context of an entry (has access to entry fields), not to any data. You can only read field values - modification of field values is not supported.


Op zaterdag 11 oktober 2025 om 08:53:34 UTC+2 schreef MR. A.S.:

David Gilmore

unread,
Oct 11, 2025, 10:41:50 AMOct 11
to mementodatabase
I would change the script to update the "Balance" field (and make it an ordinary field). I would place that script in a function located in your shared script area. And then call that function from the "Before Create" and "Before Update" triggers. This would accomplish what you want.

Bill Crews

unread,
Oct 11, 2025, 12:19:15 PMOct 11
to David Gilmore, mementodatabase
The direct answer to your immediate problem is that that script should be implemented as a trigger script more or less as suggested by David, and the BALANCE field should be a Currency field. JavaScript fields indeed cannot reference other libraries in this fashion. The script also contains references to the entry() function, which JavaScript field also can't access. In the trigger case, for each entry, the script will run, calculate the desired balance, and store that value into the BALANCE field. David's idea of making it a function in shared space seems like a good idea to me. 

But please allow me try to contribute by making some observations about your approach.

You are trying to operate your business based not on operational reference tables (or libraries) and transactional tables, but on a couple of reports that would typically be generated from such tables. Reports are not by nature operational, but informational in nature. This may cause various troubles as you go along. It would be better to create the tables themselves and use those. If so if what you have are only the reports, you likely could produce those operational tables from these two reports, though you don't have all the necessary information in these reports. The process of making tables from the reports would actually iron out the problems that will be caused by trying to use the reports as your basis. The tables to create would be Accounts, Sales Transactions, and Journal Entries (possibly also Products and maybe others). Also, if an account means a general ledger account, it would mean one thing, or maybe in this case it means a customer account. That would imply more things.

Your Embedded Object has two attributes: a name and an amount. Since the name of the library is SALES REPORT, I gather that the amounts are the amounts received in selling products, which have no library as yet. But there is no multivalued attribute or field that lists multiple sales for an account. I gather that each sale will cause the report to contain a separate entry, representing each sale, so you probably don't need to use an Embedded Object at all. A given account might contain many sales, so there is no library representing accounts themselves at all, which is why I suggested an Accounts library be created. As would Products, if you want such a library, Accounts would be reference libraries: one per account (or product), not transactional in nature, where entries represent transactions, not reference data.

The way you have your SALES REPORT library designed now, there is no list of sales within the Embedded Object field, but rather just a record of a product being sold against one account. There can be no list coming from this. 

This is getting long, and you and other readers might not be able to make use of this database design discussion, so I'll end it here, though there is more that needs to be said, according to me. If you have interest in further discussion about your database design, please contact me by private email at bill....@gmail.com. If some possibly useful result comes from that discussion, I'll be happy to report that result back to the forum. 

Good luck going forward.


--
You received this message because you are subscribed to the Google Groups "mementodatabase" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mementodataba...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/mementodatabase/c9e2711f-8ea6-44de-83af-46907e14701en%40googlegroups.com.

Mmm

unread,
Oct 12, 2025, 4:35:12 AMOct 12
to mementodatabase
Сначала внесу поправку: поле JS имеет доступ к объекту entry().
Это легко проверить. 
Например строкой,

entry().id;

Вариант 1.
Пожелание автора можно реализовать с помощью дополнительного текстового поля и триггеров.

Как выше уже отметили, в поле JS нельзя обратиться к объекту Library.
Но можно триггером при создании или изменении записи в момент открытия формы выполнить скрипт сбора сведений о всех счетах и текущих балансах. Результат сохранить в дополнительное текстовое поле в формате JSON. Поле можно поместить на скрытой странице. 

Это поле послужит источником данных для поля JS "BALANCE".

Чтобы не хранить лишнюю информацию, дополнительное поле очищать триггерами после сохранения.

Вариант 2.
Если счетов мало, отказаться от поля JS и сохранять информацию в нужном виде о всех счетах в текстовом поле. Информацию получать триггером в момент открытия формы создания или изменения записи и очищать после сохранения.

Вариант 3.
Добавить кнопку вызова окна dialog().

В окне должны отображаться все активные счета в виде ui().checkbox().

Если поле "DEBIT ACCOUNT", уже имеет элементы, то ui().checkbox() для этих счетов должны быть выбраны.

После подтверждения диалога, выполняется скрипт и заполняется текстовое поле "BALANCE".

Сохранять результат в поле не обязательно. Информацию можно отобразить в новом окне dialog(). А если счетов мало, то можно сразу вызывать окно с информацией о текущем балансе всех счетов без вызова окна выбора.

Дополнение: Сортировка в скрипте от ИИ не нужна.
В MDB последняя созданная запись имеет индекс 0. Если выполнить фильтр по счету, то запись filter[0] будет последней для счета.

суббота, 11 октября 2025 г. в 19:19:15 UTC+3, bill....@gmail.com:

Mmm

unread,
Oct 12, 2025, 9:06:14 AM (14 days ago) Oct 12
to mementodatabase
Тестовые библиотеки для Варианта 1 (JSON):


воскресенье, 12 октября 2025 г. в 11:35:12 UTC+3, Mmm:
IC__12102025.jpg

Mmm

unread,
Oct 14, 2025, 4:43:42 AM (12 days ago) Oct 14
to mementodatabase
Вариант с диалоговыми окнами.

1. Важно! Номера счетов должны быть внесены в атрибут "ACCOUNT NAME" поля "DEBIT ACCOUNT" заблаговременно.
В примере используется атрибут набор значений.
Добавить новый элемент (новый счёт) скриптом в этот тип атрибута нельзя.

2. Создать новую запись можно одним из трех скриптов действия в библиотеке, которые отличаются окном диалога.
Выбранные в форме счета автоматически добавляются в поле встроенный объект "DEBIT ACCOUNT".
После выбора подходящей формы, другие отключить или удалить.

2.1. "New entry 1" не показывает текущий баланс счёта.

2.2. "New entry 2" показывает в одной строке счёт и его баланс.
В строке два ui().text(): счёт и баланс.
Для выравнивая элементов баланса задана фиксированная ширина элемента счета в пикселях, которую нужно подобрать под свое устройство и записать в константе "acc_width" в начале скрипта (по умолчанию 550).
Валюта счета указывается в константе "currency" (по умолчанию "💎").

2.3. "New entry 3" показывает счёт и его баланс в разных строках.
Для одинакового отступа баланса от левого края формы добавлен пустой ui().text() с фиксированной шириной. Задаётся в константе "indent" в пикселях (по умолчанию 150).
Валюта - в константе "currency".

3. Кнопки в записи вызывают окна и показывают балансы счетов: все или выбор.
Балансы счетов отображаются только в форме и не сохраняется в записи. Для сохранения необходима доработка скриптов.

Тестовые библиотеки:
https://mementodb.com/s/6n8ot2wJM
https://mementodb.com/s/6xfuzPALj

воскресенье, 12 октября 2025 г. в 16:06:14 UTC+3, Mmm:

Mmm

unread,
Oct 17, 2025, 9:00:58 AM (9 days ago) Oct 17
to mementodatabase
Тестовые библиотеки удалены из облака.

Шаблон-контейнер:
вторник, 14 октября 2025 г. в 11:43:42 UTC+3, Mmm:
Scr_1.png

MR. A.S.

unread,
Oct 17, 2025, 7:54:47 PM (8 days ago) Oct 17
to mementodatabase
Many many thanks to everyone who replied here. 
@Bill Sir, 
I have 3 tables "Customer", "Account Report" , and "Sales Report" in this library. I don't need "Product" table because I am developing this library for " Recharge or Bill Payment Report". And here "Account" means Bank Account or Wallet from where money will be deducted during Recharge or Bill Payment . I will not use embedded object anymore. Button field script shared by @Mmm is the best option for my library.

@Mmm sir,
   Thank you very very much for your help. 
Sir, In my library, there will be 5-6 accounts, such as Bank 1, Bank 2, Wallet 1, Wallet 2, and CASH, etc. When I make a bill payment for a customer, the bill amount will be deducted from the selected single/multiple debit account(s). And the payments made by the customer will be added to the selected single/multiple credit account(s) . When the entry is saved in the "Sales Report" table, the debit and credit amounts of the selected accounts will be saved in the "Account Report" library.
I wanted to check the balance of the selected accounts before adding or deducting amounts, The button field script provided by you is the best for it.
      Now, I want that when I select single/multiple accounts from the  button field, a single/multiple currency field or dialogue/pop-up will appear to take the input amount which will be deducted/added from/with those selected account's Balance.
 

Please tell me if there is any script for it .

Thanks.

Mmm

unread,
Oct 18, 2025, 5:07:04 AM (8 days ago) Oct 18
to mementodatabase
Если я правильно понял, библиотека "ACCOUNT REPORT" является операционной.
Вы хотите создавать записи из формы диалога с выбором счета, вида проводки, валюты и суммы непосредственно в ней, минуя библиотеку "SALES REPORT". Верно?

Создайте копии своих библиотек (или новых, как Вы их видите), заполните их произвольными данными, чтобы понять структуру и связи библиотек.
Предоставьте общий доступ и включите разрешение копировать структуру.
Ссылки на библиотеки отправьте мне лично или сюда в тему.

суббота, 18 октября 2025 г. в 02:54:47 UTC+3, MR. A.S.:

Mmm

unread,
Oct 21, 2025, 1:35:43 PM (5 days ago) Oct 21
to mementodatabase
Вариант решения (оригинальных или тестовых библиотек от автора не видел).

Добавлены виджеты–скрипты с балансом каждого счета и виджет–кнопка вызова диалога с общими сведениями.

Поле "operation" для окраски фона записей в списке и видимости полей "Dr" и "Cr".

Добавлена агрегация – сумма по полям "Dr" и "Cr". Агрегация по каждому счету будет видна при группировке по названию счета.

Новые записи создаются скриптами действие в библиотеке: "New DEBIT" и "New CREDIT". 

Информация о балансе всех счетов – скрипт действие в библиотеке "BALANCE".

Шаблон примера библиотеки:
суббота, 18 октября 2025 г. в 12:07:04 UTC+3, Mmm:
IC__21102025.jpg

Mr. A. SMITH

unread,
Oct 23, 2025, 12:21:10 PM (3 days ago) Oct 23
to Mmm, mementodatabase
@Mmm 

  Sir, I am very much sorry for late reply.  Due to  lack of time, I can't complete my library yet. That's why I have not sent it here. 

I have checked your template. I want same work but using a "Button Field". Button will be placed in "Sales Report" library but new record will be created in "Account Reports" Library. 

I will try to Complete my library on Sunday. 

Many many thanks. 


Reply all
Reply to author
Forward
0 new messages