Generating the report form sonarqube using gitlab ci getting error

Issue: SonarQube Report Not Generated in GitLab CI

I’m using GitLab CI for code quality checks with SonarQube. My SonarQube instance is running on an EC2 virtual machine, and I’m using the SonarQube CLI to push the code quality reports to SonarQube. However, I’m encountering an issue where the report is not being generated.

GitLab CI Configuration

.gitlab-ci.yml

sonarqube-check:
  stage: analysis
  image:
    name: sonarsource/sonar-scanner-cli:latest
    entrypoint: [""]
  variables:
    SONAR_USER_HOME: "${CI_PROJECT_DIR}/.sonar"
    GIT_DEPTH: "0"
    SONAR_URL: "http://143.127.12.15:9000"
    SONAR_TOKEN: $SONAR_TOKEN
  cache:
    key: php_vendor
    paths:
      - .sonar/cache
  script:
    - sonar-scanner
  artifacts:
    paths:
      - report.json
  allow_failure: true

sonarqube_report_download:
  stage: download
  image:
    name: alpine:latest
  needs: ["sonarqube-check"]
  script:
    - apk update
    - apk add curl
    - mkdir -p Sonar_Report
    - curl -u $SONAR_TOKEN "$SONAR_URL/api/issues/search?projectKeys=phpprojecttest" -o Sonar_Report/report.json
  artifacts:
    paths:
      - Sonar_Report/report.json

This is sonar-properties

sonar.projectKey=phpprojecttest
sonar.projectName=phptest
sonar.sourceEncoding=UTF-8

sonar.host.url=http://143.127.12.75:9000
sonar.login=sqp_fc4da4b3b4a22b221045463956

sonar.sources=.
sonar.exclusions=**/vendor/**

sonar.tests=tests
sonar.test.inclusions=**/*.test.php
sonar.php.coverage.reportPaths=coverage.xml

Here I need to Generate the Sonarqube Report.json or xml file which i need to upload in the defectdojo.

Doctrine Using short namespace alias “App:MyEntity” Problem: Feature deprecated in doctrine/persistence 2.x and is not supported by persistence:3.x

I am updating and developing a CLI function in my sf 6.4 project, and it returns :

In NotSupported.php line 31:
                                                                                                                          
  Context: Using short namespace alias "App:SampleNature" when calling DoctrineORMEntityManager::getRepository          
  Problem: Feature was deprecated in doctrine/persistence 2.x and is not supported by installed doctrine/persistence:3.x  
  Solution: See the doctrine/deprecations logs for new alternative approaches.

Here are command code with line that call entityManager :

<?php

namespace AppCommand;

use AppEntitySampleNature;
…
use DoctrineORMEntityManager;
use DoctrineORMEntityManagerInterface;
…

#[AsCommand(name: 'app:migrate-samples-results')]
class MigrateResultsCommand extends Command
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
        parent::__construct();
    }

    public function getCursorResult(SymfonyStyle $terminal, $fp_recept, $fp_result) {
         … 
         // LINE BELOW THAT MAKE THIS ISSUE
         $nature = $this->entityManager->getRepository('App:SampleNature')->findOneBy($nature_ech);
         …
     }
     …
}

doctrine version :

composer show -i | grep doctrine
You are using the deprecated option "installed". Only installed packages are shown by default now. The --all option can be used to show all packages.
doctrine/annotations                2.0.1   Docblock Annotations Parser
doctrine/cache                      2.2.0   PHP Doctrine Cache library is a popular cache implementation that supports many different drivers such as redis, memcache, apc, mongodb and others.
doctrine/collections                2.2.2   PHP Doctrine Collections library that adds additional functionality on top of PHP arrays.
doctrine/common                     3.4.4   PHP Doctrine Common project is a library that provides additional functionality that other Doctrine projects depend on such as better reflection support, proxie...
doctrine/dbal                       3.9.0   Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.
doctrine/deprecations               1.1.3   A small layer on top of trigger_error(E_USER_DEPRECATED) or PSR-3 logging with options to disable all deprecations or selectively for packages.
doctrine/doctrine-bundle            2.12.0  Symfony DoctrineBundle
doctrine/doctrine-migrations-bundle 3.3.1   Symfony DoctrineMigrationsBundle
doctrine/event-manager              2.0.1   The Doctrine Event Manager is a simple PHP event system that was built to be used with the various Doctrine projects.
doctrine/inflector                  2.0.10  PHP Doctrine Inflector is a small library that can perform string manipulations with regard to upper/lowercase and singular/plural forms of words.
doctrine/instantiator               2.0.0   A small, lightweight utility to instantiate objects in PHP without invoking their constructors
doctrine/lexer                      3.0.1   PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.
doctrine/migrations                 3.8.0   PHP Doctrine Migrations project offer additional functionality on top of the database abstraction layer (DBAL) for versioning your database schema and easily de...
doctrine/orm                        2.19.6  Object-Relational-Mapper for PHP
doctrine/persistence                3.3.3   The Doctrine Persistence project is a set of shared interfaces and functionality that the different Doctrine object mappers share.
doctrine/sql-formatter              1.4.1   a PHP SQL highlighting library
symfony/doctrine-bridge             v6.4.10 Provides integration for Doctrine with various Symfony components
symfony/doctrine-messenger          v6.4.9  Symfony Doctrine Messenger Bridge

