Angular update reactive formgroup values

In my Angular application, I have a [formGroup]=”form” and have a submit function which is submitting the form. Currently the form value is being submitted as :

{"customerId": 11,"email": "[email protected]","someId": {
"xid": [
  "AB12456,
  "AB345678"
]},"task": ["admin"]}

I need to change 1 key (someId) to “someIds” and send the form values as follows. What will the best approach for this. Assuming that “someIds” come as values from multiselect dropdown change.

{"customerId": 11, "email": "[email protected]", "someIdsxyz": [
{
  "yId": "abcd1",
  "yType": "abcd2"
},
{
  "yId": "pqrs1",
  "yType": "pqrs2"
}], "task": ["admin"]}

Can anyone suggest?

Django Formset Nested Structure Not Posting Correctly for Dynamic Fields

I’m working on a Django nested formset where users can:

  • Add multiple colors to a product.
  • For each color, add multiple sizes dynamically using JavaScript.
  • Each size should have its own size_name, stock, and price_increment field.

Issue

When submitting the form, Django is incorrectly grouping multiple size field values into lists instead of treating them as separate entries.

Expected Django POST Data (Correct Structure)

sizes-0-0-size_name = "Small"
sizes-0-0-stock = "100"
sizes-0-0-price_increment = "50"

sizes-0-1-size_name = "Medium"
sizes-0-1-stock = "150"
sizes-0-1-price_increment = "75"

Actual Django POST Data (Incorrect Structure)

sizes-0-0-size_name = ["Small", "Medium"]
sizes-0-0-stock = ["100", "150"]
sizes-0-0-price_increment = ["50", "75"]
  • Instead of separate fields for each size, Django is grouping values into a single list.
  • The sizes-0-TOTAL_FORMS field is appearing twice in the POST request, which might indicate a JavaScript duplication issue.

Debugging the Request Data (request.POST)

<QueryDict: {
    'colors-TOTAL_FORMS': ['1'],
    'sizes-0-TOTAL_FORMS': ['1', '1'],  # This should be a single value, not duplicated
    'sizes-0-0-size_name': ['Small', 'Medium'],
    'sizes-0-0-stock': ['100', '150'],
    'sizes-0-0-price_increment': ['50', '75']
}>

Potential Causes:

  1. JavaScript Issue:

    • Dynamic form addition might be incorrectly naming inputs, causing Django to interpret multiple values as a list.
    • TOTAL_FORMS for sizes might not be updated properly, leading to duplicate values.
  2. Django Formset Issue:

    • Django might not be detecting individual size inputs properly due to incorrect prefix handling.

Code Implementation

Forms (forms.py)

class ProductForm(forms.ModelForm):
    class Meta:
        model = VendorProduct
        fields = ['title', 'cagtegory', 'base_price']

class ProductColorForm(forms.ModelForm):
    class Meta:
        model = ProductColor
        fields = ['color_name', 'color_code']

class ProductSizeForm(forms.ModelForm):
    class Meta:
        model = ProductSize
        fields = ['size_name', 'stock', 'price_increment']

ProductColorFormSet = inlineformset_factory(
    VendorProduct, ProductColor, form=ProductColorForm, extra=1, can_delete=True
)
ProductSizeFormSet = inlineformset_factory(
    ProductColor, ProductSize, form=ProductSizeForm, extra=1, can_delete=True
)

View (views.py)

@login_required
def add_product(request):
    if request.method == 'POST':
        product_form = ProductForm(request.POST)
        color_formset = ProductColorFormSet(request.POST, prefix='colors')

        if product_form.is_valid() and color_formset.is_valid():
            product = product_form.save()
            for color_index, color_form in enumerate(color_formset):
                if color_form.cleaned_data.get('color_name'):
                    color = color_form.save(commit=False)
                    color.product = product
                    color.save()

                    # **Check if sizes are structured properly**
                    size_formset = ProductSizeFormSet(
                        request.POST, instance=color, prefix=f'sizes-{color_index}'
                    )
                    print(f"Processing sizes for color index {color_index}:")
                    print(request.POST)

                    if size_formset.is_valid():
                        size_formset.save()

            return redirect('vendorpannel:vendor_shop')

    else:
        product_form = ProductForm()
        color_formset = ProductColorFormSet(prefix='colors')
        color_size_formsets = [
            ProductSizeFormSet(instance=color_form.instance, prefix=f'sizes-{index}')
            for index, color_form in enumerate(color_formset.forms)
        ]

    return render(request, 'vendorpannel/add-product.html', {
        'product_form': product_form,
        'color_formset': color_formset,
        'color_size_formsets': color_size_formsets,
    })

