0

This is what is used in my plugin. A meta field that allows the user in a page editor to add table rows and three columns. As many rows as needed. The issue I am facing is I add a row, then populate column inputs (table data) with content, and click page update. The table is returned empty. The new dynamic table was saved, but not the content. Entering the content a second time + update returns saved content. I can add 20 rows by clicking the "add row" button, populate all twenty rows with content, and all except the 1st row content is saved. Saving new rows is successful. Saving the 1st or 1st of many rows of content initially fails. My workaround is to add all rows needed 1st, update, then populate the table, and update a second time. But ideally, the save logic should save all new content.

Here's all my code:

    function add_fly_list_travel_meta_box() {
        $pageTemplate = get_page_template_slug(get_the_ID());
        
        if ($pageTemplate == 'page-templates/travel-pdf-template.php') {
            $types = array('travel-questionaire');
            
            foreach ($types as $type) {
                add_meta_box(
                    'fly_list_travel_doc',
                    __('Fly List', 'the-fly-shop'),
                    'fly_list_travel_callback',
                    $type,
                    'normal',
                    'high'
                );
            }
        }
    }
    add_action('add_meta_boxes', 'add_fly_list_travel_meta_box');
    
    function fly_list_travel_callback($post) {
        wp_nonce_field(basename(__FILE__), 'fly_list_travel_nonce');
        
        $content_list = get_post_meta($post->ID, 'table_data_jan', true);
        $content_list = is_array($content_list) ? $content_list : array();
        
        // Get the existing row count
        $row_count = count($content_list);
        
        ob_start();
        ?>
        <h2><strong>January</strong></h2>
        <table id="myTable">
            <tr>
                <th>Fly</th>
                <th>Size</th>
                <th>Pattern</th>
                <th>Actions</th>
            </tr>
            <?php foreach ($content_list as $index => $row) : ?>
                <tr>
                    <td><input type="text" name="column1[]" value="<?php echo esc_attr($row['column1']); ?>" /></td>
                    <td><input type="text" name="column2[]" value="<?php echo esc_attr($row['column2']); ?>" /></td>
                    <td><input type="text" name="column3[]" value="<?php echo esc_attr($row['column3']); ?>" /></td>
                    <td><button class="deleteRow">Delete Row</button></td>
                </tr>
            <?php endforeach; ?>
            <tr class="row-template" style="display: none;">
                <td><input type="text" name="column1[]" /></td>
                <td><input type="text" name="column2[]" /></td>
                <td><input type="text" name="column3[]" /></td>
                <td><button class="deleteRow">Delete Row</button></td>
            </tr>
        </table>
        
        <button id="addRow">Add Row</button>
        
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                // Add row
                document.getElementById('addRow').addEventListener('click', function(e) {
                    e.preventDefault(); // Prevent the default form submission behavior
                    
                    var table = document.getElementById('myTable');
                    var newRow = table.querySelector('.row-template').cloneNode(true);
                    newRow.classList.remove('row-template');
                    newRow.style.display = 'table-row'; // Add this line to ensure the new row is displayed
                    table.querySelector('tbody').appendChild(newRow);
                    
                    // Attach event listener to the new delete button
                    var deleteButton = newRow.querySelector('.deleteRow');
                    deleteButton.addEventListener('click', function(e) {
                        e.preventDefault();
                        var row = deleteButton.closest('tr');
                        row.parentNode.removeChild(row);
                    });
                });
                
                // Delete row
                var deleteButtons = document.querySelectorAll('.deleteRow');
                deleteButtons.forEach(function(button) {
                    button.addEventListener('click', function(e) {
                        e.preventDefault(); // Prevent the default form submission behavior
                        
                        var row = button.closest('tr');
                        row.parentNode.removeChild(row);
                    });
                });
            });
            
            // Remove excess rows added on page update
            window.addEventListener('DOMContentLoaded', function() {
                var table = document.getElementById('myTable');
                var rows = table.querySelectorAll('tbody tr');
                var row_count = <?php echo $row_count; ?>;
                var excess_rows = rows.length - row_count;
                
                if (excess_rows > 0) {
                    for (var i = 0; i < excess_rows; i++) {
                        table.querySelector('tbody').removeChild(rows[row_count]);
                    }
                }
            });
        </script>
        <?php
        echo ob_get_clean();
    }


        function save_tfs_fly_list_travel_doc($post_id) {
        if (!isset($_POST['fly_list_travel_nonce']) || !wp_verify_nonce($_POST['fly_list_travel_nonce'], basename(__FILE__))) {
            return;
        }
        
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }
        
        if (!current_user_can('edit_page', $post_id)) {
            return;
        }
        
        // Check if the page is being updated
        if (isset($_POST['action']) && $_POST['action'] === 'editpost') {
            
            // Check if new row data is provided
            if (isset($_POST['column1']) && isset($_POST['column2']) && isset($_POST['column3'])) {
                $column1 = $_POST['column1'];
                $column2 = $_POST['column2'];
                $column3 = $_POST['column3'];
                
                $content_list = array();
                
                foreach ($column1 as $index => $value) {
                    $row = array(
                        'column1' => sanitize_text_field($value),
                        'column2' => sanitize_text_field($column2[$index]),
                        'column3' => sanitize_text_field($column3[$index])
                    );
                    $content_list[] = $row;
                }
                
                // Update post meta only if there is new row data
                if (!empty($content_list)) {
                    update_post_meta($post_id, 'table_data_jan', $content_list);
                }
            }
        }
    }
    add_action('save_post', 'save_tfs_fly_list_travel_doc');```

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.