is a little bit confuse… if I understand correctly, I have doctrine orm 2.19, but persistence 3.3 !

Where can I find “doctrine/deprecations logs for new alternative approaches” ?

similar to https://github.com/symfony/symfony/issues/50481#issuecomment-1903987846_

Connecting firestore using laravel

i have been trying to connect firestore using laravel 11 but it is not working, i have tried laravel 11,10 and 9 but to no avail. if i run my php artisan serve after creating code to insert into firestore it will show me a blank white screen with no error on my logs please what am i not getting please, below was the guide i used https://medium.com/@moizali1011/mastering-firestore-crud-operations-in-laravel-a-comprehensive-guide-1e4f2f7bb28f

Route::get('/insert', function() {
$flexInterest1 =  app('firebase.firestore')->database()->collection('testingWeb')->newDocument();
$flexInterest1 -> set([
    'active' => false, 
     'paymentID' => $flexInterest1->id(), 
    'status' => 'true',
    'targetTitle' => '-',
]);
echo "<h1>".'inserted'."</h1>";
});

PHP: Update global reference variabele inside function scrope

I’m trying to change a global value that is currently a reference to another value. My current implementation doesn’t work:

$anna = array('Name' => "Anna");
$bella = array('Name' => "Bella");
$girl = &$anna;

function change(){
    global $girl, $bella;
    $girl = &$bella;
    // $girl['Name'] is now 'Bella'
    output_girl(); // This still outputs 'Anna'
}

function output_girl(){
    global $girl;
    echo $girl['Name'];
}

change();

// What do we want to see?
echo $anna['Name']; // Should still be 'Anna'
echo $bella['Name']; // Should still be 'Bella'
echo $girl['Name']; // Should now be 'Bella' (in above example this will still be 'Anna')

Important notes:

  • A workaround with a return value like $girl = &change(); is not a solution to my problem. It’s important that the global $girl is changed before the end of the change() function. (Reason being this is a problem inside a complex project with nested function calls all wanting to use the same global variables.)
  • I am aware a workaround could be coded using the $GLOBALS array. However, I am specifically interested if this problem can be solved using the global keyword as seen in the example code. And if not, to know why this isn’t possible in PHP.
  • Removing the &to make it $girl = $bella is also not a solution. The global $girl object needs to always be a reference to the original arrays defined at the start of the script. We cannot ever make copies / break references.

Question: Is this an impossibility in PHP when I use the global keyword? If so, can someone explain why? If not, can someone explain how to make this work?

Error in MS Excel after filling XLSX form with PhpOfficePhpSpreadsheet

I am using the PhpOfficePhpSpreadsheet package to fill the fields of a SEPA.xlsx form. The fields are filled successfully, but when the filled form is saved to a new file, opening that file in MS Excel results in an error indicating that something is wrong with the file and it attempts to repair it.

Here is short example code:

// Reading the file:
$reader = new PhpOfficePhpSpreadsheetReaderXlsx();
$reader->setReadDataOnly(false);
$this->spreadsheet = $reader->load($this->inputXlsFile);
$this->currentTab = $this->spreadsheet->getSheetByName(self::ORIGINAL_FORM_TAB_NAME);

// Filling cells:
$this->currentTab->getCell(self::B1_PRODUCT_NAME_CELL)->setValue('Product name');

// Saving file:
$writer = new PhpOfficePhpSpreadsheetWriterXlsx($this->spreadsheet);
$writer->setPreCalculateFormulas(false);
$writer->save($this->outputXlsFilePath);

// Closing file:
$this->spreadsheet->disconnectWorksheets();
unset($this->spreadsheet);

I have tried:

  • different settings using reader PhpOfficePhpSpreadsheetReader and writer PhpOfficePhpSpreadsheetWriter
  • using empty strings for cells when data is missing
  • not setting any values for cells when data is missing
  • cloning data into new worksheet and then filling.

The problem/bug: after filling xlsx form and saving it to new file using MS Excel on Mac shows error: “We found a problem with some content in ‘my_file.xlsx’. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes.”.

Expected behavior: the new file opens using MS Excel without errors.

Exception #0 (ReflectionException): Class “Auth” does not exist