JavaScript for Dynamic Form Handling (add_product.html)

document.addEventListener("DOMContentLoaded", function () {
    let colorIndex = document.querySelectorAll(".color-item").length;
    function addColor() {
        let totalForms = document.querySelector('[name="colors-TOTAL_FORMS"]');
        let newColor = document.querySelector(".color-item").cloneNode(true);
        newColor.querySelectorAll("input").forEach(input => {
            input.name = input.name.replace(/colors-d+/g, `colors-${colorIndex}`);
            input.value = "";
        });

        let sizeContainer = newColor.querySelector(".sizeContainer");
        sizeContainer.innerHTML = "";

        let sizeTotalForms = document.createElement("input");
        sizeTotalForms.type = "hidden";
        sizeTotalForms.name = `sizes-${colorIndex}-TOTAL_FORMS`;
        sizeTotalForms.value = "0";
        sizeContainer.appendChild(sizeTotalForms);

        document.getElementById("colorContainer").appendChild(newColor);
        totalForms.value = colorIndex + 1;
        colorIndex++;
    }

    document.getElementById("addColorButton")?.addEventListener("click", addColor);
});

What I’ve Tried:

✅ Ensured sizes-{colorIndex}-TOTAL_FORMS exists before adding sizes dynamically.
✅ Used name.replace() correctly to update input names.
✅ Verified prefix usage in Django forms and formsets.


Question:

How can I ensure that each size input field gets a unique name instead of Django grouping multiple values into lists?

How to trigger browser extension’s keyboard shortcut in Playwright?

I’m trying to test my browser extension. Pressing Ctrl+Q command injects HTML form into a current page. I want to test this behaviour, but Playwright seems to be unable to trigger it during tests which leads to the test failing. If I press the shortcut manually while the browser instance is running, the form appears correctly. What am I doing wrong?

import test, { chromium, expect } from "@playwright/test";
import path from "path";
import fs from 'fs';

test.use({ browserName: 'chromium' });

test('Open example.com and trigger the popup form', async () => {
  const pathToExtension = path.resolve(__dirname, '..', 'dist');
  const userDataDir = path.resolve(__dirname, '..', 'tmp-profile');

  if (fs.existsSync(userDataDir)) {
    fs.rmSync(userDataDir, { recursive: true, force: true });
  }

  const browserContext = await chromium.launchPersistentContext(userDataDir, {
    headless: false,
    args: [
      `--disable-extensions-except=${pathToExtension}`,
      `--load-extension=${pathToExtension}`
    ]
  });

  const page = await browserContext.newPage();
  await page.goto('https://example.com');
  await page.waitForLoadState('networkidle');

  console.log('Browser launched...');
  
  page.keyboard.press('Control+q'); // doesn't happen

  const popupForm = page.getByLabel('extension-popup-form');
  expect(popupForm).toBeVisible(); // fails here because the form wasn't triggered
  expect(popupForm).toHaveText('https://example.com');

  await popupForm.press('Enter');
  expect(page).toHaveTitle('Blocked | On Pace Extension');

  browserContext.close();
});

I tried this:

  • dispatching event like this:
await page.evaluate(() => {
  document.dispatchEvent(new KeyboardEvent('keydown', {
    key: 'q',
    code: 'KeyQ',
    ctrlKey: true,
    bubbles: true,
    cancelable: true
  }));
});
  • simulated each key press separately in case the automated shortcut was to quick:
  await page.keyboard.down('Control');
  await page.waitForTimeout(800);
  await page.keyboard.press('q');
  await page.waitForTimeout(600);
  await page.keyboard.up('Control');
  • tried focusing on an element of a page before firing the event;
  • tried running the test on https://www.toptal.com/developers/keycode to ensure the codes of pressed keys were correct (they were).
  • tried experimenting with timeout values before running the event:

