Drag and Drop Tree within another tree

Description:
Hello, I am trying to implement a feature where I can make a complete tree dragable into another tree. However, I am facing issues in getting the targetType, betweenItem, and Root when I drop the tree into the target tree.

Steps to Reproduce:
Create two tree structures with multiple nodes.
Make the first tree dragable.
Try to drag the first tree and drop it into the second tree.
Expected Result:
When I drop the first tree into the second tree, I expect to get the targetType, betweenItem, and Root of the second tree so that I can render the new resultant tree accordingly.

Actual Result:
However, I am unable to get the targetType, betweenItem, and Root of the second tree, which makes it difficult for me to render the new resultant tree.

Example Resultant Tree:
Here’s an example of how I would like the new resultant tree to look like:

tree
|_ Item1
|_ Item2
|_Dragged Tree
|__dragged item 1
|__dragged item 2
|__dragged item 3
|_Item3
|_Item4
|_Item5
import {
  UncontrolledTreeEnvironment,
  Tree,
  StaticTreeDataProvider,
} from "react-complex-tree";
import { longTree } from "./data";
import "react-complex-tree/lib/style-modern.css";

export default function App() {
  const [treeData, setTreeData] = useState(longTree.items);
  const [draggedItem, setDraggedItem] = useState(null);
  const [sourceTreeId, setSourceTreeId] = useState(null);
const handleDrop = (e, targetTreeId) => {
    console.log("target treeid e", targetTreeId, draggedItem, sourceTreeId, e);
    console.log("target id", e.target.targetType);
    // if (draggedItem && sourceTreeId !== targetTreeId) {
    //   // Move the dragged item from the source tree to the target tree
    //   const updatedTreeData = { ...treeData };
    //   // Implement logic to update the tree structure
    //   // Example: Remove item from the source tree and add it to the target tree
    //   setTreeData(updatedTreeData);
    // }
  };

  const handleDragStart = (e, item, sourceTreeId) => {
    console.log("drag start", e);
    setDraggedItem(item);
    setSourceTreeId(sourceTreeId);
  };

  const handleDragOver = (e) => {
    e.preventDefault();
    console.log("e target hover", e);
    // Implement logic to handle drag over event
  };

  return (
    <UncontrolledTreeEnvironment
      canDragAndDrop={true}
      canDropOnFolder={true}
      canReorderItems={true}
      dataProvider={
        new StaticTreeDataProvider(longTree.items, (item, data) => ({
          ...item,
          data,
        }))
      }
      getItemTitle={(item) => item.data}
      viewState={{}}
    >
      <div
        style={{
          display: "flex",
          justifyContent: "space-evenly",
          alignItems: "baseline",
          padding: "20px 0",
          flexDirection: "column",
        }}
      >
        <div
          draggable="true"
          // onDragStart={(e) => handleDragStart(e, "Fruit")}
          onDragOver={handleDragOver}
          onDrop={handleDrop}
          style={{
            width: "28%",
            marginTop: "10px",
            backgroundColor: "white",
            order: 0,
          }}
      >
          <span
            draggable="true"
            onDragStart={(e) => handleDragStart(e, "Fruit")}
          >
            ||
          </span>
          <Tree treeId="tree-4" rootItem="Fruit" treeLabel="Tree 1" />
        </div>
        <div
          draggable="true"
          onDragOver={handleDragOver}
          onDrop={handleDrop}
          style={{
            width: "28%",
            marginTop: "10px",
            backgroundColor: "white",
            order: 1,
          }}
        >
          <span
            draggable="true"
            onDragStart={(e) => handleDragStart(e, "Meals")}
          >
            ||
          </span>
          <Tree treeId="tree-5" rootItem="Meals" treeLabel="Tree 2" />
        </div>
        <div
          draggable="true"
          onDragOver={handleDragOver}
          onDrop={handleDrop}
          style={{
            width: "28%",
            marginTop: "10px",
            backgroundColor: "white",
            order: 2,
          }}
        >
          <span
            draggable="true"
            onDragStart={(e) => {
              handleDragStart(e, "Drinks");
            }}
          >
            ||
          </span>
          <Tree treeId="tree-6" rootItem="Drinks" treeLabel="Tree 3" />
        </div>
        <div
          draggable="true"
          onDragOver={handleDragOver}
          onDrop={handleDrop}
          style={{
            width: "28%",
            marginTop: "10px",
            backgroundColor: "white",
            order: 3,
          }}
        >
          <span
            draggable="true"
            onDragStart={(e) => handleDragStart(e, "Desserts")}
          >
            ||
          </span>
          <Tree treeId="tree-7" rootItem="Desserts" treeLabel="Tree 4" />
        </div>
      </div>
    </UncontrolledTreeEnvironment>
  );
}```

What thing I am doing wrong, suggest me any other way to achieve similar functionality

Example Resultant Tree:
Here's an example of how I would like the new resultant tree to look like:

tree
|_ Item1
|_ Item2
|_Dragged Tree
|__dragged item 1
|__dragged item 2
|__dragged item 3
|_Item3
|_Item4
|_Item5

equivalent to JavaScript backtick template literal in PHP?

I think there is no way except adding backtick template literals not only to PHP but all programming languages.
We need to add variables and constants and of course conditions, etc. in the middle of strings in the way JavaScript allows us.
Forget about that crazy and old style:

for vars: $y = "add {$x} to y";

for consts: $y = "add ".x." to y";

for process: $y = "add ".($x>10?100:200)." to y";

and don’t forget to consider having ‘ or ” between our strings!

but in JavaScript in any situation:

y = `add ${x>10?100:200} to y`;

Is there anyone here to suggest PHP team to add this nice backtick behavior to PHP? otherwise I think PHP fans have to go through NodeJS…

Or is there any PHP framework to process exactly JavaScript-like strings with template literals?

Microsoft teams in electron webview [closed]

I am trying to implement a way to add web apps ( through their URL) in a electron application.
I am using webview for displaying the sites. In case of microsoft teams, I get an error message

We’ve run into a server error. Some functions might not work right now but you can continue to use the app.

I also dont get access to the webcam, mic and notification inside the application

I tried looking into the console but it showed no errors from inside the webview. I looked into the teams log ( Ctrl + alt + shift + 1) but didnt find anything to act on.

I see no other mentions of the issue.

Fix wrong Json coming from API in php

I’m getting a data feed which is in JSON format and the only available format. In PHP, I’m using json_decode to decode the JSON, but it was giving me Null.

I don’t have control over the creation of the data.

Below json is:

{ "status": "success" "data": { "message": "Order created successfully", "tracking_no":"TEST12323", "order_reference":"TEST77777", "print":"https://www.example//TEST77777", }, }

ECharts: Trigger an event only when datazoom’s slider drag action ends (left mouse button released)

I want to select two values through the slider of datazoom in my line chart to filter elsewhere. Since filtering after selecting values takes a relatively long time each time, I cannot directly trigger the event through code below

chart.on('datazoom', (params) => {
})

Because it will be executed many times. I want to trigger an event only after the slider is dragged to the end, that is, after the left mouse button is released. How should I implement this? I’ll appreciated much if you could offer any suggestion!

Why does my onClick event fire every time the React component renders? [duplicate]

I have a React function component for a producxt page. I am counting the number of products a user wishes to add to their basket using

const [productAmount, setProductAmount] = useState(1);

Every time a user clicks on the product counter, it updates the value of the productAmount:

  // Update counter
 const incrementAmount = () => {
    setProductAmount(productAmount+1)
  }

  const decrementAmount = () => {
    if (productAmount == 1){
      setProductAmount(1);
    }
    else {
      setProductAmount(productAmount-1);
    }
  }

Users trigger this update using:

<div className='pci' onClick={decrementAmount}>-</div>
<div className='pci' onClick={incrementAmount}>+</div>

This all works fine.

When user wants to add these products to the basket, I want to write this number to localstorage using:

  //Update cart
  const updateCart = () => {
    // Write number of products in cart to local storage
    localStorage.setItem("cartnumber", productAmount);
  }

Users trigger this update using:

<div className='productaddtocart' onClick={updateCart({productAmount})}>Add to cart</div>

My problem is that the localstorage is updated, I assume via the updateCart function, every time I click on

<div className='pci' onClick={decrementAmount}>-</div>
<div className='pci' onClick={incrementAmount}>+</div>

Why is this happening and how do I get the localstorage to update ony after a user clicks on the “Add to Cart” CTA?

See above for details

How to Conditionally Add an objectin an array in Typescript

I am getting a type error in <RenderFormFields formFields={formFieldsData} /> that:-

Types of property 'type' are incompatible. Type 'string' is not assignable to type '"select"'.ts(2322) RenderFormFields.tsx(17, 3): The expected type comes from property 'formFields' which is declared here on type 'IntrinsicAttributes & RenderFormFieldsProps'

Interestingly, when I remove the conditional insertion part from the array, this type error vanishes !

import RenderFormFields from '@common/RenderFormFields';
import {
  BlockSeparator, PrimaryButton,
  PrimaryInput, PrimarySelect,
} from '@paf-ui-components-library';
import { IProps } from '@paf-ui-components-library/PrimaryInput';
import React from 'react';

import AnnualRevenueField from './AnnualRevenueField';
import BranchLocationsField from './BranchLocationsField';
import CurrentBankStatementsField from './CurrentBankStatementsField';
import useBusinessInformationForm from './hooks/useBusinessForm';
import MajorCustomersField from './MajorCustomersField';
import MajorSuppliersField from './MajorSuppliersField';
import PrimaryBankField from './PrimaryBankField';
import TradeAreasField from './TradeAreasField';

export const RefactoredBusinessInformationForm: React.FC = () => {
  const {
    annualRevenueTypeOptions,
    appendBranchLocations,
    appendMajorCustomers,
    appendMajorSuppliers,
    appendPrimaryTradeAreas,
    branchLocationFields,
    businessIndustryOptions,
    handleContinue,
    handleSubmit,
    industryType,
    loading,
    majorCustomersFields,
    majorSuppliersFields,
    naicsCodeOptions,
    primaryTradeAreaFields,
    removeBranchLocations,
    removeMajorCustomers,
    removeMajorSuppliers,
    removePrimaryTradeAreas,
    watch,
  } = useBusinessInformationForm();

  const formFieldsData = [
    {
      data: businessIndustryOptions,
      name: 'businessInformation.industryType',
      title: 'Business Industry',
      type: 'select',
    },
// when I remove this conditional insertion, the type error vanishes !
    ...(industryType === 'Other' ? [{ 
      name: 'businessInformation.otherIndustryType',
      title: 'Other Business Industry Type',
      type: 'text',
    }] : [{}]),
    {
      data: naicsCodeOptions,
      name: 'businessInformation.naicsCode',
      title: 'NAICS Code',
      type: 'select',
    },
    {
      info: 'Describe the business revenue generating activity',
      name: 'businessInformation.natureOfBusiness',
      title: 'Nature of Business',
      type: 'textarea',
    },
    {
      info: 'Provide a description of your products and/or services',
      name: 'businessInformation.businessProductsAndServices',
      title: 'Business Products and Services',
      type: 'textarea',
    },
    {
      name: 'businessInformation.numberOfBranches',
      title: 'Number of Branches',
      type: 'number',
      allowedDecimalPlaces: 0,
    },
  ];

  return (
    <>
      <BlockSeparator
        heading="Business Information"
      >

        <RenderFormFields formFields={formFieldsData} />
        <h1>bruh</h1>

        <PrimarySelect
          data={businessIndustryOptions}
          name="businessInformation.industryType"
          title="Business Industry"
        />
        {industryType === 'Other' && (
          <PrimaryInput
            name="businessInformation.otherIndustryType"
            title="Other Business Industry Type"
            type="text"
          />
        )}
        <PrimarySelect
          data={naicsCodeOptions}
          name="businessInformation.naicsCode"
          title="NAICS Code"
        />

        <PrimaryInput
          info="Describe the business revenue generating activity"
          name="businessInformation.natureOfBusiness"
          title="Nature of Business"
          type="textarea"
        />

        <PrimaryInput
          info="Provide a description of your products and/or services"
          name="businessInformation.businessProductsAndServices"
          title="Business Products and Services"
          type="textarea"
        />

        <PrimaryInput
          allowedDecimalPlaces={0}
          name="businessInformation.numberOfBranches"
          title="Number of Branches"
          type="number"
        />

        <BranchLocationsField
          branchLocationFields={branchLocationFields}
          onAdd={appendBranchLocations}
          onRemove={removeBranchLocations}
        />

        <PrimaryInput
          name="businessInformation.noOfEmployees"
          title="Number of Employees"
          type="number"
        />

        <TradeAreasField
          onAdd={appendPrimaryTradeAreas}
          onRemove={removePrimaryTradeAreas}
          primaryTradeAreaFields={primaryTradeAreaFields}
        />

        <MajorCustomersField
          majorCustomersFields={majorCustomersFields}
          onAdd={appendMajorCustomers}
          onRemove={removeMajorCustomers}
        />

        <MajorSuppliersField
          majorSuppliersFields={majorSuppliersFields}
          onAdd={appendMajorSuppliers}
          onRemove={removeMajorSuppliers}
        />

        <PrimaryBankField />

        <CurrentBankStatementsField
          existingDocumentUrl={watch('businessInformation.currentBankStatementsDoc.frontSideUrl')}
        />

        <AnnualRevenueField
          annualRevenueTypeOptions={annualRevenueTypeOptions}
        />
      </BlockSeparator>

      <BlockSeparator>
        <PrimaryButton
          loading={loading}
          onClick={handleSubmit(({ businessInformation }) => (
            handleContinue(businessInformation)
          ))}
          variantsStyle={['primary-button-submit-accent']}
        >
          Continue
        </PrimaryButton>
      </BlockSeparator>
    </>
  );
};

RenderFormFields.tsx

import {
  PrimaryInput, PrimarySelect,
} from '@paf-ui-components-library';
import { IProps as PrimaryInputProps } from '@paf-ui-components-library/PrimaryInput';
import { IProps as PrimarySelectProps } from '@paf-ui-components-library/PrimarySelect';
import React from 'react';

export interface PrimaryInputField extends PrimaryInputProps {
  type: 'text' | 'number' | 'textarea';
}
interface PrimarySelectField extends PrimarySelectProps {
  type: 'select';
}
type FormField = PrimaryInputField | PrimarySelectField;

interface RenderFormFieldsProps {
  formFields: FormField[];
}

const RenderFormFields: React.FC<RenderFormFieldsProps> = ({ formFields }) => (
  <>
    {formFields.map((field) => (
      <React.Fragment key={field.name}>
        {field.type === 'select' && (
          <PrimarySelect data={field.data} name={field.name} title={field.title} />
        )}
        {field.type === 'text' && (
          <PrimaryInput name={field.name} title={field.title} type="text" />
        )}
        {field.type === 'textarea' && (
          <PrimaryInput info={field.info} name={field.name} title={field.title} type="textarea" />
        )}
        {field.type === 'number' && (
          <PrimaryInput
            allowedDecimalPlaces={(field as PrimaryInputField).allowedDecimalPlaces}
            name={field.name}
            title={field.title}
            type="number"
          />
        )}
      </React.Fragment>
    ))}
  </>
);

export default RenderFormFields;

create features like Facebook

My codecan the image follow the link : https://id-id.facebook.com/help/570785306433644/?helpref=hc_fnav

I hope someone can help me solve the problem of the project I am working on. So that I can live my life in peace.If anyone can help I would be very grateful

I’ve tried this in my code :

<h4 class="content-badan" onclick="toggleMenu()">Membuat akun Servaild </h4><img src="../Halaman depan/img/down-arrow.png" style="width: 15px; margin-left:870px; margin-top:-80px;" alt="">
    </div>
    <div class="content-wrap" id="contentMenu">
        <div class="content-menu">
            <div class="content-info">
                <div>
                    <a href="" class="menu-iz">
                        <p>Catatan: Anda harus berusia minimal 13 tahun untuk membuat akun Servaild.</p>
                    </a>
                </div>
            </div>
        </div>

for the full code :html – https://pastebin.com/AyiHi09x
css – https://pastebin.com/HsBfSgP5

Retrieving a link from a database table based on query and embedding it in the form using php, JQuey and js

This code generates the form shown in the following image:

enter image description here

How can I edit this file to achieve my goal?

The User selects FuxNoten in the Help Topic dropdown menu and then adds some title in the betreff field. The function should take this text as parameter and match with the keywords or title column values. If a match is found it should retrieve the link and embed it at the end of the form.

My company uses open source osticket for customer support. osticket allows the user to configure forms for ticket creation manually. Based on the configuration the forms are populated dynamically. There are a couple of files responsible for that. These forms are saved in the database.

Suppose U have created a database table called ost_links with the following fields:

id, keywords, title, link

I want to retrieve the link base on two things:
If the customer selects FuxNoten in the Help Topic dropdown
and the text he enters in the Betreff input field.

This is open.php:

<?php

/*********************************************************************
    open.php

    New tickets handle.

    Peter Rotich <[email protected]>
    Copyright (c)  2006-2013 osTicket
    
Home
Released under the GNU General Public License WITHOUT ANY WARRANTY. See LICENSE.TXT for details. vim: expandtab sw=4 ts=4 sts=4: **********************************************************************/ require('client.inc.php'); define('SOURCE', 'Web'); //Ticket source. $ticket = null; $errors = array(); if ($_POST) { $vars = $_POST; $vars['deptId'] = $vars['emailId'] = 0; //Just Making sure we don't accept crap...only topicId is expected. if ($thisclient) { $vars['uid'] = $thisclient->getId(); } elseif ($cfg->isCaptchaEnabled()) { if (!$_POST['captcha']) $errors['captcha'] = __('Enter text shown on the image'); elseif (strcmp($_SESSION['captcha'], md5(strtoupper($_POST['captcha'])))) $errors['captcha'] = sprintf('%s - %s', __('Invalid'), __('Please try again!')); } $tform = TicketForm::objects()->one()->getForm($vars); $messageField = $tform->getField('message'); $attachments = $messageField->getWidget()->getAttachments(); if (!$errors) { $vars['message'] = $messageField->getClean(); if ($messageField->isAttachmentsEnabled()) $vars['files'] = $attachments->getFiles(); } // Drop the draft.. If there are validation errors, the content // submitted will be displayed back to the user Draft::deleteForNamespace('ticket.client.' . substr(session_id(), -12)); // Anpassung Anfang: Honeypot $hpName = addFunc::getHpInputName(); if (($vars[$hpName] ?? 0) && strlen(trim($vars[$hpName]))) { $errors['err'] = __('Ticket denied by bot detection!'); $ost->logWarning(__('bot detection'), __('Ticket denied by bot detection! (Honeypot)'), false); } // Anpassung Ende: Honeypot //Ticket::create...checks for errors.. if (($ticket = Ticket::create($vars, $errors, SOURCE))) { $msg = __('Support ticket request created'); // Drop session-backed form data unset($_SESSION[':form-data']); //Logged in...simply view the newly created ticket. if ($thisclient && $thisclient->isValid()) { // Regenerate session id $thisclient->regenerateSession(); @header('Location: tickets.php?id=' . $ticket->getId()); } else $ost->getCSRF()->rotate(); } else { $errors['err'] = $errors['err'] ?: sprintf( '%s %s', __('Unable to create a ticket.'), __('Correct any errors below and try again.') ); } } //page $nav->setActiveNav('new'); if ($cfg->isClientLoginRequired()) { if ($cfg->getClientRegistrationMode() == 'disabled') { Http::redirect('view.php'); } elseif (!$thisclient) { require_once 'secure.inc.php'; } elseif ($thisclient->isGuest()) { require_once 'login.php'; exit(); } } require(CLIENTINC_DIR . 'header.inc.php'); if ( $ticket && ( (($topic = $ticket->getTopic()) && ($page = $topic->getPage())) || ($page = $cfg->getThankYouPage()) ) ) { // Thank the user and promise speedy resolution! echo Format::viewableImages( $ticket->replaceVars( $page->getLocalBody() ), ['type' => 'P'] ); } else { require(CLIENTINC_DIR . 'open.inc.php'); } require(CLIENTINC_DIR . 'footer.inc.php'); ?>

And this is the open.inc.php:

<?php
if(!defined('OSTCLIENTINC')) die('Access Denied!');
$info=array();
if($thisclient && $thisclient->isValid()) {
    $info=array('name'=>$thisclient->getName(),
                'email'=>$thisclient->getEmail(),
                'phone'=>$thisclient->getPhoneNumber());
}

$info=($_POST && $errors)?Format::htmlchars($_POST):$info;

$form = null;
if (!$info['topicId']) {
    if (array_key_exists('topicId',$_GET) && preg_match('/^d+$/',$_GET['topicId']) && Topic::lookup($_GET['topicId']))
        $info['topicId'] = intval($_GET['topicId']);
    else
        $info['topicId'] = $cfg->getDefaultTopicId();
}

$forms = array();
if ($info['topicId'] && ($topic=Topic::lookup($info['topicId']))) {
    foreach ($topic->getForms() as $F) {
        if (!$F->hasAnyVisibleFields())
            continue;
        if ($_POST) {
            $F = $F->instanciate();
            $F->isValidForClient();
        }
        $forms[] = $F->getForm();
    }
}

?>
<h1><?php echo __('Open a New Ticket');?></h1>
<p><?php echo __('Please fill in the form below to open a new ticket.');?></p>
<form id="ticketForm" method="post" action="open.php" enctype="multipart/form-data">
  <?php csrf_token(); ?>
  <input type="hidden" name="a" value="open">
  <table width="800" cellpadding="1" cellspacing="0" border="0">
<?php // Anpassung Anfang: Honeypot
/*
    <tbody>
 */
    echo '<tbody class="'.$hpClass.'">';
// Anpassung Ende: Honeypot ?>
<?php
        if (!$thisclient) {
            $uform = UserForm::getUserForm()->getForm($_POST);
            if ($_POST) $uform->isValid();
            $uform->render(array('staff' => false, 'mode' => 'create'));
        }
        else { ?>
            <tr><td colspan="2"><hr /></td></tr>
        <tr><td><?php echo __('Email'); ?>:</td><td><?php
            echo $thisclient->getEmail(); ?></td></tr>
        <tr><td><?php echo __('Client'); ?>:</td><td><?php
            echo Format::htmlchars($thisclient->getName()); ?></td></tr>
        <?php } ?>
<?php // Anpassung Anfang: Honeypot
        echo '<tr><td><input type="text" name="'.$hpName.'"></td></tr>';
// Anpassung Ende: Honeypot ?>
    </tbody>
    <tbody>
<!-- Anpassung Anfang: Design Korrektur
    <tr><td colspan="2"><hr />
        <div class="form-header" style="margin-bottom:0.5em">
        <b><?php echo __('Help Topic'); ?></b>
        </div>
    </td></tr>
-->
    <tr>
        <td colspan="2"><hr></td>
    </tr>
<!-- Anpassung Ende: Design Korrektur -->
    <tr>
        <td colspan="2">
<!-- Anpassung Anfang: Design Korrektur -->
            <label class="required" style="width:160px; float:left;">
                <?php echo __('Help Topic'); ?>:
            </label>
            <div style="padding-top: 3px; width:calc(100% - 165px); float:right;">
                <div style="width: 100%; max-width: 268px; float: left; margin-right: 10px;">
<!-- Anpassung Ende: Design Korrektur -->
            <select id="topicId" name="topicId" onchange="javascript:
                    var data = $(':input[name]', '#dynamic-form').serialize();
                    $.ajax(
                      'ajax.php/form/help-topic/' + this.value,
                      {
                        data: data,
                        dataType: 'json',
                        success: function(json) {
                          $('#dynamic-form').empty().append(json.html);
                          $(document.head).append(json.media);
                        }
                      });">
                <option value="" selected="selected">&mdash; <?php echo __('Select a Help Topic');?> &mdash;</option>
                <?php
                if($topics=Topic::getPublicHelpTopics()) {
                    foreach($topics as $id =>$name) {
                        echo sprintf('<option value="%d" %s>%s</option>',
                                $id, ($info['topicId']==$id)?'selected="selected"':'', $name);
                    }
                } ?>
            </select>
<!-- Anpassung Anfang: Design Korrektur
            <font class="error">*&nbsp;<?php echo $errors['topicId']; ?></font>
-->
        </div>
            <font class="error">*&nbsp;<?php echo $errors['topicId']; ?></font>
    </div>
<!-- Anpassung Ende: Design Korrektur -->
        </td>
    </tr>
    </tbody>
    <tbody id="dynamic-form">
        <?php
        $options = array('mode' => 'create');
        foreach ($forms as $form) {
            include(CLIENTINC_DIR . 'templates/dynamic-form.tmpl.php');
        } ?>
    </tbody>
    <tbody>
    <?php
    if($cfg && $cfg->isCaptchaEnabled() && (!$thisclient || !$thisclient->isValid())) {
        if($_POST && $errors && !$errors['captcha'])
            $errors['captcha']=__('Please re-enter the text again');
        ?>
    <tr class="captchaRow">
<!-- Anpassung Anfang: Design Korrektur - Captcha-Feld
        <td class="required"><?php echo __('CAPTCHA Text');?>:</td>
        <td>
            <span class="captcha"><img src="captcha.php" border="0" align="left"></span>
            &nbsp;&nbsp;
            <input id="captcha" type="text" name="captcha" size="6" autocomplete="off">
            <em><?php echo __('Enter the text shown on the image.');?></em>
            <font class="error">*&nbsp;<?php echo $errors['captcha']; ?></font>
        </td>
-->
        <td colspan="2" class="required" style="padding-top: 10px;">
            <label class="required" style="width:160px; float:left;">
                <?php echo __('CAPTCHA Text');?> <font class="error">*&nbsp;</font>
            </label>
            <div style="padding-top: 3px; width:calc(100% - 165px); float:right;">
                <span class="captcha"><img src="captcha.php" border="0" align="left"></span>
                &nbsp;&nbsp;
                <input id="captcha" type="text" name="captcha" size="6" autocomplete="off" style="float: left; margin-top: 5px;">
                <div class="clear"></div>
                <em><?php echo __('Enter the text shown on the image.');?></em>
                <font class="error"><?php echo $errors['captcha']?'<br>'.$errors['captcha']:''; ?></font>
            </div>
        </td>
<!-- Anpassung Ende: Design Korrektur - Captcha-Feld -->
    </tr>
    <?php
    } ?>
    <tr><td colspan=2>&nbsp;</td></tr>
    </tbody>
  </table>
<hr/>
  <p class="buttons" style="text-align:center;">
        <input type="submit" value="<?php echo __('Create Ticket');?>">
        <input type="reset" name="reset" value="<?php echo __('Reset');?>">
        <input type="button" name="cancel" value="<?php echo __('Cancel'); ?>" onclick="javascript:
            $('.richtext').each(function() {
                var redactor = $(this).data('redactor');
                if (redactor && redactor.opts.draftDelete)
                    redactor.plugin.draft.deleteDraft();
            });
            window.location.href='index.php';">
  </p>
</form>
<!-- Anpassung Anfang: help-topic-drop-down (jsTree) -->
<script type="text/javascript">
$(function() {
    var selector = '*[name="topicId"]';
    var jsTreeOpts = [];
    jsTreeOpts['initId']=<?php echo $info['topicId']?:0;?>;
    jsTreeOpts['initText']='— <?php echo __('Select Help Topic'); ?> —';
    jsTreeOpts['onChange']=function(obj) {
        var data = $(':input[name]', '#dynamic-form').serialize();
        $.ajax('ajax.php/form/help-topic/' + obj.value, {
            data: data,
            dataType: 'json',
            success: function(json) {
              $('#dynamic-form').empty().append(json.html);
              $(document.head).append(json.media);
            }
        });
    };
    jsTreeOpts['elemData'] = <?php
                                $data = Topic::getHelpTopicsTreeData(true);
                                echo Topic::getHelpTopicsTree($data);
                             ?>;
    initJsTreeForElement(selector, jsTreeOpts);
});
</script>
<!-- Anpassung Ende: help-topic-drop-down (jsTree) -->

Get value from iframe in plain javascript [duplicate]

I have this code:

<iframe src="iframe.html"></iframe>

    <script>
        // Get the iframe element
        const iframe = document.getElementsByTagName('iframe')[0];

        // Check if the iframe has loaded
        iframe.onload = function () {
            // Access the iframe's content document
            const iframeDocument = iframe.contentDocument || iframe.contentWindow;

            // Now you can interact with the content
            console.log(iframeDocument);
        };
    </script>

I need write in my console.log content from iframe.

In this moment i have nothing:(

Hoiw can i repair it?

Chart.js chart.update() is not a function

For my project, I am using vue3 and quasar.

I am building a dashboard, and users can select from a date range, and this date range will subsequently update the charts based on the data in that date range.

In the template/html

        <!-- Bar Chart -->
        <div class="col-12 col-md-6 q-my-sm q-gutter-md">
          <canvas id="barChart" ref="barChart" style="height: 350px"></canvas>
        </div>

In the script and setup of the vue file


const barChart = ref(null); // Ref for barChart canvas element

const barCtx = barChart.value.getContext("2d");

        barChart.value = new Chart(barCtx, {
          type: "bar",
          data: barChartData,
          options: {
            indexAxis: "x",
            scales: {
              y: {
                beginAtZero: true,
              },
            },
          },
        });


      for (const category in salesByCategory) {
        barChartData.labels.push(category);
        barChartData.datasets[0].data.push(salesByCategory[category]);
      }

barChart.value.update();

However, from the above snippet, i am getting barChart.value.update() is not a function

From the above, barChart is a ref thus i call it using barChart.value, but barChart.value.update() returns error in console that it is not a function

I want save the userName as unique in db using express and mongoose but it save same userNaame as multiple time in Mongodb

here is user schema

const mongoose = require('mongoose')
const {Schema}= mongoose;

const userSchema= new Schema({
    userName:{
        type:String,
        required :true,
       unique:true
       },
        
    password:{
        type:String,
        required:true},
    role:{
        type:[
            {
                type:String,
                enum:["user","admin"],
                default:["user"]
            }
        ]
    }
},{timestamps:true})

const User= mongoose.model('User',userSchema)
module.exports = User;

i have used unique validation key of mongoose type still problem occur

How to create multiple React useState based on props array

How to create multiple useState based on a array and keep track of changes? Or just pass a single state object to multiple components?

At the bottom of the component I’m trying to create customFilter in a loop based on the options array.

import * as React from 'react';

import TransferList from './TransferList';
import Accordion from '@mui/material/Accordion';
import AccordionSummary from '@mui/material/AccordionSummary';
import AccordionDetails from '@mui/material/AccordionDetails';
import Typography from '@mui/material/Typography';
import ArrowDownwardIcon from '@mui/icons-material/ArrowDownward';

export default function CustomFormatBox() {
  const options = [
    {
      name: 'sample_type_key',
      label: 'Sample Type',
      defaultOperator: 'in',
      valueEditorType: 'multiselect',
      values: [
        { name: '0', label: 'OPTICAL_BLANK_0' },
        { name: '1', label: 'OPTICAL_BLANK_1' },
      ],
    },
    {
      name: 'cuvette_number',
      label: 'Cuvette Number',
      defaultOperator: 'in',
      valueEditorType: 'multiselect',
      values: [
        { name: '0', label: '0' },
        { name: '1', label: '1' },
        { name: '2', label: '2' },
      ],
    },
    {
      name: 'wavelength_key',
      label: 'Wavelength',
      values: [
        { name: '0', label: '340nm' },
        { name: '8', label: '850nm' },
      ],
    },
  ];

  const [filters, setFilters] = React.useState([]);
  const [filters2, setFilters2] = React.useState([]);

  // How to merge multiple state into single object?
  const [allFilters, setAllFilters] = React.useState({
    sample_type_key: [],
    cuvette_number: [],
  });

  const customFilter = (option, right, setRight) => (
    <Accordion>
      <AccordionSummary
        expandIcon={<ArrowDownwardIcon />}
        aria-controls={`panel-${option.label}-content`}
        id={`panel-${option.label}-header`}
      >
        <Typography>{option.label}</Typography>
      </AccordionSummary>
      <AccordionDetails>
        <TransferList option={option} name right={right} setRight={setRight} />
        <table>
          <tbody>
            {right.map((item) => (
              <tr key={item.name}>
                <td>{item.label}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </AccordionDetails>
    </Accordion>
  );

  return (
<>
      {/* Eventually would like to create these filters in a loop based on options array. */}
      {customFilter(options[0], filters, setFilters)}
      {customFilter(options[1], filters2, setFilters2)}

      {/* How to tell setAllFilters to set only in cuvette_number?  */}
      {customFilter(options[1], allFilters['cuvette_number'], () => {
        setAllFilters((state) => ({ ...state, cuvette_number: state }));
      })}
      {/* Do not know how to do the update state part */}
    </>
  );
}

Working Stackblitz: https://stackblitz.com/edit/vite-react-state?file=src%2Fcomponents%2FCustomFormatBox.jsx

OneDrive FilePicker cannot set filter with uppercase

I’m currently working on a project that is using the OneDrive filepicker v7.2

I would like to limit the file selection by setting a filter when open up the filepicker. The file extension that I would like to set is .bmp, .BMP. However, when it is applied, it cannot filter by the uppercase extension.

How can I achieve to filter with uppercase?

var odOptions = {
   clientId: "INSERT-APP-ID-HERE",
   action: "query",
   multiSelect: false,
   advanced: {
      queryParameters: "select=id,name,size,file,folder,photo,@microsoft.graph.downloadUrl",
      filter: ".bpm,.BMP" 
   }
}