i am upgrading magento 2.4.6-p3 to 2.4.7-p2
php version 8.2
on frontend iam facing:

1 exception(s):
Exception #0 (ReflectionException): Class “Auth” does not exist

Exception #0 (ReflectionException): Class “Auth” does not exist

#1 MagentoFrameworkCodeReaderClassReader->getConstructor() called at [vendor/magento/framework/ObjectManager/Definition/Runtime.php:50]
#2 MagentoFrameworkObjectManagerDefinitionRuntime->getParameters() called at [vendor/magento/framework/ObjectManager/Factory/Compiled.php:100]
#3 MagentoFrameworkObjectManagerFactoryCompiled->create() called at [vendor/magento/framework/ObjectManager/ObjectManager.php:73]
#4 MagentoFrameworkObjectManagerObjectManager->get() called at [vendor/magento/module-customer/view/frontend/templates/js/customer-data.phtml:14]
#5 include() called at [vendor/magento/framework/View/TemplateEngine/Php.php:67]
#6 MagentoFrameworkViewTemplateEnginePhp->render() called at [vendor/magento/framework/Interception/Interceptor.php:58]
#7 MagentoFrameworkViewTemplateEnginePhpInterceptor->___callParent() called at [vendor/magento/framework/Interception/Interceptor.php:138]
#8 MagentoFrameworkViewTemplateEnginePhpInterceptor->MagentoFrameworkInterception{closure}() called at [vendor/magento/framework/Interception/Interceptor.php:153]
#9 MagentoFrameworkViewTemplateEnginePhpInterceptor->___callPlugins() called at [generated/code/Magento/Framework/View/TemplateEngine/Php/Interceptor.php:23]
#10 MagentoFrameworkViewTemplateEnginePhpInterceptor->render() called at [vendor/magento/framework/View/Element/Template.php:263]
#11 MagentoFrameworkViewElementTemplate->fetchView() called at [vendor/magento/framework/View/Element/Template.php:293]
#12 MagentoFrameworkViewElementTemplate->_toHtml() called at [vendor/magento/framework/View/Element/AbstractBlock.php:1128]
#13 MagentoFrameworkViewElementAbstractBlock->MagentoFrameworkViewElement{closure}() called at [vendor/magento/framework/View/Element/AbstractBlock.php:1132]
#14 MagentoFrameworkViewElementAbstractBlock->_loadCache() called at [vendor/magento/framework/View/Element/AbstractBlock.php:676]
#15 MagentoFrameworkViewElementAbstractBlock->toHtml() called at [vendor/magento/framework/View/Layout.php:578]
#16 MagentoFrameworkViewLayout->_renderBlock() called at [vendor/magento/framework/View/Layout.php:555]
#17 MagentoFrameworkViewLayout->renderNonCachedElement() called at [vendor/magento/framework/View/Layout.php:510]
#18 MagentoFrameworkViewLayout->renderElement() called at [vendor/magento/framework/View/Layout.php:606]
#19 MagentoFrameworkViewLayout->_renderContainer() called at [vendor/magento/framework/View/Layout.php:557]
#20 MagentoFrameworkViewLayout->renderNonCachedElement() called at [vendor/magento/framework/View/Layout.php:510]
#21 MagentoFrameworkViewLayout->renderElement() called at [vendor/magento/framework/View/Layout.php:606]
#22 MagentoFrameworkViewLayout->_renderContainer() called at [vendor/magento/framework/View/Layout.php:557]
#23 MagentoFrameworkViewLayout->renderNonCachedElement() called at [vendor/magento/framework/View/Layout.php:510]
#24 MagentoFrameworkViewLayout->renderElement() called at [vendor/magento/framework/View/Layout.php:606]
#25 MagentoFrameworkViewLayout->_renderContainer() called at [vendor/magento/framework/View/Layout.php:557]
#26 MagentoFrameworkViewLayout->renderNonCachedElement() called at [vendor/magento/framework/View/Layout.php:510]
#27 MagentoFrameworkViewLayout->renderElement() called at [vendor/magento/framework/View/Layout.php:606]
#28 MagentoFrameworkViewLayout->_renderContainer() called at [vendor/magento/framework/View/Layout.php:557]
#29 MagentoFrameworkViewLayout->renderNonCachedElement() called at [vendor/magento/framework/View/Layout.php:510]
#30 MagentoFrameworkViewLayout->renderElement() called at [vendor/magento/framework/View/Layout.php:606]
#31 MagentoFrameworkViewLayout->_renderContainer() called at [vendor/magento/framework/View/Layout.php:557]
#32 MagentoFrameworkViewLayout->renderNonCachedElement() called at [vendor/magento/framework/View/Layout.php:510]
#33 MagentoFrameworkViewLayout->renderElement() called at [vendor/magento/framework/View/Layout.php:606]
#34 MagentoFrameworkViewLayout->_renderContainer() called at [vendor/magento/framework/View/Layout.php:557]
#35 MagentoFrameworkViewLayout->renderNonCachedElement() called at [vendor/magento/framework/View/Layout.php:510]
#36 MagentoFrameworkViewLayout->renderElement() called at [vendor/magento/framework/View/Layout.php:975]
#37 MagentoFrameworkViewLayout->getOutput() called at [vendor/magento/framework/Interception/Interceptor.php:58]
#38 MagentoFrameworkViewLayoutInterceptor->___callParent() called at [vendor/magento/framework/Interception/Interceptor.php:138]
#39 MagentoFrameworkViewLayoutInterceptor->MagentoFrameworkInterception{closure}() called at [vendor/magento/framework/Interception/Interceptor.php:153]
#40 MagentoFrameworkViewLayoutInterceptor->___callPlugins() called at [generated/code/Magento/Framework/View/Layout/Interceptor.php:41]
#41 MagentoFrameworkViewLayoutInterceptor->getOutput() called at [vendor/magento/framework/View/Result/Page.php:260]
#42 MagentoFrameworkViewResultPage->render() called at [vendor/magento/framework/View/Result/Layout.php:171]
#43 MagentoFrameworkViewResultLayout->renderResult() called at [vendor/magento/framework/Interception/Interceptor.php:58]
#44 MagentoFrameworkViewResultPageInterceptor->___callParent() called at [vendor/magento/framework/Interception/Interceptor.php:138]
#45 MagentoFrameworkViewResultPageInterceptor->MagentoFrameworkInterception{closure}() called at [vendor/magento/framework/Interception/Interceptor.php:153]
#46 MagentoFrameworkViewResultPageInterceptor->___callPlugins() called at [generated/code/Magento/Framework/View/Result/Page/Interceptor.php:32]
#47 MagentoFrameworkViewResultPageInterceptor->renderResult() called at [vendor/magento/framework/App/Http.php:120]
#48 MagentoFrameworkAppHttp->launch() called at [vendor/magento/framework/Interception/Interceptor.php:58]
#49 MagentoFrameworkAppHttpInterceptor->___callParent() called at [vendor/magento/framework/Interception/Interceptor.php:138]
#50 MagentoFrameworkAppHttpInterceptor->MagentoFrameworkInterception{closure}() called at [vendor/magento/module-application-performance-monitor/Plugin/ApplicationPerformanceMonitor.php:38]
#51 MagentoApplicationPerformanceMonitorPluginApplicationPerformanceMonitor->aroundLaunch() called at [vendor/magento/framework/Interception/Interceptor.php:135]
#52 MagentoFrameworkAppHttpInterceptor->MagentoFrameworkInterception{closure}() called at [vendor/magento/framework/Interception/Interceptor.php:153]
#53 MagentoFrameworkAppHttpInterceptor->___callPlugins() called at [generated/code/Magento/Framework/App/Http/Interceptor.php:23]
#54 MagentoFrameworkAppHttpInterceptor->launch() called at [vendor/magento/framework/App/Bootstrap.php:264]
#55 MagentoFrameworkAppBootstrap->run() called at [pub/index.php:30]