await page.waitForTimeout(5000);

  • tried manually pressing the command while the browser instance was running to ensure the extension was loaded correctly (it was).

Fetch returning 404 [closed]

The api link is working but for some reason when i try to fetch it, it shows 404 on console

console gets: 404 (Not Found)

const outputElement = document.createElement("h1");
document.body.appendChild(outputElement);

const reqOptions = {
  method: "GET",
  Headers: "Access-Control-Allow-Origin",
};

function getJson(urlApi) {
  fetch(urlApi)
    .then((response) => {
      if (!response.ok) {
        throw new Error("Network is not ok");
      }
      return response.json();
    })
    .then((data) => {
      console.log(data);
      outputElement.textContent = JSON.stringify(data.location);
    })
    .catch((error) => {
      console.error(error);
    });
}

OnTabChange Event not fired on TinyMCE Custom Dialog with TabPanel

With TinyMCE V6, in a custom dialogs, i’d like to handle the tab change event of a tabpanel which got two tabs. I tried to use ‘OnTabChange’, ‘OnChange’ but none of them was never fired. How can i achieve this?

Here’s the code i used:

let activeTab = 'Insert_UGC_From_ID';
const InsertUgcPanel = {
    title: 'Insertion'
    body: {
        type: 'tabpanel',
        tabs: [...]
            }
        ]
    },
    buttons: [{
            type: 'custom',
            name: 'insert-UGC-button',
            text: 'Insérer la chaîne'
        },
        {
            type: 'custom',
            name: 'doesnothing',
            text: 'Annuler'
        }
    ],
    onTabChange: (dialogApi, details) => {
        if (details.name) {
            activeTab = details.name;}
    },  
    onAction: (dialogApi, details) => {
        if (details.name === 'insert-UGC-button') {
            const data = dialogApi.getData()
            dialogApi.close()
        } else if (details.name === 'doesnothing') {
            dialogApi.close()
        }
    }

};

using syncfusion-vue-uploader with vue-3

I am using Vue Syncfusion Uploader (ejs-uploader) to upload files. The upload functionality works fine, and Syncfusion provides a function to handle the selected file.

<template>
  <ejs-uploader
    :buttons="buttonsText"
    id="template"
    name="UploadFiles"
    :multiple="false"
    ref="profileUploader"
    @selected="handleProfilePic"
    @removing="fileDeleted($event, 'profile')"
    :disabled="isView"
  />
</template>

<script setup>
import { ref, onMounted } from "vue";

const fileRecordsForUpload = ref([]);
const profileFiles = ref([]);
const props = defineProps(["rowData"]);

const handleProfilePic = (e) => {
  fileRecordsForUpload.value.push({
    fileName: e.filesData[0].rawFile.name,
    file: e.filesData[0].rawFile,
    originalName: e.filesData[0].rawFile.name,
  });
};

onMounted(() => {
  profileFiles.value = props.rowData.driverDocuments
    .filter((file) => file.documentType === "Driver Picture")
    .map((file) => ({
      name: file.documentName,
      type: "image/jpeg", // Default type
      fileSource: file.contentUrl, // File URL
    }));
});
</script>

After successfully uploading a file, when I open the specific record, all other text data loads correctly, but the previously uploaded file is not displayed in the Syncfusion Uploader.

I tried using v-model, but it didn’t work. How can I prepopulate the Syncfusion Uploader with the previously uploaded file when viewing a record?

Any help would be appreciated!

HTMLCollection does not function for loops [duplicate]

I encountered a problem of making a for loop after a document.getElementsByClassName(“..”)

