Set value in datalist

User
Assistant
You can set the value of an “ field based on a selection from the “ in JavaScript. Assuming you have an “ element that uses the “:

### Example:

<input type="text" id="product_input-<?php echo $product->get_id(); ?>" list="product_code-<?php echo $product->get_id(); ?>">

<datalist id="product_code-<?php echo $product->get_id(); ?>">
    <?php 
    if(is_array($p_sku) && count($p_sku) > 0){
        foreach($p_sku as $data){
            echo '<option value="' . htmlspecialchars($data) . '">';
        }
    }
    ?>
</datalist>

<script>
document.addEventListener("DOMContentLoaded", function() {
    let inputField = document.getElementById("product_input-<?php echo $product->get_id(); ?>");

    inputField.addEventListener("input", function() {
        let datalist = document.getElementById("product_code-<?php echo $product->get_id(); ?>");
        let options = datalist.options;
        let found = false;

        for (let i = 0; i < options.length; i++) {
            if (options[i].value === inputField.value) {
                found = true;
                break;
            }
        }

        if (!found) {
            console.log("Invalid selection"); // Handle invalid selection
        }
    });
});
</script>

### Explanation:
1. The “ field is linked to the “ using the `list` attribute.
2. When a user types in the input field, JavaScript checks if the value exists in the “.
3. If the value exists, it allows the input, otherwise, you can handle invalid selections.

Let me know if you need further modifications! πŸš€

User
Assistant
If you want to dynamically set the value of the “ field based on a selection from the “, you can use JavaScript to listen for input changes.

### Updated Code:

<input 
    autocomplete="off" 
    list="product_code-<?php echo $product->get_id(); ?>" 
    class="product_code" 
    name="product_code" 
    value="" 
    style="font-size: 12px;" 
    data-pid="<?php echo $product->get_id(); ?>" 
    placeholder="Enter or select the Product Code">

<datalist id="product_code-<?php echo $product->get_id(); ?>">
    <?php 
    if(is_array($p_sku) && count($p_sku) > 0){
        foreach($p_sku as $data){
            echo '<option value="' . htmlspecialchars($data) . '">';
        }
    }
    ?>
</datalist>

<script>
document.addEventListener("DOMContentLoaded", function() {
    document.querySelectorAll(".product_code").forEach(inputField => {
        inputField.addEventListener("input", function() {
            let datalist = document.getElementById(this.getAttribute("list"));
            let options = datalist.options;
            let isValid = false;

            for (let i = 0; i < options.length; i++) {
                if (options[i].value === this.value) {
                    isValid = true;
                    break;
                }
            }

            if (!isValid) {
                console.log("Invalid selection: " + this.value); // Handle invalid selection
            }
        });
    });
});
</script>

### Explanation:
1. The `input` field has an associated `datalist` for product codes.
2. JavaScript listens for `input` events on all elements with the `.product_code` class.
3. It checks if the input value matches any `option` in the `datalist`.
4. If an invalid value is entered (not present in `datalist`), it logs an error (you can modify this to clear the input or display a message).

Let me know if you need further improvements! πŸš€

User
Fatal error: Uncaught Error: Failed opening required '/home/studcosystems/public_html/fpdf/fpdf.php' (include_path='.:/opt/cpanel/ea-php81/root/usr/share/pear') in /home/studcosystems/public_html/wp-content/themes/StudcoUS/submittest.php:14 Stack trace: #0 /home/studcosystems/public_html/wp-includes/template-loader.php(106): include() #1 /home/studcosystems/public_html/wp-blog-header.php(19): require_once('/home/studcosys…') #2 /home/studcosystems/public_html/index.php(17): require('/home/studcosys…') #3 {main} thrown in /home/studcosystems/public_html/wp-content/themes/StudcoUS/submittest.php on line 14

<style>
@page {
                        margin-left:0px;
                        margin-right:0px;
                        margin-top:0mm;
                        margin-bottom:0mm;                      
                    }
                    table.aaa{ width:100%;margin:0px 10px;}
                    td{width:30%;font-size:14px;}
                    table{padding-top:0px;}

                    html, body, h4, p{
                        font-family: "helvetica";

                    }
            td {
                padding-top: 8px;
                padding-bottom: 0px;
                min-height:12px;
                font-family: "helvetica";

            }
            img{
                width:100%;
                float:left;
            }
            .footer{
                position: absolute;
                bottom: 0;
                width: 100%;
            }