i have run all commands
bin/magento s:up; bin/magento s:d:c; bin/magento s:s:d -f; bin/magento c:f
cammands are excuting properly

I want to retrieve and display the data in the modal form after clicking the button

I am coding a project and I am using a modal form for registrations so I now want to display and modify the data in the modal, When I click on the edit button I get the data from the form in the console but I do not cannot display them in modal form.
in the ‘domainedeformation_candidats’ table I record the information with the user ID ($_SESSION[‘user_id’])

Code index.php :

<?php 
session_start(); 
require_once('../session.php');
require_once('../connexion.php');
// header('Content-Type: application/json');
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
?>
<body>
    <!-- Header End -->
    <?php
        // Supposons que $conn est votre objet PDO pour la connexion à la base de données
        $stmt = $conn->prepare("SELECT * FROM DomaineDeFormation_candidats WHERE ID_Candidat = :id_candidat");
        $stmt->bindParam(':id_candidat', $_SESSION['user_id']); // Assurez-vous que l'ID du candidat est disponible
        $stmt->execute();
        $formations = $stmt->fetchAll(PDO::FETCH_ASSOC);
    ?>

    <!-- Diplômes et Formations -->
    <div class="col-md-12 wow mt-2">
        <div class="bg-light rounded p-4">
            <div class="text">
                <div class="row">
                    <?php foreach ($formations as $formation): ?>
                    <div class="col-md-12 mb-3">
                        <div class="row">
                            <div class="col-md-3 espace_bordure">
                                <?= htmlspecialchars($formation['Mois_AnneeDebut']) ?> - <?= htmlspecialchars($formation['Mois_AnneeFin']) ?>
                            </div>
                            <div class="col-md-8 espace_bordure">
                                <?= htmlspecialchars($formation['Diplome']) ?> - <?= htmlspecialchars($formation['DomaineDeFormation']) ?> - <?= htmlspecialchars($formation['Ecole']) ?>
                            </div>
                            <div class="col-md-1">                                                    
                                <a href="#" data-id="<?= htmlspecialchars($formation['ID']) ?>" data-bs-toggle="modal" data-bs-target="#editeformation" onclick="fetchFormationData(this)" style="text-decoration: none;">
                                    <i class="bi bi-pen-fill"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
        
        
    <!-- Modale HTML (structure inchangée) -->
    <div class="modal fade" id="editeformation" tabindex="-1" aria-labelledby="editeformationLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editeformationLabel">Modifier la Formation</h5>
                    <button type="button" class="btn-close" id="formationModal" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="submit_formation.php" method="post">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                    <div class="modal-body">
                        <div id="formation-container" class="">
                            <div class="formation-item mb-3">
                                <div class="row">
                                    <div class="mb-3 col-md-12">
                                        <label for="ecole_1" class="form-label">Établissement</label>
                                        <input type="text" name="ecole[]" id="ecole_1" class="form-control" required>
                                    </div>
                                    <div class="mb-3 col-md-6">
                                        <label for="diplome_1" class="form-label">Diplôme</label>
                                        <input type="text" name="diplome[]" id="diplome_1" class="form-control" required>
                                    </div>
                                    <div class="mb-3 col-md-6">
                                        <label for="domaineDeFormation_1" class="form-label">Domaine de formation</label>
                                        <input type="text" name="domaineDeFormation[]" id="domaineDeFormation_1" class="form-control" required>
                                    </div>
                                    <script>
                                        const htmlContent = `
                                            <div class="mb-3 col-md-6">
                                                <label for="domaineDeFormation_1" class="form-label">Domaine de formation</label>
                                                <input type="text" name="domaineDeFormation[]" id="domaineDeFormation_1" class="form-control" required>
                                            </div>
                                        `;
                                    </script>
                                    <div class="mb-3 col-md-6">
                                        <label for="moisanneedebut_1" class="form-label">Mois et Année de début</label>
                                        <input type="month" name="moisanneedebut[]" id="moisanneedebut_1" class="form-control" required>
                                    </div>
                                    <div class="mb-3 col-md-6">
                                        <label for="moisanneefin_1" class="form-label">Mois et Année de fin</label>
                                        <input type="month" name="moisanneefin[]" id="moisanneefin_1" class="form-control" required>
                                    </div>
                                    <div class="mb-3 col-md-12">
                                        <label for="competences_1" class="form-label">Mes Compétences</label>
                                        <input type="text" name="competences[]" id="competences_1" class="form-control" required>
                                    </div>
                                    <div class="mb-3 col-md-12">
                                        <label for="descriptionPoste_1" class="form-label">Description</label>
                                        <textarea name="descriptionPoste[]" id="descriptionPoste_1" class="form-control" rows="3" required></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-primary" style="border-radius: 18px;">Enregistrer</button>
                    </div>
                </form>
            </div>
        </div>
    </div>


