Choose the checkboxes you want to include and pass them along as parameters for action execution

Looking for a way to execute a mass delete function on a list of items? Each item is equipped with a checkbox, and there's a designated button to remove all selected items. Sounds like a job for Symfony!

The challenge here lies in the fact that the list with checkboxes populates via AJAX. This means we can't define listeners in the template where the list is created; rather, it needs to be done in the template receiving the AJAX response.

Let me share some snippets of my code:

  • The template generating the list includes:

`

foreach($items as $item){
    echo '<input id="'.$item->getItemID().'" type="checkbox" onClick="[CAN'T REFER TO A FUNCTION IN THE OTHER TEMPLATE]">';
    echo 'and so forth ...';
}`
  • As for the template that receives the list:

`

<div id="itemList">
    [insert AJAX list content here]  
</div>
<input type="button" value="delete all items">`

So, how can this be implemented? How do I set it up so that when the 'delete all items' button is clicked, it triggers a Symfony action while passing an array of selected checkboxes (or equivalent data) as a parameter?

Your help is greatly appreciated!

Answer №1

To start, the initial step is to retrieve the array of checkboxes and send them to Symfony. If you have this snippet of html:

<input id="1" type="checkbox" class="delete">
<input id="2" type="checkbox" class="delete">
<input id="3" type="checkbox" class="delete">
<input id="4" type="checkbox" class="delete">
<input type="submit">

along with the following piece of jquery:

$('input[type=submit]').click(function(){
    var elems = new Array();
    $('.delete:checked').each(function(){
        elems.push($(this).attr('id'));
    });

    $.ajax({
        type: 'POST',
        url: 'url',
        data: {elements_to_delete: elems}});
});

You can refer to this demo on: http://jsfiddle.net/HbkvF/

Next, you would execute a method like executeDeleteBatch() as shown below (not tested):

public function execute(sfWebRequest $request)
{
  $ids = $request->getParameter('elements_to_delete');
  $count = Doctrine_Query::create()
    ->delete()
    ->from('<YOUR CLASS>')
    ->whereIn('id', $ids)
    ->execute();
  }
}

The variable $count will hold the count of items that were successfully deleted.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Do not repeat loading JavaScript files in Partial Views

Within my project, I am facing an issue with a large JavaScript file (over 1 MB) that is utilized across all pages. This file is placed in the _Layout and everything functions correctly. However, the problem arises when trying to update a partial view disp ...

When the user modifies the input, React fails to update the component state

Currently, I am utilizing React in conjunction with express to server-side render the views for my project. However, I have encountered a minor setback. Within one of my components, users are directed after their initial login. Here, they are prompted to ...

An issue has occurred in Angular pipe: TypeError - array.map is not functioning as expected

I encountered the following error: ERROR TypeError: array.map is not a function, while using this angular pipe. Here is the code snippet: export class CharacterWithCommasPipe implements PipeTransform { transform(array) { return array.map(item => ...

The JSON data response is not being properly displayed on the div element

I am having trouble with the success function in my ajax call. The data is processed correctly in the view and the ajax call works fine, but for some reason, the data is not getting appended to the div. Here is my jQuery: $(document).ready(function() { ...

The inline script is deemed non-compliant as it infringes upon the Content Security Policy directive: "script-src 'self'"

My chrome-extension is built using react-create-app. However, I encountered an error when running npm run build in react-create-app: Refused to execute inline script because it violates the following Content Security Policy directive: "script-src &apo ...

When whitespace is entered as the value for an input type=email, the change event does not fire

I'm facing an issue with my 'change' event listener on a type=email input element. It seems that when I enter a couple of space characters into the email field and then click out of the element, the change event fails to trigger. Interestin ...

Experiencing difficulties with iterating through an array using a for loop and handling JSON variables

JS code <?php date_default_timezone_set('America/Los_Angeles'); $date = date('Gi', time()); ?> <script type="text/javascript"> $(function() { $(".show_hide").click( function() { var locTime = <?php echo jso ...

Is it possible to execute JavaScript code (using Node.js) through AppleScript on MAC OS?

After downloading Node.js for MAC OS from this link: http://nodejs.org/download/ (http://nodejs.org/dist/v0.10.29/node-v0.10.29.pkg), I needed to execute a JavaScript on Google Chrome. To do this, I utilized the following AppleScript code: do shell script ...

When employing a string union, property 'X' exhibits incompatibility among its types

In my code, I have two components defined as shown below: const GridCell = <T extends keyof FormValue>( props: GridCellProps<T>, ) => { .... } const GridRow = <T extends keyof FormValue>(props: GridRowProps<T>) => { ... & ...

Deploying a Node.js and Next.js application within a single project

I am working on a NextJS 13 project. Inside the same project, I have a Node project located in a folder named server. When deploying to production, this is how my Dockerfile appears: FROM path-to-node16-runtime:latest COPY node_modules ./node_modules CO ...

Django Query doesn't align

Behold the Django Model I've constructed: class State(models.Model): name = models.CharField(max_length=80,null=False) latitude = models.CharField(max_length=80,null=False) longitude = models.CharField(max_length=80,null=False) def __uni ...

IE8 Failing to Upload Files via Ajax

I encountered an issue while attempting to upload a file using a Javascript function that triggers an Ajax call to a servlet. Surprisingly, the file uploads successfully in Chrome but fails in IE8 (quite the mystery). Initially, I had a file select button ...

Updating another component when an input value changes in React

I am currently learning React and I am facing a challenge in updating a component based on an input value. Previously, I had successfully done this using HTML and vanilla JavaScript. Now, I am trying to achieve the same functionality in React but encounter ...

Design an interactive table featuring rowspan functionality

Working on a project with React and attempting to build a dynamic table. Here is an example of how the table should look: https://i.sstatic.net/oEd7q.png The object being used: [ {category: "Type One", subCategory: "One", val: 1, rowSpan: 4}, {category: ...

"Adding an image to create a border within a dropdown in Bootstrap 4: A step

I have been utilizing Bootstrap 4 navbar to construct my menu. Within my menu, there is a dropdown menu that I am seeking to customize. My goal is to adjust the top border of the dropdown menu so it resembles the design seen in this image. My attempt to i ...

Creating a session using jQuery to maintain user data without having to refresh the entire

Struggling with setting a session using jQuery and AJAX without the need for a page refresh. Currently, I can only set the session by pressing the refresh button, which is less than ideal. My PHP page is separate from my jQuery code, making it challengin ...

I'm having trouble with my TextGeometry not displaying on screen. Can someone help me figure

Here is the code I am using for Three.js: <html> <head> <title>My first Three.js app</title> <style> body { margin: 0; } canvas { width: 100%; height: 100% } </style> ...

angular add to the end the most recent compiled element

Looking to incorporate a custom event into the fullcalendar plugin. eventRender: function(event, eventElement) { scope.tmp = { time: $time, $title: $title, crest: event.clubCrest, statusKey: statusKey }; scope.data ...

Using Typescript to add an element to a specific index in an array

Currently, I am engaged in a project using Angular2 and Firebase. My goal is to consolidate all query results under a single key called this.guestPush. Within my project, there is a multiple select element with different user levels - specifically 4, 6, ...

Having trouble retrieving the JSON response attribute

Upon receiving a JSON response in JavaScript, the structure is as follows: {"opt1":"2.92","opt2":"4.24","opt3":"6.36"}; This is what happens when console.log(data) is implemented with data being the response: success: function(data){ console ...