</style>

');
$pdf->WriteHTML('

SUBMITTAL DATE: '.date("F j, Y") .'

General Details
Name: '. $row["your_name"].'
Company: '. $row["your_detail"].'
Number: '. $row["contact_no"].'
Email: '. $row["email"].'

Project Information
Name: '. $row["project_name"].'
Address: '. $row["address"].'

Contractor Details
Company: '. $row["contractor_company"].'
Contact: '. $row["contractor_contactno"].'
Email: '.$row["contractor_email"].'

Architect Details
Company: '. $row["architect_company"].'
Contact: '. $row["architect_contactno"].'
Email: '. $row["architect_email"].'

Distrubutor Details
Company: '. $row["distrubutor_company"].'
Contact: '. $row["distrubutor_contactno"].'
Email: '. $row["distrubutor_email"].'

For Sales Inquiries, please contact Studco Building Systems on 800.675.8023
Studco Building Systems US LLC | 1700 Boulter Industrial Parkway Webster NY 14580 USA | www.studcosystems.com
');

$rand = rand();
$t=time();
$date = date('Y-m-d-H-i-s');
$rand1= rand();
$projectnamenew = str_replace(' ', '-',$row["project_name"]);
$pdf_filename ="Studco_".$projectnamenew."_".$date."_".$rand1.".pdf";

$pdf->Output($pdf_filename, 'F');

$zip = new ZipArchive();

$filename = "./Studco_".$projectnamenew."_".$date."_".$rand1.".zip";

if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
exit("cannot open n");
}

$pdf = new PDFMerger;
$pdf->addPDF($pdf_filename, 'all');

$product_ids = explode(",", $row["product_ids"]);
foreach ($product_ids as $key => $value) {
$variation = wc_get_product( $value );
if (get_post_meta( $value, '_dtp_field', true ) != '') {
$path = explode("wp-content", get_post_meta( $value, '_dtp_field', true ));
$filename_new_pdf = "./wp-content". $path[1];
$pdf->addPDF($filename_new_pdf, 'all');
}
}
//$termspdf = 'https://studcosystems.com/submittal_terms.pdf';
$pdf_finalfilename ="Studco_".$projectnamenew."_".$date."_".$rand1.".pdf";
$pdf->addPDF('submittal_terms.pdf', 'all');
$pdf->merge('file', $pdf_finalfilename);
$zip->addFile($pdf_finalfilename);
$zip->close();
if ($_REQUEST['mail_or_download'] == 'mail') {

$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->IsSMTP();
$mail->IsHTML(true);
$mail->SMTPAuth = true; // enable SMTP authenticatio
$mail->Host = 'mail.kidzcommunity.org';
$mail->Mailer = 'smtp';
$mail->Port = 587;
$mail->Username = "maniple@kidzcommunity.org";
$mail->Password = "L82nK^aq9cC!";
$mail->SetFrom("noreply@studcosystems.com","Studco");
$mail->AddAddress($row["email"],"Studco");
//$mail->FromName = 'Manon Marketing';
$mail->FromName = $c_fname;
//$mail->AddCC('carunwebdeveloper@gmail.com');
$mail->Subject = 'Builder Submission – Studco US';
$mail->Body = 'Submittal Builder Receipt Thanks for using the Studco Submittal builder, your assets are attached to this email';
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);

$mail->addAttachment($filename);
$mail->send();
session_start();
$_SESSION['message'] = 1;
unlink($pdf_filename);
unlink($filename);
header("Location: https://studcosystems.com/submittal-builder/");
}

if ($_REQUEST['mail_or_download'] == 'download') {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filename).'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
ob_clean();
flush();

readfile($filename);
}

unlink($pdf_filename);
unlink($filename);
//header("Location: https://studcosystems.com/submittal-builder/");
//;
//header('Content-Length: ' . filesize($filename));
} catch (Exception $e) {
echo 'No Data Found';
}
} else {
echo "No Record Found";
}
}

?>

Assistant
The fatal error indicates that the script cannot find the required `fpdf.php` file. Specifically:

Fatal error: Uncaught Error: Failed opening required '/home/studcosystems/public_html/fpdf/fpdf.php'