$('#editeformation').on('shown.bs.modal', function () {
    var formationId = $('#editeformation').data('formation-id');
    fetchFormationData(formationId);
});

function fetchFormationData(formationId) {
    console.log('Formation ID: ' + formationId);

    fetch('get_formation_data.php?id=' + formationId)
        .then(response => response.text())
        .then(responseText => {
            console.log('Texte de la réponse:', responseText);
            try {
                var data = JSON.parse(responseText);
                console.log('Données reçues:', data);

                // Mise à jour des champs du formulaire avec les données reçues
                $('#ecole_1').val(data.ecole || '');
                $('#diplome_1').val(data.diplome || '');
                $('#domaineDeFormation_1').val(data.domaineDeFormation || '');
                $('#moisanneedebut_1').val(data.moisanneedebut || '');
                $('#moisanneefin_1').val(data.moisanneefin || '');
                $('#competences_1').val(data.competences || '');
                $('#descriptionPoste_1').val(data.descriptionPoste || '');
                
                console.log('Données reçues - 5 :', data.descriptionPoste);
            } catch (error) {
                console.error('Erreur lors de la conversion en JSON:', error);
                alert('Erreur lors de la récupération des données.');
            }
        })
        .catch(error => {
            console.error('Erreur:', error);
            alert('Erreur lors de la requête : ' + error.message);
        });
}

get_formation_data.php

<?php
require '../connexion.php'; 

if (!isset($_GET['id']) || empty($_GET['id'])) {
    echo json_encode(['error' => 'ID manquant']);
    exit();
}

