Blog  |  Support  |  Forums

Search Results for 'form.getRecords'

Tap Forms – Organizer Database App for Mac, iPhone, and iPad Forums Search Search Results for 'form.getRecords'

Viewing 15 results - 1 through 15 (of 141 total)
  • Author
    Search Results
  • Fernando DS
    Participant

    Hello everyone, I have an amount search script in the table field of all records. But it works for me with some quantities and not with others. And I don’t understand why.
    This is the script:

    // Definiciones de IDs de campos dentro de la tabla
    var pagos_cobros_tabla_id = ‘fld-a878bb1af5534101bcfab905279b1180’; // ID del campo Pagos/Cobros dentro de la tabla
    var movs_banco_tabla_id = ‘fld-57a5fdcd593e46b298948845321d78ac’; // ID del campo Mvtos. Banco dentro de la tabla
    var fecha_id = ‘fld-547c13e982e84d0793b0aba6c220cf76’; // ID del campo de fecha dentro de la tabla
    var nombre_id = ‘fld-baf116cd116e4cde9b65e79014a49f28’; // ID del campo de nombre dentro de la tabla
    var tabla_id = ‘fld-d8a58dbf35914f3c858c6dfb880c1c48’;
    var nota_id = ‘fld-7918261f865b489a8f7672cf733712a9’;
    var listado_de_script_id = ‘fld-555622f4bf0344f9b9e92af0806210fc’;
    // Reemplazar ‘XXXXXX’ con el ID del campo “Listado de script”

    // Define el importe a buscar
    var buscarImporte = “19.99”; // Ajusta este valor según el importe que desees buscar

    console.log(“”);
    console.log(“*************************************”);
    console.log(“Importe buscado: ” + buscarImporte);
    console.log(“*************************************”);
    console.log(“”);

    // Inicializar el contenido del campo “Listado de script”
    var output = “”;

    // Función para parsear el importe independientemente del formato
    function parseImporte(importeStr) {
    if (typeof importeStr === ‘string’) {
    return parseFloat(importeStr.replace(/[^\d.-]/g, ”)) || 0; // Devolver 0 si el valor no se puede convertir a número
    } else {
    return parseFloat(importeStr) || 0; // Devolver 0 si el valor no se puede convertir a número
    }
    }

    buscarImporte = parseImporte(buscarImporte);

    var records = form.getRecords();

    for (var i = 0; i < records.length; i++) {
    var record = records;
    var registrosTabla = record.getFieldValue(‘fld-d8a58dbf35914f3c858c6dfb880c1c48’) || []; // Reemplaza ‘tabla_id’ con el ID del campo de la tabla
    var nombre = record.getFieldValue(‘fld-baf116cd116e4cde9b65e79014a49f28’); // Obtener el nombre fuera del bucle de la tabla

    // Array para almacenar los movimientos correspondientes a cada nombre
    var movimientosNombre = [];

    for (var j = 0; j < registrosTabla.length; j++) {
    var registroTabla = registrosTabla[j];
    var pagosCobros = parseImporte(registroTabla.getFieldValue(pagos_cobros_tabla_id));
    var movsBanco = parseImporte(registroTabla.getFieldValue(movs_banco_tabla_id));
    var fechaRaw = new Date(registroTabla.getFieldValue(fecha_id));
    var fecha = ${('0' + fechaRaw.getDate()).slice(-2)}/${('0' + (fechaRaw.getMonth() + 1)).slice(-2)}/${fechaRaw.getFullYear().toString().substr(-2)};
    var nota = registroTabla.getFieldValue(nota_id);

    // Comparar el valor absoluto de los importes
    if (Math.abs(pagosCobros) === Math.abs(buscarImporte) || Math.abs(movsBanco) === Math.abs(buscarImporte)) {
    movimientosNombre.push({ fecha: fecha, movsBanco: movsBanco, pagosCobros: pagosCobros, nota: nota });
    }
    }

    // Mostrar el nombre y luego los movimientos correspondientes
    if (movimientosNombre.length > 0) {
    output += “\n” + nombre + “\n\n”;
    console.log(“” + nombre);
    console.log(“”);
    for (var k = 0; k < movimientosNombre.length; k++) {
    var movimiento = movimientosNombre[k];
    output += ${movimiento.fecha}: ${movimiento.movsBanco} | ${movimiento.pagosCobros}\n\n${movimiento.nota}\n;
    console.log(${movimiento.fecha}: ${movimiento.movsBanco} | ${movimiento.pagosCobros});
    console.log(“” + movimiento.nota);
    console.log(“”);
    }
    }
    }

    // Actualizar el campo “Listado de script” del primer registro con el texto generado
    record.setFieldValue(listado_de_script_id, output);

    // Guardar los cambios en los registros
    form.saveAllChanges();

    Any help will be welcome.

     

    #50623

    In reply to: Previous record skip

    Glen Forister
    Participant
    I can’t figure out how to fix the code so the first actual record after the “Begin Year Mark” record adds the $100 to $0 of the initialization record for the year.
    Thanks…
    Date Org $ Total$
    01/01/24 Begin. 0 0 Begin Year mark
    01/01/24. KVMR 100 0
    03/12/24 test 20 20
    03/27/24. test.2. 50 70
    04/17/24. test.3. 55 125
    Can’t remember how to display the code correctly – searched for it – Put that hint somewhere? “!”???
    !
    function Year_to_date() {
    var date_id = ‘fld-e2d20da877cb4a6c8fd72153b86f1ab1’;
    var donation_id = ‘fld-05c429d6a4484061b554aa584a45f8fc’;
    var total_id = ‘fld-7c6b9bb288ab47e0b295af6eacc9cd26’;
    var records = form.getRecords(); // calls function getRecords()
    var currentRecordIndex = records.indexOf(record);
    if (currentRecordIndex > 0) {
    var previousRecord = records[currentRecordIndex-1];
    } else {
    return 0;
    }
    // Is this the beginning of the year?
    var date = record.getFieldValue(date_id);
    if (date.getMonth() == 0 && date.getDate() == 1){
    return 0;
    }
    var today = record.getFieldValue(donation_id);
    var previous_total = previousRecord.getFieldValue(total_id);
    var total = today + previous_total;
    console.log(“Today: ” + today)
    console.log(“Previous: ” + previous_total)
    console.log(“Total: ” + total)
    return total;
    }
    Year_to_date();
    !
    #50622
    Glen Forister
    Participant
    I can’t figure out how to fix the code so the first actual record after the “Begin Year Mark” record adds the $100 to $0 of the initialization record for the year.
    Thanks…
    Date              Org         $     Total$
    01/01/24    Begin.      0         0            Begin Year mark
    01/01/24.   KVMR   100      0
    03/12/24    test          20      20
    03/27/24.  test.2.      50      70
    04/17/24.  test.3.      55     125
    Can’t remember how to display the code correctly – searched for it – Put that hint somewhere? “!”???
    !
    function Year_to_date() {
    var date_id = ‘fld-e2d20da877cb4a6c8fd72153b86f1ab1’;
    var donation_id = ‘fld-05c429d6a4484061b554aa584a45f8fc’;
    var total_id = ‘fld-7c6b9bb288ab47e0b295af6eacc9cd26’;
    var records = form.getRecords();   // calls function getRecords()
        var currentRecordIndex = records.indexOf(record);
        if (currentRecordIndex > 0) {
            var previousRecord = records[currentRecordIndex-1];
        } else {
          return 0;
        }
    // Is this the beginning of the year?
    var date = record.getFieldValue(date_id);
    if (date.getMonth() == 0 && date.getDate() == 1){
    return 0;
    }
    var today = record.getFieldValue(donation_id);
    var previous_total = previousRecord.getFieldValue(total_id);
    var total = today + previous_total;
    console.log(“Today: ” + today)
    console.log(“Previous: ” + previous_total)
    console.log(“Total: ” + total)
    return total;
    }
    Year_to_date();
    !
    #50454
    Fernando DS
    Participant

    <p style=”text-align: left;”>I send another script later and I think it’s more complete.

    </p>
    var fecha_pago_o_cobro_id = ‘fld-3671b67b092b4b3b949984292c023511’;
    var pagos_y_acumulado_id = ‘fld-a1ee93e141f34774be95df31d316be12’;
    var importes_y_acumulado_id = ‘fld-d72e37e939fe476e820ff4f3c4ef12c7’;
    var fecha_proximo_pago_o_cobro_id = ‘fld-51be737772e840d2b4d365bd1f5230cd’;
    var saldo_proximo_pago_o_cobro_id = ‘fld-a554770fd7834b22802b65c488be9f0d’;

    var fechaActual = new Date();
    var registros = form.getRecords();

    registros.forEach(function (registro) {
    var calculos = registro.getFieldValue(‘fld-d8a58dbf35914f3c858c6dfb880c1c48’) || [];

    if (calculos.length > 0) {
    var ultimoCalculo = calculos[calculos.length – 1];
    var fechaPagoCobro = new Date(ultimoCalculo[fecha_pago_o_cobro_id]);
    var importe = ultimoCalculo[importes_y_acumulado_id];

    if (fechaPagoCobro < fechaActual) {
    // Cumplimentar el campo Pagos con el valor del campo Importes para saldar el pago o cobro
    ultimoCalculo[pagos_y_acumulado_id] = importe;

    // Determinar la nueva fecha de pago o cobro
    var periodicidadTexto = registro.getFieldValue(‘fld-aaba9a24064a4a8893a3963f7cbe8595’);
    var nuevaFechaProximoPagoCobro = new Date(fechaPagoCobro);
    switch (periodicidadTexto) {
    case ‘Mensual’:
    nuevaFechaProximoPagoCobro.setMonth(nuevaFechaProximoPagoCobro.getMonth() + 1);
    break;
    case ‘Bimensual’:
    nuevaFechaProximoPagoCobro.setMonth(nuevaFechaProximoPagoCobro.getMonth() + 2);
    break;
    case ‘Trimestral’:
    nuevaFechaProximoPagoCobro.setMonth(nuevaFechaProximoPagoCobro.getMonth() + 3);
    break;
    case ‘Semestral’:
    nuevaFechaProximoPagoCobro.setMonth(nuevaFechaProximoPagoCobro.getMonth() + 6);
    break;
    case ‘Anual’:
    nuevaFechaProximoPagoCobro.setFullYear(nuevaFechaProximoPagoCobro.getFullYear() + 1);
    break;
    // Añadir más casos de periodicidad si es necesario
    default:
    console.error(‘Periodicidad no reconocida: ‘ + periodicidadTexto);
    break;
    }

    // Crear una nueva línea con la nueva fecha de pago o cobro y el mismo importe
    var nuevoCalculo = {
    ‘fecha_pago_o_cobro_id’: nuevaFechaProximoPagoCobro,
    ‘importes_y_acumulado_id’: importe,
    ‘pagos_y_acumulado_id’: ”
    };
    calculos.push(nuevoCalculo);

    // Actualizar los campos fuera de la tabla ‘Cálculos’
    registro.setFieldValue(fecha_proximo_pago_o_cobro_id, nuevaFechaProximoPagoCobro);
    // No es necesario actualizar ‘Saldo/próximo pago o cobro’ si es un campo calculado automáticamente

    // Guardar los cambios en el registro actual
    registro.setFieldValue(‘fld-d8a58dbf35914f3c858c6dfb880c1c48’, calculos);
    }
    }
    });

    form.saveAllChanges();

    #50453
    Fernando DS
    Participant
    • Hi everybody,

      I have an income and expense form and I want to automate it as much as possible. To do this, and with the invaluable help of my friend ChatGPT, I have made the script that I am sending you. What I want is for the last pending payments or collections to be credited when the script is executed, if the current date is later than the date of said payments or collections. The payment records are in a table-type field called “Calculations”, which includes the fields: – “Payment or collection date”, date type field, is the expected date for payment or collection. – “Amounts and accumulated”, numerical field, is the amount to be paid or collected. – “Payments and accruals”, numerical field, is filled in with the value of the Amounts field when the Payment Date arrives. What the script intends is that when the Payment or Collection Date is before the current date, the script will be executed and the following actions will occur: In the line of the last pending payment, the Payments field will be filled with the value of the Amounts field, so that payment or collection will be skipped. At the same time, a new line will be created with the new Payment or Collection Date and the new Amount, which is always the same, and therefore will copy the one imported from the previous movement. Regarding the new date, the script will take into account the “Periodicity” field, a text field that marks the type of period that passes between one movement and the next, monthly, annual, etc., and which is also outside the Calculations table. And with this the next pending payment or collection will be fulfilled. 2 more fields will also be fulfilled, which are outside the Calculations table: – Next payment or collection date, date type field, which will copy the date of the last pending payment or collection that has been created. – Balance/next payment or collection, field calculated with a formula, which is the balance between the totals of the Amounts and the Payments. Here the new balance will be incorporated, which will be equal to the previous one. And that would be it. I want to clarify that I also have records with different imports, but I find it very difficult to measure these in a script. Each record in the form is a different payment or collection and are independent of each other. Without prejudice to the fact that the amounts are added to obtain totals and balances.
      Obviously the script does not work. It has no errors in the console, but not working.

    • Anyway, I hope I have explained myself. Although I will clarify any doubts. And this is the script

     

    var fechaActual = new Date();
    var registros = form.getRecords();

    registros.forEach(function (registro) {
    var calculos = registro.getFieldValue(‘fld-d8a58dbf35914f3c858c6dfb880c1c48’) || [];
    var fechaProximoPagoCobro = registro.getFieldValue(‘fld-3671b67b092b4b3b949984292c023511’);
    var saldoProximoPagoCobro = registro.getFieldValue(‘fld-a554770fd7834b22802b65c488be9f0d’);
    var periodicidadTexto = registro.getFieldValue(‘fld-aaba9a24064a4a8893a3963f7cbe8595’);
    if (calculos.length > 0 && fechaProximoPagoCobro && saldoProximoPagoCobro && periodicidadTexto) {
    var fechaUltimoCalculo = new Date(calculos[calculos.length – 1].fecha_pago_o_cobro_id);

    // Si la última fecha de pago es anterior a la fecha actual
    if (fechaUltimoCalculo < fechaActual) {
    var nuevaFecha = new Date(fechaUltimoCalculo);
    var meses = { ‘Mensual’: 1, ‘Bimensual’: 2, ‘Trimestral’: 3, ‘Semestral’: 6, ‘Anual’: 12 };
    var dias = { ‘7 días’: 7 };

    // Añadir tiempo a la fecha según la periodicidad
    if (meses[periodicidadTexto]) {
    nuevaFecha.setMonth(nuevaFecha.getMonth() + meses[periodicidadTexto]);
    } else if (dias[periodicidadTexto]) {
    nuevaFecha.setDate(nuevaFecha.getDate() + dias[periodicidadTexto]);
    }

    // Si la nueva fecha es en el futuro, añadimos una nueva entrada
    if (nuevaFecha > fechaActual) {
    var ultimoImporte = calculos[calculos.length – 1].importes_y_acumulado_id;
    calculos.push({
    fecha_pago_o_cobro_id: nuevaFecha,
    importes_y_acumulado_id: ultimoImporte,
    pagos_y_acumulado_id: ”
    });
    }

    // Actualizamos el campo ‘Pagos y acumulado’ del último cálculo
    calculos[calculos.length – 1].pagos_y_acumulado_id = saldoProximoPagoCobro;

    // Guardamos los cambios en el registro
    registro.setFieldValue(‘fld-d8a58dbf35914f3c858c6dfb880c1c48’, calculos);

    form.saveRecord(registro);
    }
    }
    });

     

    Thank you in advance for your kind help.

    #50452

    In reply to:

    Fernando DS
    Participant
    • I have an income and expense form and I want to automate it as much as possible. To do this, and with the invaluable help of my friend ChatGPT, I have made the script that I am sending you. What I want is for the last pending payments or collections to be credited when the script is executed, if the current date is later than the date of said payments or collections. The payment records are in a table-type field called “Calculations”, which includes the fields: – “Payment or collection date”, date type field, is the expected date for payment or collection. – “Amounts and accumulated”, numerical field, is the amount to be paid or collected. – “Payments and accumulated”, numerical field, is filled in with the value of the Amounts field when the Payment Date arrives. What the script intends is that when the Payment or Collection Date is before the current date, the script is executed and the following actions occur: In the line of the last pending payment, the Payments field will be filled in with the value of the Amounts field, so that payment or collection will be settled. At the same time, a new line will be created with the new Payment or Collection Date and the new Amount, which is always the same, and therefore will copy the amount of the previous movement. Regarding the new date, the script will take into account the “Periodicity” field, a text field that marks the type of period that passes between one movement and the next, monthly, annual, etc., and which is also outside the Calculations table. And with this the next pending payment or collection will be completed. Two more fields will also be completed, which are outside the Calculations table: – Next payment or collection date, date type field, which will copy the date of the last pending payment or collection that has been created. – Balance/next payment or collection, field calculated with a formula, which is the balance between the totals of the Amounts and the Payments. Here the new balance will be incorporated, which will be equal to the previous one. And that would be it. I want to clarify that I also have records with different amounts, but I find it very difficult to put these in a script. Each record in the form is a different payment or collection and are independent of each other. Without prejudice to the fact that the amounts are added to obtain totals and balances. Anyway, I hope I have explained myself. Although I will clarify any doubts. And this is the script

     

    var fechaActual = new Date();
    var registros = form.getRecords();

    registros.forEach(function (registro) {
    var calculos = registro.getFieldValue(‘fld-d8a58dbf35914f3c858c6dfb880c1c48’) || [];
    var fechaProximoPagoCobro = registro.getFieldValue(‘fld-3671b67b092b4b3b949984292c023511’);
    var saldoProximoPagoCobro = registro.getFieldValue(‘fld-a554770fd7834b22802b65c488be9f0d’);
    var periodicidadTexto = registro.getFieldValue(‘fld-aaba9a24064a4a8893a3963f7cbe8595’);
    if (calculos.length > 0 && fechaProximoPagoCobro && saldoProximoPagoCobro && periodicidadTexto) {
    var fechaUltimoCalculo = new Date(calculos[calculos.length – 1].fecha_pago_o_cobro_id);

    // Si la última fecha de pago es anterior a la fecha actual
    if (fechaUltimoCalculo < fechaActual) {
    var nuevaFecha = new Date(fechaUltimoCalculo);
    var meses = { ‘Mensual’: 1, ‘Bimensual’: 2, ‘Trimestral’: 3, ‘Semestral’: 6, ‘Anual’: 12 };
    var dias = { ‘7 días’: 7 };

    // Añadir tiempo a la fecha según la periodicidad
    if (meses[periodicidadTexto]) {
    nuevaFecha.setMonth(nuevaFecha.getMonth() + meses[periodicidadTexto]);
    } else if (dias[periodicidadTexto]) {
    nuevaFecha.setDate(nuevaFecha.getDate() + dias[periodicidadTexto]);
    }

    // Si la nueva fecha es en el futuro, añadimos una nueva entrada
    if (nuevaFecha > fechaActual) {
    var ultimoImporte = calculos[calculos.length – 1].importes_y_acumulado_id;
    calculos.push({
    fecha_pago_o_cobro_id: nuevaFecha,
    importes_y_acumulado_id: ultimoImporte,
    pagos_y_acumulado_id: ”
    });
    }

    // Actualizamos el campo ‘Pagos y acumulado’ del último cálculo
    calculos[calculos.length – 1].pagos_y_acumulado_id = saldoProximoPagoCobro;

    // Guardamos los cambios en el registro
    registro.setFieldValue(‘fld-d8a58dbf35914f3c858c6dfb880c1c48’, calculos);

    form.saveRecord(registro);
    }
    }
    });

    #50281
    Fernando DS
    Participant

    Thank you Glen.

    I must say that my records are independent. Every record is a different debt.

    I have done the following script, but it continues not working. The saldo field is the result of importe-pagos, not saldo-pagos as I want. Any sugestions on the script?

     

    function updateRunningTotal(records) {
    records.forEach(function(record) {
    var importe = parseFloat(record.getFieldValue(‘fld-1cff7a1e6d3d4c68a081fa20be53ba48’)) || 0;
    var pagos = parseFloat(record.getFieldValue(‘fld-c4d4d96ce0584cef99a8422512ece4e6’)) || 0;
    var saldoAnterior = parseFloat(record.getFieldValue(‘fld-db305c87f3db46d0bbcaaf95dcb47858’)) || 0;

    // Calcular el nuevo Saldo basándose en el Saldo anterior y los Pagos
    var nuevoSaldo = saldoAnterior – pagos;

    // Actualizar el campo Saldo en el registro actual
    record.setFieldValue(‘fld-db305c87f3db46d0bbcaaf95dcb47858’, nuevoSaldo);

    console.log(“Importe: ” + importe);
    console.log(“Pagos: ” + pagos);
    console.log(“Saldo Anterior: ” + saldoAnterior);
    console.log(“Nuevo Saldo: ” + nuevoSaldo);
    });
    }

    var allRecords = form.getRecords();

    // Llamar a esta función para actualizar el Saldo basándose en el Saldo anterior y los Pagos en todos los registros
    updateRunningTotal(allRecords);

    #50268
    Daniel Leu
    Participant

    Hi Glen, in your original script, you were reading the previous total from the wrong field. Now it should work as expected:

    function toHrsMin(sec){
    let str = "";
    let h = Math.floor(sec / 3600);
    let m = (sec / 60) % 60;
    return h + ' hr, ' + m + ' mins';
    }
    function Accum_Tot() {
    var records = form.getRecords();
        var currentRecordIndex = records.indexOf(record);
        if (currentRecordIndex > 0) {
            var previousRecord = records[currentRecordIndex-1];
            var previous_total = previousRecord.getFieldValue('fld-b2f9616bf5e44fb4880ad9addd2afc6e');
        } else {
        var previous_total = 0;
        }
    var today = record.getFieldValue('fld-44acc9d2314f41beb3f2257ace5bae01');
    var total = today + parseInt(previous_total);
    console.log("Today: " + toHrsMin(today))
    console.log("Previous: " + toHrsMin(previous_total))
    console.log("Total: " + toHrsMin(total))
    return total;
    }
    Accum_Tot();
    • This reply was modified 3 months, 4 weeks ago by Daniel Leu.
    #50249
    Daniel Leu
    Participant

    This works for me:

    function toHrsMin(sec){
       let h = Math.floor(sec / 3600);
       let m = (sec / 60) % 60;
       return h + ' hr, ' + m + ' mins';
    }
    function Accum_Tot() {
       var records = form.getRecords();
       var currentRecordIndex = records.indexOf(record);
       if (currentRecordIndex > 0) {
          var previousRecord = records[currentRecordIndex-1];
      var previous_total = previousRecord.getFieldValue('fld-44acc9d2314f41beb3f2257ace5bae01');
       } else {
          var previous_total = 0;
       }
       var today = record.getFieldValue('fld-44acc9d2314f41beb3f2257ace5bae01');
       var total = today + previous_total;
       console.log("Today: " + toHrsMin(today))
       console.log("Previous: " + toHrsMin(previous_total))
       console.log("Total: " + toHrsMin(total))
       return total;
    }
    Accum_Tot();
    • This reply was modified 4 months ago by Daniel Leu.
    • This reply was modified 4 months ago by Daniel Leu.
    • This reply was modified 4 months ago by Daniel Leu.
    • This reply was modified 4 months ago by Daniel Leu.
    • This reply was modified 4 months ago by Daniel Leu.
    • This reply was modified 4 months ago by Daniel Leu.
    • This reply was modified 4 months ago by Daniel Leu.
    #50176
    Fernando DS
    Participant

    At last this is the script that works:

    function modifyFieldsBasedOnCondition() {
    var fieldId1 = ‘fld-28b97ce8ab4f4f57a83aefa7e91f17fe’;
    var fieldId2 = ‘fld-c2fd26ae62c1445692b3a0abc1e89158’;

    for (var record of form.getRecords()) {
    var valueField1 = record.getFieldValue(fieldId1);
    var valueField2 = record.getFieldValue(fieldId2);

    if (valueField1 === 4 && (valueField2 === null || valueField2 === “”)) {
    record.setFieldValue(fieldId2, “Buen disco.”);
    console.log(“Campo fieldid2 actualizado en el registro con campo fieldid1 igual a 4 y fieldid2 vacío.”);
    }
    }

    form.saveAllChanges();
    }

    modifyFieldsBasedOnCondition();

     

    Thank you Brendan and Daniel for your valuable help.

    Bye.

     

    #50169
    Daniel Leu
    Participant

    This works for me:

     function modifyFieldsBasedOnCondition() {
    
    var fieldId1 = 'fld-28b97ce8ab4f4f57a83aefa7e91f17fe';
    var fieldId2 = 'fld-c2fd26ae62c1445692b3a0abc1e89158';
       for (var record of form.getRecords()) {
          console.log(record.getFieldValue(fieldId1));
          console.log(record.getFieldValue(fieldId2));
          if (record.getFieldValue(fieldId1) == 4 &&
             record.getFieldValue(fieldId2) == undefined)
          {
             record.setFieldValue(fieldId2, "Buen disco.");
             console.log("empty record found");
          }
       }
       form.saveAllChanges();
    }
    modifyFieldsBasedOnCondition();
    • This reply was modified 5 months ago by Daniel Leu.
    • This reply was modified 5 months ago by Daniel Leu.
    • This reply was modified 5 months ago by Daniel Leu.
    • This reply was modified 5 months ago by Daniel Leu.
    • This reply was modified 5 months ago by Daniel Leu.
    #50167
    Fernando DS
    Participant

    Just another try, without errors in console, but not works.

    function modifyFieldsBasedOnCondition() {
    var fieldId1 = 'fld-28b97ce8ab4f4f57a83aefa7e91f17fe';
    var fieldId2 = 'fld-c2fd26ae62c1445692b3a0abc1e89158';
    
    for (var record of form.getRecords()) {
    if (record.getFieldValue(fieldId1) == 4 &&
    record.getFieldValue(fieldId2) <= (0))
    record.setFieldValue(fieldId2, "Buen disco.");
    }
    }
    
    form.saveAllChanges();
    
    modifyFieldsBasedOnCondition();
    • This reply was modified 5 months ago by Brendan.
    #50160
    Fernando DS
    Participant

    Well, I’m going to paste it here.

     

    function modifyFieldsBasedOnCondition() {
    var fieldId1 = 'fld-28b97ce8ab4f4f57a83aefa7e91f17fe';
    var fieldId2 = 'fld-c2fd26ae62c1445692b3a0abc1e89158';
    
    for (var record of form.getRecords()) {
    if (record.getFieldValue(fieldId1) == 4 &&
    record.getFieldValue(fieldId2) == "") {
    record.setFieldValue(fieldId2, "Buen disco.");
    }
    }
    
    form.saveAllChanges();
    }
    
    modifyFieldsBasedOnCondition();
    • This reply was modified 5 months, 1 week ago by Brendan.
    #50104

    In reply to: Javascript Help

    Daniel Leu
    Participant

    In my case, the checkbox field is called ‘selected’. You just need to assign the field id of field Added_to_VR-Mailing on line 3 of the code below.

    // This script selects all records
    
    function selectAll(){
    const selected_id = 'fld-xxxx';
    var records = form.getRecords();
    
    for (var index = 0, count = records.length; index < count; index++){
    var myRec = records[index];
    myRec.setFieldValue(selected_id, true);
    }
    
    document.saveAllChanges();
    }
    
    selectAll();

    The code loops over all records and sets the checkbox value to true.

    • This reply was modified 5 months, 3 weeks ago by Daniel Leu.
    • This reply was modified 5 months, 3 weeks ago by Daniel Leu.
    • This reply was modified 5 months, 3 weeks ago by Daniel Leu.
    #50016

    In reply to: Open record as result

    Daniel Leu
    Participant

    I got it working after some edits. It shows as well that form.selectRecord(someRecord); works :). The issue was results vs results_name. The former contains the found records while the latter contains the matching names.

    A remaining issue is when you get more than one match. Since you match on the name and then use results_name.indexOf(name) to find the index, you will always stop at the first found entry. This needs some refinement.

    //var myForm = document.getFormNamed(‘Test’);
    //var records = myForm.getRecords();
    var records = form.getRecords();
    var search_term = Utils.copyTextFromClipboard();
    var result_count = 0;
    var results = [];
    var results_name = [];
    var selected;
    function show_name( name ) {
        form.selectRecord(name);
    }
    function copy_result_multiple( name ) {
        if ( name == true ) {
        let index = results_name.indexOf(selected);
            console.log( 'Index:' + index );
            console.log( results_name[index]);
            show_name( results[index]);
        } else {
            console.log( 'Cancelled' );
        }
    }
    function multiple_results( all_results ) {
        let prompter = Prompter.new();
        prompter.cancelButtonTitle = 'cancel';
        prompter.continueButtonTitle = 'Show Name';
        prompter.addParameter('Select Result ', 'selected', 'popup', results_name)
        .show('Multiple Results Found', copy_result_multiple );
    }
    function search_records( haystack , needle ) {
    var name_id = 'fld-5ecd60d90a8246f4853175f6fc6aaabe';
    //var name_id = 'fld-1acb38c0b51b44698849501407b51722';
        var rec;
        for (rec of haystack) {
        var name = rec.getFieldValue( name_id );
        if (name && name.includes( needle ) ) {
                results.push( rec );
                results_name.push( rec.getFieldValue( name_id ) );
                result_count++;
            } else {
            if (! name) {
           console.log("Empty field: " + rec.getUrl());
            }
            }
        }
        if( result_count == 0 ){
            Utils.alertWithMessage("No Results", "No results were found for the search term: " + needle);
        } else if ( result_count > 1 ){
            //multiple results
            console.log("Found " + result_count + " matches");
            multiple_results( results );
        } else {
            //single result
            console.log("Found one match");
            show_name( results[0] );
        }
    }
    search_records( records , search_term );
    • This reply was modified 6 months, 1 week ago by Daniel Leu.
    • This reply was modified 6 months, 1 week ago by Daniel Leu.
    • This reply was modified 6 months, 1 week ago by Daniel Leu.
    • This reply was modified 6 months, 1 week ago by Daniel Leu.
    • This reply was modified 6 months, 1 week ago by Daniel Leu.
Viewing 15 results - 1 through 15 (of 141 total)
 
Apple, the Apple logo, iPad, iPhone, and iPod touch are trademarks of Apple Inc., registered in the U.S. and other countries. App Store is a service mark of Apple Inc.