### Possible Reasons:
1. The file **does not exist** at the specified location (`/home/studcosystems/public_html/fpdf/fpdf.php`).
2. Incorrect **file path** in `require_once`.
3. **File permissions** prevent access.

## **Steps to Fix the Issue:**

### **1. Verify the File Path**
Check if the `fpdf.php` file exists at `/home/studcosystems/public_html/fpdf/`. You can do this via:
– **cPanel File Manager**: Navigate to `/home/studcosystems/public_html/fpdf/` and confirm `fpdf.php` exists.
– **SSH/FTP**: Use SSH or an FTP client to check the file location.

If the file is missing, you need to re-download **FPDF** and place it in the correct directory.

### **2. Adjust the `require_once` Path**
The current path:

require_once dirname( dirname( dirname( dirname( __FILE__ ) ) ) ) . '/fpdf/fpdf.php';

is navigating four levels up before looking for `fpdf.php`. To confirm the correct path:

Replace:

require_once dirname( dirname( dirname( dirname( __FILE__ ) ) ) ) . '/fpdf/fpdf.php';

with:

var_dump(dirname(__FILE__)); die();

Run the script and check the output directory. Then, manually adjust the correct path.

For example, if the correct path is `/home/studcosystems/public_html/fpdf/fpdf.php`, use:

require_once '/home/studcosystems/public_html/fpdf/fpdf.php';

Or, if `fpdf` is inside your theme folder:

require_once get_template_directory() . '/fpdf/fpdf.php';

### **3. Check File Permissions**
Ensure that:
– The `fpdf.php` file **exists**.
– The permissions allow PHP to read it. Run:

ls -l /home/studcosystems/public_html/fpdf/

The output should show at least `-rw-r–r–` (644) for `fpdf.php`. If not, change permissions:

chmod 644 /home/studcosystems/public_html/fpdf/fpdf.php

If using FTP, right-click the file and set permissions to **644**.