$id = intval($_GET['id']);

error_log("ID recherché : " . $id);

try {
    $stmt = $conn->prepare('SELECT * FROM domainedeformation_candidats WHERE ID = :id');
    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    $stmt->execute();

    $data = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($data) {
        echo json_encode($data);
    } else {
        echo json_encode(['error' => 'Aucune donnée trouvée']);
    }
} catch (PDOException $e) {
    echo json_encode(['error' => 'Erreur de base de données: ' . $e->getMessage()]);
}
?>

I tried this script to display the data in the Modal form but nothing is displayed however I retrieve it in the console:

function fetchFormationData(element) {
    var formationId = element.getAttribute('data-id');
    console.log('Formation ID: ' + formationId);

    fetch('get_formation_data.php?id=' + formationId)
        .then(response => response.text())
        .then(responseText => {
            console.log('Texte de la réponse:', responseText);
            try {
                var data = JSON.parse(responseText);
                console.log('Données reçues:', data);

                // Test simple : mise à jour des champs avec des valeurs statiques
                document.getElementById('ecole_1').value = data.ecole || 'Valeur par défaut';
                document.getElementById('diplome_1').value = data.diplome || 'Valeur par défaut';
                document.getElementById('domaineDeFormation_1').value = data.domaineDeFormation || 'Valeur par défaut';
                document.getElementById('moisanneedebut_1').value = data.moisanneedebut || '2023-01';
                document.getElementById('moisanneefin_1').value = data.moisanneefin || '2023-12';
                document.getElementById('competences_1').value = data.competences || 'Compétence par défaut';
                document.getElementById('descriptionPoste_1').value = data.descriptionPoste || 'Description par défaut';
                
                console.log('Données ECOLE:', document.getElementById('moisanneefin_1').value);
            } catch (error) {
                console.error('Erreur lors de la conversion en JSON:', error);
            }
        })
        .catch(error => {
            console.error('Erreur:', error);
            alert('Erreur : ' + error.message);
        });
}

Open link on new tab when place order is clicked

I have created a custom payment gaeway where user can place order through whatsapp. When place order is clicked I want to open whatsapp url in the new tab and thank you page in same tab. I am stuck at sending the customer to the whatsapp url and at the same time open thank you page in same tab.

Here is the full code of custom payment gateway:

class WC_Gateway_WhatsApp extends WC_Payment_Gateway
{

    public function __construct()
    {
       //... predefined variables

        add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
    }

    public function init_form_fields()
    {

        $this->form_fields = array(
            //...fields
        );
    }

    public function payment_fields()
    {
        $order_id = absint( get_query_var( 'order-pay' ) );
        $order = wc_get_order( $order_id );

        echo '<p>' . esc_html__($this->description, 'woocommerce') . '</p>';
        ?>
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                const form = $("form.checkout");
                form.submit(function(e) {
                    if (form.find("input[name='payment_method']:checked").val() === "whatsapp") {
                        e.preventDefault();
                        const whatsappUrl = $('#whatsapp-url').data('url');
                        window.open(whatsappUrl, "_blank");
                        form.unbind('submit').submit();
                    }
                });
            });
        </script>
        <?php
    }

    public function process_payment($order_id)
    {
        $order = wc_get_order($order_id);
        $order->set_payment_method($this->id);
        
        $order->save();

        $whatsapp_url = $this->generate_whatsapp_message($order);
        echo '<input type="hidden" id="whatsapp-url" data-url="' . esc_url($whatsapp_url) . '" />';

        return array(
            'result'   => 'success',
            'redirect' => $this->get_return_url($order)
        );
    }

    private function generate_whatsapp_message($order) {
        $customer_name = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
$whatsapp_message = "Order from " . $customer_name . ":n";
        $whatsapp_message .= "Order Id = " . $order_id . "n";        
//...other message
        $whatsapp_number = $this->number;

        $whatsapp_url = 'https://wa.me/' . $whatsapp_number . '?text=' . urlencode($whatsapp_message);
        return $whatsapp_url;
    }
}

Couldn’t install Testlink

Fatal error: Array and string offset access syntax with curly braces
is no longer supported in
D:xampphtdocstestlinkthird_partykintinckintParser.class.php on
line 463

I was trying to install testlink via localhost/testlink and found this error

Laravel: Maatwebsite get the selected row only

Our client has a separate system, they want to import from their system to our system via import.

Example template from their system

enter image description here

Below picture is the feature we develop, where the user will import from their system to our system.

The header input indicates which header will be gonna use after uploading te mplate

Before uploading a template

enter image description here

After uploading a template

enter image description here

As you can see from the picture above, the column headers is the row # 3 because we chose 3 as a header.

Controller