document.addEventListener('DOMContentLoaded', function() {
let btnTitle = document.getElementsByClassName("button-title");
console.log("Number of button-title elements found:", btnTitle.length);
if (btnTitle) {
    console.log("all button: ", btnTitle);
    Array.from(btnTitle).forEach((btn) => {
        console.log("btn", btn);
        btn.addEventListener("click", (event) => {
            const courseContent = btn.nextElementSibling;
            console.log("courseContent:", courseContent)
            courseContent.classList.toggle('show');
        })
    })
}
}

It will be returning like the image

Image of console

I don’t understand why btnTitle.length return 0, but it still has btnTitle in console, and it has one element who owns a length: 1. I did it because I want to debug why the button’s function is not working

And this is how I create the buttons by javascript (if it’s necessary to debug):

    const courseAndTest = document.getElementById("course_and_test");
if(courseAndTest) {
    //Fetch data
    const student_id = courseAndTest.dataset.studentId;
    fetch(`/student_tests/${student_id}`)
        .then(response => response.json())
        .then(data => {
            if (!data || !data.courses) {
                courseAndTest.innerHTML = "<p>No courses found.</p>";
                return;
            }

            //Make div for each course
            data.courses.forEach(course => {
                let course_nb = 0
                const course_container = document.createElement("div");
                course_container.innerHTML += `<button class="btn btn-primary button-title"><h3>Course ${course_nb += 1}: ${course.course.title}</h3></button>`
                const course_container_2 = document.createElement("div");
                course_container_2.classList.add("toggle-course");
                //Add all lectures of course
                course.lectures.forEach(lecture => {
                    const lecture_container = document.createElement("div");
                    lecture_container.style.overflowX = "auto";
                    lecture_container.innerHTML += `<h4>${lecture.title}</h4>`

                    //create a table with the lecture test score
                    const lecture_table = document.createElement("table");
                    lecture_table.classList.add("lecture-table", "table", "table-hover");
                    //create header for the table
                    lecture_table.innerHTML += `
                    <tr>
                        <th scope="col">Number</th>
                        <th scope="col">Quiz</th>
                        <th scope="col">Score</th>
                    </tr>
                    `
                    lecture_container.appendChild(lecture_table);
                    
                    //Add quize's cell
                    let i = 0
                    lecture.quizes.forEach(quiz => {
                        const tableRow = lecture_table.insertRow();
                        tableRow.insertCell().textContent = i+=1;
                        tableRow.insertCell().textContent = quiz.title;
                        tableRow.insertCell().textContent = quiz.score;
                    });
                    lecture_container.appendChild(lecture_table);
                    course_container_2.appendChild(lecture_container);
                    course_container.appendChild(course_container_2);
                });
                courseAndTest.appendChild(course_container);
            });
        })
        .catch(error => {
            console.error("Error fetching data:", error);
            courseAndTest.innerHTML = "<p>Error loading courses.</p>";
        });

}

Why don’t my angular components realise that it’s part of a module?

Disclaimer: I may be wrong about my understanding of this seeing as I have only been using Angular for little over a year (Angular 16.0.0).

Code

I have this component (SidebarComponent):

@Component({
    selector: 'app-sidebar',
    templateUrl: './sidebar.component.html',
    styleUrls: ['./sidebar.component.scss']
})
export class SidebarComponent implements OnInit {
    ... // Not very relevant to the issue
}

This SidebarComponent is declared as part of a module (ShellModule):

@NgModule({
    declarations: [
        ...,
        SidebarComponent,
        ...
    ],
    imports: [
        CommonModule,
        RouterModule,
        ... // Other necessary modules that are used in the sidebar
        TranslatePipe,
    ],
    exports: [
        ...,
        SidebarComponent,
        ...
    ],
    schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class ShellModule {}

Issue

What I expect here is that the sidebar component can access imports from the module that declares it and that includes exports from RouterModule and TranslatePipe.

Note: The solution to import TranslateModule(.forChild()) doesn’t really work, I tried. Furthermore, I import the pipe only in other projects and it works dandy.

However, The errors i get are the following :

Error: src/app/components/shell/sidebar/sidebar.component.html:51:82 - error NG8004: No pipe found with name 'translate'.

51 {{'sidebar.' + sub_child.title | translate}}

  src/app/components/shell/sidebar/sidebar.component.ts:11:18
    11     templateUrl: './sidebar.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component SidebarComponent.

                 ----------------------------------
Error: src/app/components/shell/sidebar/sidebar.component.html:48:51 - error NG8002: Can't bind to 'routerLinkActiveOptions' since it isn't a known property of 'span'.

48 <span [routerLinkActiveOptions]="{exact: true}" class="sidemenu-link"

  src/app/components/shell/sidebar/sidebar.component.ts:11:18
    11     templateUrl: './sidebar.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component SidebarComponent.

Along with other issues concerning other html tags like, mat-panel-tilte, mat-expansion-panel… Which I’m sure are included in the module’s imports.

The reason why i’m suspicious of the component not realising that it’s a part of a module and has access to its imports and not an issue of paths or architecture is because when I tried to make the component standalone and have the pipe as its import it actually worked.

Conclusion

I want to understand why this and many other (not all) components from the same module don’t realise what is imported in the module and act as if they’ve never seen it. Also, if the standalone solution is actually the better way please let me know why because I’m still learning and would like to be better at this.

How to Avoid ‘unsafe-eval’ in CSP with jQuery AJAX get() and .js.erb in Rails?

I’m working on a Ruby on Rails 7.1 application and encountering an issue with Content Security Policy (CSP). When I make an AJAX request using get() in a .js.erb file, I get the following error in the browser console:

application-8846f773213213213332321321321323.js:83759 U**ncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive:** "script-src 'unsafe-inline' 'nonce-ewqe321PNhjdasdafdse2q3eurY42hk10fVB7en='".

The error occurs in this create.js.erb file:

  get("<%= action_button_index_path(object_type: @object_type, format: :js) %>");

This is my CSP configuration in config/application.rb:

Rails.application.configure do
  config.content_security_policy do |policy|
    policy.default_src :self, :unsafe_inline
    policy.font_src :self, "https://fonts.gstatic.com"
    policy.frame_src :self
    policy.script_src :unsafe_inline
    policy.script_src_elem :self, :unsafe_inline, "https://www.recaptcha.net"
    policy.connect_src :self, "*.nr-data.net"m"
    policy.style_src_elem :self, :unsafe_inline, "https://fonts.googleapis.com", "https://www.gstatic.com"
    policy.img_src :self, :unsafe_inline, "data:"
    policy.object_src :none
    policy.base_uri :self
    policy.report_uri "/csp_violation"
  end

  config.content_security_policy_nonce_generator = ->(_request) { SecureRandom.base64(32) }
  config.content_security_policy_nonce_directives = %w[script-src]
  config.content_security_policy_report_only = false
end

I want to avoid adding ‘unsafe-eval’ to my CSP because it weakens security against XSS attacks. How can I refactor my code to load or execute the JavaScript from widget_button_index_path(widget_type: @widget_type, format: :js) without requiring ‘unsafe-eval’? Ideally, I’d like a solution that works with my current setup (Rails, jQuery, and CSP with nonce).

Any suggestions or examples would be greatly appreciated! Thanks!

WebRTC ICE Candidates Not Settling on Receiver Side (React, Socket.io)

I am implementing a video call feature using two separate RTCPeerConnection instances for sending and receiving video. Currently, I have only implemented the sender’s RTC connection, meaning only the receiver can see the sender’s video.

Issue: ICE candidates are received on the receiver’s side but don’t seem to be applied properly. Tracks seem to be received, but no video is displayed.

reciever logs

reciever logs 2

sender logs

webrtc recievr

webrtc sender

function VideoFrameReciever() {
  const { match,  socket } = useAuthStore();
  const remoteVideoRef = useRef();
  const startCall = async () => {
     let candidates= null;
     const sendersPC = new RTCPeerConnection({
         iceServers: [
       { urls: "stun:stun.l.google.com:19302" }, 
       { urls: "stun:global.stun.twilio.com:3478" },
      ],
    });
  socket.on("receive-offer", async ({ sdp, from }) => {
     console.log("offer received");

     await sendersPC.setRemoteDescription(sdp);
     const answer = await sendersPC.createAnswer();
     await sendersPC.setLocalDescription(answer);
     socket.emit("send-answer", {sdp: sendersPC.localDescription,to: match,      
     });

Not able to use the LiveUpdate Capacitor plugin for self hosted services | Capacitor Live Update Plugins

I have a Vue.js-based application and I am using Capacitor to build the mobile app.

The mobile application is working fine as expected but I am facing an issue with using the live-update plugin using self-hosted not capawesome cloud.
I have read the documentation from here

To get the latest version, I have the following file on my self-hosted server

app-versions.php

<?php
header('Access-Control-Allow-Origin: *'); 
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');

$data = [
    ["version" => "8.1.27"],
    ["version" => "8.1.28"],
];
header('Content-type: application/json');
echo json_encode($data);
?>

based on this, I have the following code in my main.js

import { LiveUpdate } from '@capawesome/capacitor-live-update';

const getBundleInfo = async () => {
    try {
        const request = await fetch("https://example.com/app-versions.php", {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
              "Accept": "application/json",  
            }
        })
        const result = await request.json();
        let appVersion = version;
        if (result.length > 0) {
            appVersion = result[result.length - 1].version
            alert("Latest version is: " + appVersion)
        }
        return appVersion;
        
    } catch (error) {
        alert(error)
    }
}

(async () => {
    if (Capacitor.isNativePlatform()) {
        try {
            const result = await LiveUpdate.getCurrentBundle();
            // this result is always {bundleId: null}
        } catch (error) {
            alert(error)
        }

        try {
            const version = await getBundleInfo();
            await LiveUpdate.downloadBundle({
                url: `https://example.com/build-v${version}.zip`,
                bundleId: version,
            });
            await LiveUpdate.ready();
            await LiveUpdate.reload();
        } catch (error) {
            alert(error)
        }
    }
})();

Issues:-

  • The LiveUpdate.getCurrentBundle(); always returns {bundleId: null} for self-hosted.
  • If I call the setBundle() then it always says “LiveUpdate.setBundle() is not implemented on ios”.
    enter image description here
  • It is very difficult to know when should I download the new bundle because the applied bundle is always null.
  • I rely on the exception of the downloadBundle function so when I get the error “Bundle already exists” my further script didn’t execute(i.e ready, reload).

ABCpdf: How to run javascript after PDF-File is opened?

I have a component which generates PDF-File using ABCpdf. In that PDF-File I need a “DateTime Picker” field.
There are JavaScript functions which can be used for this purpose: AFDate_Format, AFDate_FormatEx (ABCpdf Documentation)

Thus, it can be achieved with simple JavaScript Code

getField("MyField").setAction("Format","AFDate_Format(6)");
getField("MyField").setAction("Keystroke", "AFDate_Format(6)");

I know how to add JavaScript events on fields in PDF-File (e.g. on mouse click). And it works. DateTime picker control is applied to the field when I click that control in a PDF-File.

But I need to apply DateTime picker control when PDF-File is opened.

According to PDF ISO (page 109) there is ‘JavaScript Dictionary’ which can be used for this, but it is not clear hot to add it using ABCPdf

How can I execute JavaScript code when PDF-File is loaded?

JS Path or Xpath syntax for dynamic webpage: Extracting tbody information

I am very new to JS,xpath and HTML but im trying to build a web scrubber for data mining purposes.
So far ChatGPT has been great help in getting what i need done but it seems to struggle with JS paths or xpath referencing.

How would i use CSS_SELECTOR to identify this element called LigandMainTable (refer to image) and its data listed within it? I basically want a script that would read the table data, extract the ligand name (first row), chain ID info (second row), ligand formula (third row), then download the .svg file that is linked in the 4th row (which would be the ligand 2D image).

I am not sure how to structure the syntax to properly extract the proper data type i need from these rows. screenshot of the website + html structure
If theres an efficient way to do this using a standard method, that would be greatly appreciated.