### **4. Reinstall FPDF**
If the file is missing or corrupted:
1. Download FPDF from [fpdf.org](http://www.fpdf.org/en/download.php).
2. Extract and upload the `fpdf` folder to `/home/studcosystems/public_html/`.
3. Confirm that `fpdf.php` is inside `/home/studcosystems/public_html/fpdf/`.

### **5. Verify PHP Include Path**
Run:

phpinfo();

and check `include_path`. If it's incorrect, update `php.ini`:

include_path = ".:/opt/cpanel/ea-php81/root/usr/share/pear:/home/studcosystems/public_html/"

Then restart Apache:

service apache2 restart

### **Final Fix**
After verifying the correct path, update your `require_once`:

require_once '/home/studcosystems/public_html/fpdf/fpdf.php';

Or, if inside a WordPress theme:

require_once get_template_directory() . '/fpdf/fpdf.php';

Let me know if you need further assistance! πŸš€

User
add Tracking Product SKU field to each variation woocommerce
Assistant
To add a **Tracking Product SKU** field to each variation in WooCommerce, follow these steps:

### **1. Add the Custom Field to Variation Settings**
Add this to your theme's `functions.php` or a custom plugin:

add_action('woocommerce_variation_options_pricing', 'add_tracking_sku_field_to_variations', 10, 3);

function add_tracking_sku_field_to_variations($loop, $variation_data, $variation) {
    // Get existing tracking SKU
    $tracking_sku = get_post_meta($variation->ID, '_tracking_sku', true);

    // Add custom field to variation settings
    woocommerce_wp_text_input(
        array(
            'id' => '_tracking_sku[' . $variation->ID . ']',
            'label' => __('Tracking SKU', 'woocommerce'),
            'placeholder' => 'Enter tracking SKU',
            'value' => $tracking_sku,
            'description' => __('This SKU is for tracking purposes.', 'woocommerce'),
            'desc_tip' => true,
        )
    );
}

### **2. Save the Custom Field When Updating Variations**
Now, save the field data when the variation is updated:

add_action('woocommerce_save_product_variation', 'save_tracking_sku_field', 10, 2);

function save_tracking_sku_field($variation_id, $i) {
    if (isset($_POST['_tracking_sku'][$variation_id])) {
        update_post_meta($variation_id, '_tracking_sku', sanitize_text_field($_POST['_tracking_sku'][$variation_id]));
    }
}

### **3. Display the Tracking SKU on the Frontend (Optional)**
To show the tracking SKU on the **single product page**, add this:

add_action('woocommerce_product_meta_end', 'display_tracking_sku_on_product_page');

function display_tracking_sku_on_product_page() {
    global $product;

    if ($product->is_type('variable')) {
        echo '<p><strong>Tracking SKU:</strong> <span id="tracking-sku-display"></span></p>';

        ?>
        <script>
        jQuery(document).ready(function($) {
            $('input.variation_id').change(function() {
                var variationID = $(this).val();
                var trackingSKU = $('input[name="_tracking_sku[' + variationID + ']"]').val();
                $('#tracking-sku-display').text(trackingSKU ? trackingSKU : 'N/A');
            });
        });
        </script>
        <?php
    }
}

### **4. Retrieve Tracking SKU in Orders (Optional)**
If you want to get the Tracking SKU in WooCommerce orders, use this:

add_action('woocommerce_order_item_meta_end', 'display_tracking_sku_in_order', 10, 3);

function display_tracking_sku_in_order($item_id, $item, $order) {
    if ($item->get_variation_id()) {
        $tracking_sku = get_post_meta($item->get_variation_id(), '_tracking_sku', true);
        if ($tracking_sku) {
            echo '<p><strong>Tracking SKU:</strong> ' . esc_html($tracking_sku) . '</p>';
        }
    }
}

### **Result**
– A new **Tracking SKU** field appears in **each variation** under the product edit page.
– Tracking SKU data is saved for each variation.
– It can be displayed on the **product page** and in **WooCommerce orders**.

Let me know if you need modifications! πŸš€

User
ACF
Assistant
### **Add a "Tracking Product SKU" Field to WooCommerce Variations Using ACF (Advanced Custom Fields)**

If you want to add a **Tracking Product SKU** field to each **WooCommerce product variation** using **Advanced Custom Fields (ACF)**, follow these steps:

## **Step 1: Create a Custom Field Group in ACF**
1. **Go to**: WP Admin β†’ **Custom Fields** β†’ **Add New**.
2. **Field Group Name**: `Variation Fields`
3. **Add a new field**:
– **Field Label**: `Tracking Product SKU`
– **Field Name**: `tracking_product_sku`
– **Field Type**: `Text`
4. **Set the Location Rules**:
– **Show this field group if**: `Post Type` **is equal to** `Product Variation`
5. **Publish** the field group.

## **Step 2: Display the Tracking SKU in the Variation Edit Page**
By default, ACF will now add this field to each variation.

## **Step 3: Display the Tracking SKU on the Frontend**
To show the **Tracking Product SKU** on the single product page when a variation is selected:

### **Add this to Your Theme’s `functions.php`**

add_action('woocommerce_product_meta_end', 'display_tracking_sku_on_product_page');

function display_tracking_sku_on_product_page() {
    global $product;

    if ($product->is_type('variable')) {
        echo '<p><strong>Tracking SKU:</strong> <span id="tracking-sku-display"></span></p>';

        ?>
        <script>
        jQuery(document).ready(function($) {
            $('input.variation_id').change(function() {
                var variationID = $(this).val();
                
                $.ajax({
                    url: '<?php echo admin_url('admin-ajax.php'); ?>',
                    type: 'POST',
                    data: {
                        action: 'get_tracking_sku',
                        variation_id: variationID
                    },
                    success: function(response) {
                        $('#tracking-sku-display').text(response ? response : 'N/A');
                    }
                });
            });
        });
        </script>
        <?php
    }
}

## **Step 4: Create an AJAX Function to Retrieve the Tracking SKU**
Add this in `functions.php`:

add_action('wp_ajax_get_tracking_sku', 'get_tracking_sku');
add_action('wp_ajax_nopriv_get_tracking_sku', 'get_tracking_sku');

function get_tracking_sku() {
    if (isset($_POST['variation_id'])) {
        $variation_id = intval($_POST['variation_id']);
        $tracking_sku = get_field('tracking_product_sku', $variation_id);
        echo esc_html($tracking_sku);
    }
    wp_die();
}

## **Step 5: Display Tracking SKU in WooCommerce Orders**
To show the **Tracking SKU** in order items:

add_action('woocommerce_order_item_meta_end', 'display_tracking_sku_in_order', 10, 3);

function display_tracking_sku_in_order($item_id, $item, $order) {
    if ($item->get_variation_id()) {
        $tracking_sku = get_field('tracking_product_sku', $item->get_variation_id());
        if ($tracking_sku) {
            echo '<p><strong>Tracking SKU:</strong> ' . esc_html($tracking_sku) . '</p>';
        }
    }
}

## **βœ… Final Result**
– **Admin Panel**: A "Tracking Product SKU" field appears for **each variation** in ACF.
– **Product Page**: The **Tracking SKU updates dynamically** when a variation is selected.
– **Orders**: The **Tracking SKU appears in WooCommerce order items**.

Let me know if you need further tweaks! πŸš€

User
Fatal error: Array and string offset access syntax with curly braces is no longer supported in /home/studcosystems/public_html/wp-content/themes/StudcoUS/third_party/vendor/mpdf/mpdf/src/Mpdf.php on line 2238
Assistant
The error:

Fatal error: Array and string offset access syntax with curly braces is no longer supported in /home/studcosystems/public_html/wp-content/themes/StudcoUS/third_party/vendor/mpdf/mpdf/src/Mpdf.php on line 2238

### **Cause of the Error**
– PHP **7.4 and later** **deprecated** the use of curly braces `{}` for accessing array and string offsets.
– From **PHP 8.0 and later**, this syntax **causes a fatal error**.
– The `mpdf` library you are using is **outdated** and still uses `{}` instead of `[]` for array or string offsets.

### **Solution: Upgrade mPDF**
You need to update **mPDF** to the latest version, which supports PHP 8+.

#### **1️⃣ Check Your Current PHP Version**
Run:

php -v

or use this PHP snippet:

<?php phpinfo(); ?>

If you are on PHP **8.0 or later**, you **must** update mPDF.

#### **2️⃣ Update mPDF Using Composer**
If your project uses **Composer**, navigate to your theme's `third_party/vendor/` directory and run:

composer update mpdf/mpdf --with-dependencies

Or, if `mpdf` is missing from `composer.json`, install the latest version:

composer require mpdf/mpdf

This will update mPDF to the latest version, fixing the curly brace issue.

#### **3️⃣ Manually Update mPDF (If Not Using Composer)**
1. **Download the latest mPDF** from [GitHub](https://github.com/mpdf/mpdf) or [Packagist](https://packagist.org/packages/mpdf/mpdf).
2. Extract the contents and replace your existing `third_party/vendor/mpdf/` folder.
3. Ensure that `autoload.php` is still correctly required in your script.

### **Temporary Fix (If You Can't Update)**
If updating is not an option, **manually fix the code**:

1. Open the file:

/home/studcosystems/public_html/wp-content/themes/StudcoUS/third_party/vendor/mpdf/mpdf/src/Mpdf.php

2. Go to line **2238** and find something like:

$var{0} = 'something';

3. Replace `{}` with `[]`:

$var[0] = 'something';

⚠ **Warning:** This is a **temporary fix** and may not work across the entire library. **Updating mPDF is the recommended solution.**

### **Final Check**
After updating or modifying, test if the error is gone:

php -v
php /home/studcosystems/public_html/wp-content/themes/StudcoUS/third_party/vendor/mpdf/mpdf/src/Mpdf.php

Let me know if you need further assistance! πŸš€

User
Download Project
submit below form when click above button
Assistant
You can use JavaScript to trigger form submission when clicking the **"Download Project"** button.

### **Solution:**
Modify your code to include an `id` for the form and use JavaScript to submit it.

<button type="button" class="open-button" id="download-btn">Download Project</button>

<form id="download-form" style="display:inline;" action="<?php echo get_site_url(); ?>/submit-test/" method="POST">
    <div class="col-sm-12 variationbutton" style="padding:30px;"> 
        <input type="hidden" value="'+ res +'" name="id">
        <input type="hidden" value="download" name="mail_or_download"> 
    </div>
</form>

<script>
document.addEventListener("DOMContentLoaded", function() {
    document.getElementById("download-btn").addEventListener("click", function() {
        document.getElementById("download-form").submit();
    });
});
</script>

### **How It Works:**
1. The “ with `id="download-btn"` is clicked.
2. JavaScript listens for the click event and **submits the form** with `id="download-form"`.
3. The form sends data to `submit-test/`.

βœ… **This ensures that clicking the button submits the form properly.** πŸš€

Leave a Comment

Your email address will not be published. Required fields are marked *