$results = Excel::toArray(new TemplateImportCSV, $data['file']);
$array                                          = [];
$selected_header                                = $data['selected_header'] - 1;
$counter = 0;

foreach($results[0][$selected_header] as $key => $result){
    if($result){
        $object                                 = new stdClass();
        $object->column_header                  = $result;
        $object->column_field                   = strtolower(str_replace(' ', '_', $result));
        $object->selected_accubooks_field       = 0 ;
        $object->new_field                      = false;
        $object->new_field_error                = false;
        $object->added_new_field_name           = '';
        $object->coa_field                      = false;
        $object->coa_field_error                = false;
        $object->name_exists                   = false;
        $object->selected_coa                   = '';

        array_push($array, $object);
    }
}

Import

<?php

namespace AppHttpControllersTemplateCollectionsOthersImports;

// use AppModelsAdjustment;
// use AppModelsAdjustmentCategory;
// use AppModelsEmployee;
// use AppRulesCheckEmployee;
use IlluminateSupportCarbon;
use IlluminateSupportFacadesAuth;
use IlluminateSupportCollection;
use MaatwebsiteExcelConcernsToCollection;
use AppModelsFee;
use IlluminateSupportStr;
use AppModelsChartOfAccount;
use AppModelsProformaEntries;
use AppModelsBilling;
use AppModelsBillingItem;
use AppModelsJournalEntry;
use AppModelsMember;

class TemplateCollectionsOtherImportCSVController implements ToCollection
{
    public function collection(Collection $rows)
    {
       
    }

}

For example: The file that they will import is around 10,000. As I understand from collections, it will get all the rows then convert it to collections

Now, were having a problem because the request will be drop. Is it possible to get only the row selected from the headers without looping all the data?

how to change add to cart behavior in WordPress WooCommerce

I have a WordPress product with the specific product number ‘121’ in WooCommerce. I created the product page using Elementor single product page template. On this page, there are two input fields. What I want to achieve is that when the ‘Add to Cart’ button is clicked, the input from these fields is sent to my API. The page will then wait for the API response, which will trigger a popup displaying the response. Within this popup, there will be a new ‘Add to Cart’ button that functions as the standard add to cart button does.
Image Example

I’ve tried getting help from various AI tools, but they didn’t really solve my problem. I’m not very experienced in this area. I attempted something simple, like hiding the ‘Add to Cart’ button with CSS and showing it in an Elementor popup. It almost worked, but the ‘Add to Cart’ button in the popup isn’t working. My API endpoint is: https://example.com/api.php?id=12&size=38.

HTML Code of each element:
Add to cart button:

<button type="submit" name="add-to-cart" value="121" class="single_add_to_cart_button button alt wp-element-button">Add to cart</button>

Two fields

<input type="text" name="ppom[fields][user_id]" id="user_id" class="form-control text ppom-input ppom-required" placeholder="User ID." autocomplete="off" data-type="text" data-data_name="user_id">

<input type="text" name="ppom[fields][size_id]" id="size_id" class="form-control text ppom-input ppom-required" placeholder="Size ID." autocomplete="off" data-type="text" data-data_name="size_id">

One thing to mention: I have the Code Snippets plugin. If anyone provides me with code, I can easily add it to the plugin, which will make things clearer for both of us.

Any kind of suggestion would be helpful for my progress.

Pimcore 11 PimcoreTinymce with textcolor

i’m using PimcoreTinymce in Pimcore 11 and i need to edit the color of text, when i work with
pimcore_wysiwyg

I try this configuration in config/config.yaml
, but it don’t work:
`pimcore:

documents:
    richtext_editor: tinymce
    tinymce:
        plugins:
            - textcolor
            - colorpicker
        toolbar: 'textcolor | undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image'`

how to make dropdown address in php [closed]

I don’t know how to make the dropdown address what I want to happen in our system is to become a dropdown address

What I want to happen is to add features to our system, we want to have a dropdown address, because that’s what our panel wants, the address should have a dropdown button in the area with a choice.

Sometime this PHP code works and sometime don’t.. why?

I created a Php program in which a user will give his name and phone number and then the program will redirect to another Php file which is a preview page, after submitting it will go to the previous page and if everything is right it will show us ‘batch added successfully”, else it will show “duplicate value not possible”. Now yesterday this program worked, but today it is not working and fun fact, this same problem happened to my friend and i changed from $res = mysqli_query($conn, $sql); to $res = mysqli_query($conn,$sql); and it worked. But today both cases are not working in my program. Note : “phonenumber” is here UNIQUE in my “login” table and I am using XAMPP.

Code for pracaddtudent.php

<?php
include('connect1.php');
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="pracaddstudentsave.php" method="POST">
        <input type="text" name="sname" placeholder="enter student name">
        <input type="text" name="phonenumber" placeholder="enter student phonenumber">

        <input type="submit" name="add" value="Submit">
        <input type="reset" name="reset" value="Reset">
    </form>
    <?php if (isset($_SESSION['add'])) {
    echo $_SESSION['add'];
    unset($_SESSION['add']);
} ?>
</body>
</html>

Code for pracaddstudentsave.php

<?php

include('connect1.php');

$sname = $_POST['sname'];
$phonenumber = $_POST['phonenumber'];



?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <div class="submit-form">
        <form action="" method="post">
          <input type="text" value=<?php echo $sname; ?> name="sname" readonly> 
          <input type="text" value=<?php echo $phonenumber; ?> name="phonenumber" readonly>
       
<input type="submit" name="save_student" value="Submit">
<input type="reset" name="reset" value="Reset">
        </form>
    </div>
</body>
</html>
<?php
    if (isset($_POST['save_student']) && $_POST['sname'] !="" ) {
       
        $sql = "insert into login set 
        sname='$sname',phonenumber='$phonenumber'";
        // $sql = "INSERT INTO login (sname, phonenumber) 
            // VALUES ('$sname', '$phonenumber')";
        $res = mysqli_query($conn,$sql);

        if ($res == true) {
            $_SESSION['add']= "Batch Added Successfully";
            header("Location:pracaddstudent.php");
            
        } else {
            
            $_SESSION['add']="Duplicate Value Not Possible";
            ?>
 <script> location.replace("pracaddstudent.php"); </script> 
            <?php
           echo mysqli_error($conn);
            
      }
}
?>

I tried it several times and most of the time it showed me “Duplicate value not possible” but yesterday same code worked. I was expecting it to work every time just like other web applications do. I also believe that there can be a problem about Session handling.

Laravel Livewire Event Not Received in Component After Pusher Broadcast

livewire=3 laravel =10
I am working on a Laravel project that uses Livewire for real-time messaging, with events being broadcasted via Pusher. The issue I am facing is that the event is recognized by Pusher, but my Livewire component is not receiving the broadcasted event.

Pusher Setup:
I have set up Pusher and can see events being broadcasted successfully in the Pusher dashboard.
The Pusher setup in resources/js/app.js looks like this:

import Echo from "laravel-echo";

import Pusher from "pusher-js";
window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: "pusher",
    key: import.meta.env.VITE_PUSHER_APP_KEY,
    cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? "mt1",
    wsHost: import.meta.env.VITE_PUSHER_HOST
        ? import.meta.env.VITE_PUSHER_HOST
        : `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`,
    wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
    wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
});

and the event from livewire

$members = ConversationMember::where('conversation_id', $this->conversationId)->get();
        foreach ($members as $member) {
            if ($member->user_id != Auth::id()) {
                event(new MessageSent($this->newMessage, Auth::id(), $member->user_id, $this->conversationId));
            }
        }

MessageSent.php

<?php

namespace AppEvents;

use IlluminateBroadcastingChannel;
use IlluminateBroadcastingInteractsWithSockets;
use IlluminateFoundationEventsDispatchable;
use IlluminateQueueSerializesModels;
use IlluminateContractsBroadcastingShouldBroadcastNow;

class MessageSent implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;
    public $user_id;
    public $res_id;
    public $conversation_id;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($message, $user_id, $res_id, $conversation_id)
    {
        $this->message = $message;
        $this->user_id = $user_id;
        $this->res_id = $res_id;
        $this->conversation_id = $conversation_id;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return IlluminateBroadcastingChannel|array
     */
    public function broadcastOn()
    {
        return new Channel("users.{$this->user_id}");
    }

    /**
     * Get the broadcastable data.
     *
     * @return array
     */
    public function broadcastWith()
    {
        return [
            'conversation_id' => $this->conversation_id,
            'user_id' => $this->user_id,
            'message' => $this->message,
            'res_id' => $this->res_id,
        ];
    }
}

the event listener

  public function getListeners()
    {

        return [
            "echo-private:users.{$this->user_id},.App\Events\MessageSent" => 'receiveMessage_e',
            'conversationSelected' => 'loadConversation',
            'conversationStarted' => 'handleConversationStarted',
            'messageReceived' => 'receiveMessage'
        ];
    }

public function receiveMessage_e($event)
{
    dd($event); // This never gets triggered
}

and last the debug console “pusher” pusher

I configured Pusher correctly in app.js and verified that events are being broadcasted successfully to the Pusher dashboard. In my Livewire component, I set up the getListeners method to listen for the MessageSent event using the correct channel and event syntax.

What I Expected:
I expected the Livewire component to receive the broadcasted event and trigger the receiveMessage_e method, which would dump the event data.

What Happened:
The event was successfully broadcasted to Pusher, but the receiveMessage_e method in the Livewire component was never triggered, and the event data was not received in the browser.