问:
send_keys with python-selenium does not work
I've tried everything I can find here. (I have of course tried waiting for the item to be clickable as advised  here ):
I find my item easily, but when I try to click before typing I get an error Message: element click intercepted.
Whatever I do after that, in the screenshots I see that the input box is not active and empty

```<code>    inputbox = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "TextField__input")))
    if inputbox:
            actions = ActionChains(drv)
            drv.save_screenshot('debug_cap_0.png')
            try:
                inputbox.click()
            except:
                driver.execute_script("arguments[0].click()", inputbox)
            time.sleep(1)
            actions.move_to_element(to_element=inputbox).send_keys(mytext).perform()
            inputbox.send_keys(mytext)
            drv.save_screenshot('debug_cap_1.png')
</code>```

Body:
I've tried everything I can find here. (I have of course tried waiting for the item to be clickable as advised  here ):
I find my item easily, but when I try to click before typing I get an error Message: element click intercepted.
Whatever I do after that, in the screenshots I see that the input box is not active and empty

    inputbox = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "TextField__input")))
    if inputbox:
            actions = ActionChains(drv)
            drv.save_screenshot('debug_cap_0.png')
            try:
                inputbox.click()
            except:
                driver.execute_script("arguments[0].click()", inputbox)
            time.sleep(1)
            actions.move_to_element(to_element=inputbox).send_keys(mytext).perform()
            inputbox.send_keys(mytext)
            drv.save_screenshot('debug_cap_1.png')


来源: stackexchange

问:
Nuxt middleware know if $router.push was called with "replace" or not
So I have this component that updates part of its state into query parameters:

```<code>        this.$router.push({
          replace: true,
          path: `${this.$router.currentRoute.path}?${this.stepperParamsToQueryString}`,
        });
</code>```

Besides, I have a middleware that reset a store:

```<code>export default ({ app, from, route }) => {
  app.apolloProvider.defaultClient.resetStore();
};
</code>```

But I don't need this call to be made if replace: true is set in $router.push or if $router.replace is called (doc).

Any chance I can know that the current redirection happens with replace: true or not in the middleware?

For now I using this alternative check which does not exactly the same:

```<code>export default ({ app, from, route }) => {
  if (from.path !== route.path) {
    app.apolloProvider.defaultClient.resetStore();
  }
};
</code>```

Using "nuxt": "^2.15.8".

Thanks for the help

ContentLicense: CC BY-SA 4.0

Body:
So I have this component that updates part of its state into query parameters:

        this.$router.push({
          replace: true,
          path: `${this.$router.currentRoute.path}?${this.stepperParamsToQueryString}`,
        });

Besides, I have a middleware that reset a store:

export default ({ app, from, route }) => {
  app.apolloProvider.defaultClient.resetStore();
};

But I don't need this call to be made if replace: true is set in $router.push or if $router.replace is called (doc).

Any chance I can know that the current redirection happens with replace: true or not in the middleware?

For now I using this alternative check which does not exactly the same:

export default ({ app, from, route }) => {
  if (from.path !== route.path) {
    app.apolloProvider.defaultClient.resetStore();
  }
};

Using "nuxt": "^2.15.8".

Thanks for the help


问:
Server-client for Qt Webassembly
I am working on a robot project.  I developed an interface using Qt and communicated between the device and the interface using tcp socket.  I saw that Qt supports webassembly and I tried to move the project to the web via webassembly, but the tcp connection I have established does not work in this case.  How should I proceed in such a situation?

I want to communicate the device with the qt application that works with webassembly

Title: Server-client for Qt Webassembly


问:
Conda installs old pytorch-lightning on m1 mac
I'm having the same problem as this question: Conda is installing a very old version of pytorch-lightning, however when I tried the solution (create new python 3.9 environment with pytorch lightning) I got the following error:

```<code>PackagesNotFoundError: The following packages are not available from current channels:

  - pytorch-lightning

Current channels:

  - https://repo.anaconda.com/pkgs/main/osx-arm64
  - https://repo.anaconda.com/pkgs/main/noarch
  - https://repo.anaconda.com/pkgs/r/osx-arm64
  - https://repo.anaconda.com/pkgs/r/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.
</code>```

The only reason I can think of is because I'm running on M1

Body:
I'm having the same problem as this question: Conda is installing a very old version of pytorch-lightning, however when I tried the solution (create new python 3.9 environment with pytorch lightning) I got the following error:

PackagesNotFoundError: The following packages are not available from current channels:

  - pytorch-lightning

Current channels:

  - https://repo.anaconda.com/pkgs/main/osx-arm64
  - https://repo.anaconda.com/pkgs/main/noarch
  - https://repo.anaconda.com/pkgs/r/osx-arm64
  - https://repo.anaconda.com/pkgs/r/noarch

To search for alternate channels that may provide the conda package you're
looking for, navigate to

    https://anaconda.org

and use the search bar at the top of the page.

The only reason I can think of is because I'm running on M1


问:
Is there a way `globals` will be in the provider package instead of the consumer?
There is a familiar option in rollup output.globals

assuming the provider package have global variables that look like this:

$myGlobal = {
   parents: class Parents {}
   managers: class Managers {}
}
```
<p>and the consumer imports the classes in this approach:</p>
<pre class="lang-js prettyprint-override"><code>import Parents from "@myglobal/parents";
import Managers from "@myglobal/managers";
</code>```

This is easily can be done from the consumer side using the option output.globals, that will look like that:

output: {
   file: `lib/${outputFileName}.js`,
   format: 'cjs',
   indent: false,
   exports: 'auto',
   globals: {
      '@myglobal/parents': '$myGlobal.parents',
      '@myglobal/managers': '$myGlobal.managers',
   },
},
```

The question is how to achieve it via the provider, not via the consumer?
Thanks.

Body:
There is a familiar option in rollup output.globals

assuming the provider package have global variables that look like this:

$myGlobal = {
   parents: class Parents {}
   managers: class Managers {}
}

and the consumer imports the classes in this approach:

import Parents from "@myglobal/parents";
import Managers from "@myglobal/managers";

This is easily can be done from the consumer side using the option output.globals, that will look like that:

output: {
   file: `lib/${outputFileName}.js`,
   format: 'cjs',
   indent: false,
   exports: 'auto',
   globals: {
      '@myglobal/parents': '$myGlobal.parents',
      '@myglobal/managers': '$myGlobal.managers',
   },
},

The question is how to achieve it via the provider, not via the consumer?
Thanks.


问:
Linking a Google Apps Script to multiple Google Sheets
I have written a little bit of Apps Script code for a spreadsheet that calculates price based on a cost value (and some other things). The script works perfectly for the spreadsheet that it was attached to, but I'd like to use this same code across about forty other spreadsheets. Since the values may change over time, I'd like all of the spreadsheets to reference the same custom function file so that I can make an edit once and affect all of the spreadsheets at the same time.

Is there something blatant that I am missing?

I have tried importing as a Macro but that seems to only show up as an option occasionally. I have also tried deploying my Apps script but cannot seem to be able to reference it in each individual Sheet.


问:
kendo-dropdowntree Angular - Select child node only
I am working an angular view using kendo-dropdowntree, and I want to restrict users from selecting a parent node, i.e. allow child-node/leaf selection only. below is my current implementation.

(close) = $event.preventDefault(); // This prevents dropdown tree from closing.

on value change event, I check if node has some children, then do nothing. if there is no child then select this node and close dropdown. However if user wants to close it by selecting same value, value change event is not fired and user is forced to select a different node.

Alternatively, I tried to select first child of the parent, but updating value is not reflected on the control and continue to show previously selected node.

Solution to any of these problems will help me resolve this issue. I found select event of kendo-dropdowntree in Javascript but there is no such event in Angular.


问:
How to send form data to the server using React and Node JS?
I'm using the redux toolkit to handle a reactjs login form. I receive a 404 server error when I submit the form.
The Login API i created checks if the user exists before returning a 404 error if it doesn't exists.
When I submit the form I get a 404 error and when I console log the data sent, it appears that the form sent no data at all.
I looked at my form code and believe I made a mistake, but I am at a loss.

Here is what my code looks like:

```<code>import React, { useState, useRef } from "react";
import { useForm } from "react-hook-form";
import { useDispatch } from "react-redux";
import { loginFailure, loginStart, loginSuccess } from "../../redux/userSlice";
import axios from 'axios';

const Login = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const dispatch = useDispatch();
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm();
  const form = useRef();

  const onSubmit = async (e) => {
    const LoginData = {
      email: email,
      password: password
    }
    setLoading(true);
    dispatch(loginStart());
    console.log(LoginData)
    axios
      .post(
        `auth/login`,
        LoginData
      )
      .then((res) => {
        setLoading(false);
        dispatch(loginSuccess(res.data));
      })
      .catch((error) => {
        setLoading(false);
      dispatch(loginFailure);
      });
      return false;
  };

  return (
    <div id="app" className="app">
      <div className="login login-v1">
        <div className="login-container">
          <div className="login-body">
            <div className="login-content fs-13px">
              <form
                ref={form}
                onSubmit={handleSubmit(onSubmit)}
                className="form-horizontal"
              >
                <div className="form-floating mb-20px">
                  <input
                    type="email"
                    name="email"
                    className="form-control fs-13px h-45px"
                    id="emailAddress"
                    placeholder="Email Address"
                    onChange={(e) => setEmail(e.target.value)}
                    {...register("email", { required: true })}
                  />
                  {errors.email && (
                    <ul
                      className="parsley-errors-list filled"
                      id="parsley-id-7"
                      aria-hidden="false"
                    >
                      <li className="parsley-required">
                        Email is required.
                      </li>
                    </ul>
                  )}
                  <label
                    htmlFor="emailAddress"
                    className="d-flex align-items-center py-0"
                  >
                    Email Address
                  </label>
                </div>
                <div className="form-floating mb-20px">
                  <input
                    type="password"
                    name="password"
                    className="form-control fs-13px h-45px"
                    id="password"
                    placeholder="Password"
                    onChange={(e) => setPassword(e.target.value)}
                    {...register("password", { required: true })}
                  />
                  {errors.password && (
                    <ul
                      className="parsley-errors-list filled"
                      id="parsley-id-7"
                      aria-hidden="false"
                    >
                      <li className="parsley-required">
                        Email is required.
                      </li>
                    </ul>
                  )}
                  <label
                    htmlFor="password"
                    className="d-flex align-items-center py-0"
                  >
                    Password
                  </label>
                </div>

                <div className="login-buttons">
                  <button
                  type="submit"
                    className="btn h-45px btn-success d-block w-100 btn-lg"

                  >
                  {loading ? "Login in..." : "Log me in"}

                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;

</code>```

Server API:

```<code>exports.login = async (req, res, next) => {
  try {
    const user = await UserModel.findOne({ email: req.body.email });
    if (!user) return next(createError(404, "User not found!"));

    const isCorrect = await bcrypt.compare(req.body.password, user.password);
    if (!isCorrect) return next(createError(400, "Wrong credentials"));

    const token = jwt.sign({ id: user._id }, process.env.JWT);
    const { password, permissions, ...others } = user._doc;
    res
      .cookie("access_token", token, {
        httpOnly: true,
      })
      .status(200)
      .json(others);
  } catch (err) {
    next(err);
  }
};
</code>```

Router:

```<code>const router = require("express").Router();
const authController = require("../controllers/authController")

//SIGN IN
router.post('/login', authController.login)

module.exports = router;
</code>```

Body:
I'm using the redux toolkit to handle a reactjs login form. I receive a 404 server error when I submit the form.
The Login API i created checks if the user exists before returning a 404 error if it doesn't exists.
When I submit the form I get a 404 error and when I console log the data sent, it appears that the form sent no data at all.
I looked at my form code and believe I made a mistake, but I am at a loss.

Here is what my code looks like:

import React, { useState, useRef } from "react";
import { useForm } from "react-hook-form";
import { useDispatch } from "react-redux";
import { loginFailure, loginStart, loginSuccess } from "../../redux/userSlice";
import axios from 'axios';

const Login = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const dispatch = useDispatch();
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm();
  const form = useRef();

  const onSubmit = async (e) => {
    const LoginData = {
      email: email,
      password: password
    }
    setLoading(true);
    dispatch(loginStart());
    console.log(LoginData)
    axios
      .post(
        `auth/login`,
        LoginData
      )
      .then((res) => {
        setLoading(false);
        dispatch(loginSuccess(res.data));
      })
      .catch((error) => {
        setLoading(false);
      dispatch(loginFailure);
      });
      return false;
  };

  return (

              <form
                ref={form}
                onSubmit={handleSubmit(onSubmit)}
                className="form-horizontal"
              >

                  <input
                    type="email"
                    name="email"
                    className="form-control fs-13px h-45px"
                    id="emailAddress"
                    placeholder="Email Address"
                    onChange={(e) => setEmail(e.target.value)}
                    {...register("email", { required: true })}
                  />
                  {errors.email && (

                        Email is required.

                  )}

                    Email Address

                  <input
                    type="password"
                    name="password"
                    className="form-control fs-13px h-45px"
                    id="password"
                    placeholder="Password"
                    onChange={(e) => setPassword(e.target.value)}
                    {...register("password", { required: true })}
                  />
                  {errors.password && (

                        Email is required.

                  )}

                    Password

                  <button
                  type="submit"
                    className="btn h-45px btn-success d-block w-100 btn-lg"

                  >
                  {loading ? "Login in..." : "Log me in"}

                  </button>

              </form>

  );
};

export default Login;

Server API:

exports.login = async (req, res, next) => {
  try {
    const user = await UserModel.findOne({ email: req.body.email });
    if (!user) return next(createError(404, "User not found!"));

    const isCorrect = await bcrypt.compare(req.body.password, user.password);
    if (!isCorrect) return next(createError(400, "Wrong credentials"));

    const token = jwt.sign({ id: user._id }, process.env.JWT);
    const { password, permissions, ...others } = user._doc;
    res
      .cookie("access_token", token, {
        httpOnly: true,
      })
      .status(200)
      .json(others);
  } catch (err) {
    next(err);
  }
};

Router:

const router = require("express").Router();
const authController = require("../controllers/authController")

//SIGN IN
router.post('/login', authController.login)

module.exports = router;


问:
how to handle database connection when using APIRouter in fastapi
I am trying to understand how to properly split bigger application into multiple files.
But I am facing Database related issue when I try to do CRUD operation from a different file than the main

In Main.py I have made the connection to the mongodb like this:

```<code>app = FastAPI()
app.include_router(admin_routes.router)

@app.on_event("startup")
def startup_db_client():
    app.mongodb_client = MongoClient("mongodb://localhost:27017")
    app.database = app.mongodb_client["db"]
    app.Admin = app.database["Admin"]
    print("Connected to the MongoDB database!",app.database)
</code>```

and in my admin_routes.py

```<code>@router.post("/CreateAdmin" , tags=["Admin"])
async def create_admin(data: signup_admin):
    if router.Admin.count_documents({'phone':  data.phone }) :
        return {"message": "Phone Already Exist !"}
    elif router.Admin.count_documents({'username':  data.username }) :
        return {"message": "Username Already Exist !"}
    else:
        mydict = { "phone":data.phone,"username":data.username,"password":data.password }
        x = router.Admin.insert_one(mydict)
        return{"status":"ok","message":"Admin Account Created!"}
</code>```

But I am getting error AttributeError: 'APIRouter' object has no attribute 'Admin' when the I access the endpoint CreateAdmin

Whats the proper way to handle the connection so that database operations are available from the routers ?

Body:
I am trying to understand how to properly split bigger application into multiple files.
But I am facing Database related issue when I try to do CRUD operation from a different file than the main

In Main.py I have made the connection to the mongodb like this:

app = FastAPI()
app.include_router(admin_routes.router)

@app.on_event("startup")
def startup_db_client():
    app.mongodb_client = MongoClient("mongodb://localhost:27017")
    app.database = app.mongodb_client["db"]
    app.Admin = app.database["Admin"]
    print("Connected to the MongoDB database!",app.database)

and in my admin_routes.py

@router.post("/CreateAdmin" , tags=["Admin"])
async def create_admin(data: signup_admin):
    if router.Admin.count_documents({'phone':  data.phone }) :
        return {"message": "Phone Already Exist !"}
    elif router.Admin.count_documents({'username':  data.username }) :
        return {"message": "Username Already Exist !"}
    else:
        mydict = { "phone":data.phone,"username":data.username,"password":data.password }
        x = router.Admin.insert_one(mydict)
        return{"status":"ok","message":"Admin Account Created!"}

But I am getting error AttributeError: 'APIRouter' object has no attribute 'Admin' when the I access the endpoint CreateAdmin

Whats the proper way to handle the connection so that database operations are available from the routers ?


问:
In Ruby, using either HTTParty or the native HTTP Net lib, how do I reuse a TLS session across different requests/clients?
I need a way to extract the TLS session from a request and reuse it on new requests but to a different host/ip. I saw there's the OpenSSL::SSL::SSLContext.new and OpenSSL::SSL::Session.new but I didn't find a way of extracting the session from a request and neither how to start a new one using it.

Thoughts?


问:
Pymongo, sorting data by embedded array value
I am having issues when trying to sort an array of documents contained within a document from my MongoDB. At the moment, the data is displayed in ascending order of game_id, however I want this to be descending order in terms of game_id. I've tried resources online but cannot get any to work and I am not sure why.

Python File:

```<code>@app.route("/api/v1.0/clubs/<int:id>/games", methods=["GET"])
def showClubGames(id):
    pageNum, pageSize = 1,10
    if request.args.get("pn"):
        pageNum = int(request.args.get("pn"))
    if request.args.get("ps"):
        pageSize = int(request.args.get("ps"))
    pageStart = (pageSize * (pageNum-1))
    dataToReturn = []
    status = 0
    #skip(pageStart).limit(pageSize)
    for game in clubs.find({"club_id": id}, {"club_games": 1}):
        dataToReturn.append(game)

    dataToReturn = dataToReturn[0]["club_games"]
    dataToReturn = parseJson(dataToReturn)

    status = 200

    return make_response(jsonify(dataToReturn), status)
</code>```

I have tried using .sort({'club_games.game_id': -1}) but it also returns blank results.

Sample Data set being returned (there is ~1000 of these):

```<code>[
  {
    "_id": {
      "$oid": "637cfc3a747290f9dd0778a4"
    },
    "club_id": 11,
    "game_id": 2225784,
    "hosting": "Home",
    "is_win": 0,
    "opponent_goals": 1,
    "opponent_id": 985,
    "opponent_manager_name": "Sir Alex Ferguson",
    "opponent_position": 1,
    "own_goals": 1,
    "own_manager_name": "Ars\u221a\u00aene Wenger",
    "own_position": 4
  },
</code>```

Any help would be greatly appreciated!

Body:
I am having issues when trying to sort an array of documents contained within a document from my MongoDB. At the moment, the data is displayed in ascending order of game_id, however I want this to be descending order in terms of game_id. I've tried resources online but cannot get any to work and I am not sure why.

Python File:

@app.route("/api/v1.0/clubs/<int:id>/games", methods=["GET"])
def showClubGames(id):
    pageNum, pageSize = 1,10
    if request.args.get("pn"):
        pageNum = int(request.args.get("pn"))
    if request.args.get("ps"):
        pageSize = int(request.args.get("ps"))
    pageStart = (pageSize * (pageNum-1))
    dataToReturn = []
    status = 0
    #skip(pageStart).limit(pageSize)
    for game in clubs.find({"club_id": id}, {"club_games": 1}):
        dataToReturn.append(game)

    dataToReturn = dataToReturn[0]["club_games"]
    dataToReturn = parseJson(dataToReturn)

    status = 200

    return make_response(jsonify(dataToReturn), status)

I have tried using .sort({'club_games.game_id': -1}) but it also returns blank results.

Sample Data set being returned (there is ~1000 of these):

[
  {
    "_id": {
      "$oid": "637cfc3a747290f9dd0778a4"
    },
    "club_id": 11,
    "game_id": 2225784,
    "hosting": "Home",
    "is_win": 0,
    "opponent_goals": 1,
    "opponent_id": 985,
    "opponent_manager_name": "Sir Alex Ferguson",
    "opponent_position": 1,
    "own_goals": 1,
    "own_manager_name": "Ars\u221a\u00aene Wenger",
    "own_position": 4
  },

Any help would be greatly appreciated!


问:
Symfony form, dynamically change form on PRE_SUBMIT - error on validation
I have been trying for some time to modify an entity type form before its validation according to the data of another form.
The idea is that if someone changes the 'state' field, we propose the 'cities' of the 'state' in question.
So I use a PRE_SUBMIT event to modify the field but despite this, I always get an error at validation 'The selected choice is invalid'. Any idea what I'm missing?

My code :

```<code>$frm
->add(
                'villeNaissance',
                EntityType::class,
                [
                    'expanded' => false,
                    'multiple' => false,
                    'class' => Ville::class,
                    'label' => 'Ville de naissance',
                    'choice_label' => 'libLong',
                    'placeholder' => 'Séléctionnez un département',
                    'choices'=>[]
                    /*'query_builder' => static function (EntityRepository $er) {
                        return $er->createQueryBuilder('v')
                            ->where('v.code like :dpt')
                            ->setParameter('dpt', '01___')
                            ->orderBy('v.libLong', 'ASC');
                    },*/
                ]
            )
->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $evt) use ($villeRepo) {
                $dpt = $evt->getData()['departementNaissance'] ?? false;
                if ($dpt) {
                    $villesInDpt = $villeRepo->findByDpt($dpt);
                    //$evt->getForm()->remove('villeNaissance');
                    $evt->getForm()
                        ->add(
                            'villeNaissance',
                            EntityType::class,
                            [
                                'expanded' => false,
                                'multiple' => false,
                                'mapped' => false,
                                'class' => Ville::class,
                                'label' => 'Ville de naissance',
                                'choice_label' => 'libLong',
                                'required' => true,
                                'choices' => $villesInDpt,
                            ]
                        );

                }
            })

</code>```

thx in advance

I tried to start from an empty 'choices' in the form, to delete or simply overwrite the form in question but the result is always the same.

so, i try the solution of @Marleen like that :
i remove the PRE_SUBMIT event on parent form and add that :

```<code>$builder->get('departementNaissance')->addEventListener(FormEvents::POST_SUBMIT,function(FormEvent $evt) use ($villeRepo){
               $dpt = $evt->getForm()->getData();
               $parentForm = $evt->getForm()->getParent();

                $villesInDpt = $villeRepo->findByDpt($dpt->getCode());
                $parentForm->remove('villeNaissance');
                $parentForm
                    ->add(
                        'villeNaissance',
                        EntityType::class,
                        [
                            'expanded' => false,
                            'multiple' => false,
                            'mapped' => false,
                            'class' => Ville::class,
                            'label' => 'Ville de naissance',
                            'choice_label' => 'libLong',
                            'required' => true,
                            'choices' => $villesInDpt,
                        ]
                    );
                //dd($parentForm->get('villeNaissance')->getConfig()->getOption('choices'));
            });
</code>```

I didn't manage to add my new cities to the existing city form (in the example, they just create a new form, they dont modify an existing one), so I tried to delete it and add it again or add it directly from the parent but nothing works for the moment.

PS :
the error dumped :

```<code>DeposerController.php on line 234:
Symfony\Component\Form\FormErrorIterator {#10235 ▼
  -form: Symfony\Component\Form\Form {#2956 ▶}
  -errors: array:1 [▼
    0 => Symfony\Component\Form\FormError {#10438 ▼
      #messageTemplate: "The selected choice is invalid."
      #messageParameters: array:1 [▼
        "{{ value }}" => "02007"
      ]
      #messagePluralization: null
      -message: "The selected choice is invalid."
      -cause: Symfony\Component\Validator\ConstraintViolation {#10350 ▶}
      -origin: Symfony\Component\Form\Form {#4511}
    }
  ]
}
</code>```

to be complete :
here is my FormType :

```<code><?php

namespace App\Form;

use App\Entity\Agorha\ConcoursType;
use App\Entity\Agorha\Departement;
use App\Entity\Agorha\Pays;
use App\Entity\Agorha\Sexe;
use App\Entity\Agorha\Ville;
use App\Entity\Candidature;
use App\Entity\ConcoursTypeEtape;
use App\Entity\EtapeDocumentUploade;
use App\Entity\Identite;
use App\Entity\UploadDocument;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\BirthdayType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\GreaterThan;
use Symfony\Component\Validator\Constraints\LessThan;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class IdentiteType extends CompteCandidatType
{
    private $villeNaissance;
    private $prenom1;
    private $prenom2;
    private $identiteRepo;
    private $identiteId;
    private $identiteSess;
    private $session;
    private $user;

    public function __construct(private RequestStack $requestStack, private EntityManagerInterface $em, Security $security)
    {
        $this->session = $this->requestStack->getSession();
        $this->identiteRepo = $this->em->getRepository(Identite::class);
        $this->identiteSess = $this->session->get('app_deposer_identite');
        $this->user = $security->getUser();
        if (!is_null($this->identiteSess)) {
            $this->identiteId = $this->identiteSess;
        } else {
            $identite = $this->identiteRepo->findLastByUser($this->user);
            if ($identite) {
                $this->identiteId = $identite->getId();
            }
        }
        if ($this->identiteId) {
            $this->villeNaissance = $this->identiteRepo->find($this->identiteId)->getVilleNaissance();
            $identite = $this->identiteRepo->find($this->identiteId);
            $prenoms = $identite->getPrenoms();
            $this->prenom1 = $prenoms[0];
            $this->prenom2 = (array_key_exists(1, $prenoms) ? $prenoms[1] : false);
        }
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $request = $this->requestStack->getCurrentRequest();
        $sess = $request->getSession();
        if ($sess) {
            $candiRepo = $this->em->getRepository(Candidature::class);
            $candi = $candiRepo->find($sess->get('candidature'));
        }
        $etapeTypeRepo = $this->em->getRepository(ConcoursTypeEtape::class);
        $etapeType = $etapeTypeRepo->findOneByTypeAndRoute($this->session->get('typeConcours'), $this->requestStack->getCurrentRequest()->get('_route'));

        //$etape = $etapeTypeRepo->findOneByRoute($request->get('_route'));

        $docToUpRepo = $this->em->getRepository(EtapeDocumentUploade::class);
        if ($etapeType && $candi) {
            $docToUp = $docToUpRepo->findByEtapeAndUploaded($etapeType, $candi);
        } else {
            $docToUp = null;
        }

        $typeRepo = $this->em->getRepository(ConcoursType::class);
        $villeRepo = $this->em->getRepository(Ville::class);
        $type = $typeRepo->find($request->getSession()->get('typeConcours'));
        $now = new \DateTimeImmutable();
        $min = $now->modify("-" . $type->getContraintes()['ageMin'] . " years");
        $max = $now->modify("-" . $type->getContraintes()['ageMax'] . " years");

        $builder
            ->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $evt) use ($villeRepo) {
                $dpt = false;
                $data = $evt->getData() ?? false;

                if ($data) {
                    $dpt = $data->getDepartementNaissance();

                    if ($prenoms = $data->getPrenoms()) {
                        if (count($prenoms) == 1) {
                            $evt->getForm()->remove('nonConcerne');
                            $evt->getForm()->add('nonConcerne', CheckboxType::class, [
                                'label' => 'Non concerné pas un deuxième prénom',
                                'mapped' => false,
                                'attr'=>['checked'=>'checked']
                            ]);
                        }
                    }
                }
                if ($dpt) {
                    $villesInDpt = $villeRepo->findByDpt($dpt->getCode());
                    $evt->getForm()->remove('villeNaissance');
                    $evt->getForm()
                        ->add(
                            'villeNaissance',
                            EntityType::class,
                            [
                                'expanded' => false,
                                'multiple' => false,
                                'mapped' => false,
                                'placeholder' => $this->villeNaissance,
                                'class' => Ville::class,
                                'label' => 'Ville de naissance',
                                'choice_label' => 'libLong',
                                'choices' => $villesInDpt,
                                'required' => true,
                            ]
                        );
                }
            })
            /*->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $evt) use ($villeRepo) {

                $dpt = $evt->getData()->getDepartementNaissance() ?? false;
                if ($dpt) {
                    $villesInDpt = $villeRepo->findByDpt($dpt);
                    //$evt->getForm()->remove('villeNaissance');
                    $evt->getForm()
                        ->add(
                            'villeNaissance',
                            EntityType::class,
                            [
                                'expanded' => false,
                                'multiple' => false,
                                'mapped' => false,
                                'class' => Ville::class,
                                'label' => 'Ville de naissance',
                                'choice_label' => 'libLong',
                                'required' => true,
                                'choices' => $villesInDpt,
                            ]
                        );

                }
                dd($evt);

            })*/
            ->add('nom', TextType::class, [
                'label' => 'Nom de naissance',
                'required' => true,
            ])
            ->add('nomUsage', TextType::class, [
                'label' => 'Nom d\'usage ou matrimonial',
                'required' => false,
            ])
            ->add('nonConcerne', CheckboxType::class, [
                'label' => 'Non concerné pas un deuxième prénom',
                'mapped' => false
            ])
            ->add(
                'prenom1',
                TextType::class,
                [
                    'data' => $this->prenom1,
                    'label' => 'Premier prénom',
                    'required' => true,
                    'constraints' => [
                        new NotBlank([], 'Le premier prénom ne peut être vide'),
                        new Regex('/\d/', 'Your prenom cannot contain a number', null, false)
                    ],
                ]
            )
            ->add(
                'prenom2',
                TextType::class,
                [
                    'label' => 'Deuxième prénom',
                    'data' => $this->prenom2,
                    'constraints' => [
                        new Callback(['callback' => static function (?string $data, ExecutionContextInterface $context) {
                            $form = $context->getRoot();
                            if (!$data && !$form->get('nonConcerne')->getData()) {
                                $context->buildViolation('Merci d\'entrer votre deuxième prénom ou de cocher "Non concerné"')
                                    ->addViolation();
                            }
                        }])
                    ]
                ]
            )
            ->add(
                'sexe',
                EntityType::class,
                [
                    'expanded' => false,
                    'multiple' => false,
                    'class' => Sexe::class,
                    'choice_label' => 'libLong',
                    'required' => true,
                    'label' => 'Sexe',
                    'query_builder' => static function (EntityRepository $er) {
                        return $er->createQueryBuilder('s')
                            ->orderBy('s.libLong', 'ASC');
                    },
                ]
            )
            ->add('villeEtrangerNaissance')
            ->add('codePostalEtrangerNaissance')
            ->add(
                'dateNaissance',
                BirthdayType::class,
                [
                    'attr'=>[
                        'max' => $min->format('Y-12-31'),
                        'min' => $max->format('Y-01-01'),
                    ],
                    'label' => 'Date de naissance',
                    'widget' => 'single_text',
                    'required' => true,
                    'by_reference' => true,
                    'constraints' => [
                        new LessThan("-" . $type->getContraintes()['ageMin'] . " years", null, 'La date de naissance doit être inférieure à ' . $min->format('d/m/Y') . ' ou une dérogation d\'age est obligatoire'),
                        new GreaterThan("-" . $type->getContraintes()['ageMax'] . " years", null, 'La date de naissance doit être supérieure à ' . $max->format('d/m/Y') . ' ou une dérogation d\'age est obligatoire')
                    ]
                ]
            )
            ->add(
                'paysNaissance',
                EntityType::class,
                [
                    'expanded' => false,
                    'multiple' => false,
                    'class' => Pays::class,
                    'label' => 'Pays de naissance',
                    'required' => true,
                    'query_builder' => static function (EntityRepository $er) {
                        return $er->createQueryBuilder('p')
                            ->orderBy("p.libLong", 'desc');
                    },
                ]
            )
            ->add(
                'departementNaissance',
                EntityType::class,
                [
                    'expanded' => false,
                    'multiple' => false,
                    'required' => true,
                    'class' => Departement::class,
                    'choice_value' => function (?Departement $entity) {
                        return $entity ? $entity->getCode() : '';
                    },
                    'placeholder' => 'Séléctionnez un département',
                    'label' => 'Département de naissance',
                    /*'query_builder' => static function (EntityRepository $er) {
                        return $er->createQueryBuilder('d')
                            ->orderBy('d.code', 'ASC');
                    },*/
                ]
            )
            ->add(
                'villeNaissance',
                EntityType::class,
                [
                    'expanded' => false,
                    'multiple' => false,
                    'class' => Ville::class,
                    'label' => 'Ville de naissance',
                    'choice_label' => 'libLong',
                    'placeholder' => 'Séléctionnez un département',
                    'choices'=>[]
                    /*'query_builder' => static function (EntityRepository $er) {
                        return $er->createQueryBuilder('v')
                            ->where('v.code like :dpt')
                            ->setParameter('dpt', '01___')
                            ->orderBy('v.libLong', 'ASC');
                    },*/
                ]
            );

            $builder->get('departementNaissance')->addEventListener(FormEvents::POST_SUBMIT,function(FormEvent $evt) use ($villeRepo){
               $dpt = $evt->getForm()->getData();
               $parentForm = $evt->getForm()->getParent();

                $villesInDpt = $villeRepo->findByDpt($dpt->getCode());
                $parentForm->remove('villeNaissance');
                $parentForm
                    ->add(
                        'villeNaissance',
                        EntityType::class,
                        [
                            'expanded' => false,
                            'multiple' => false,
                            'mapped' => false,
                            'class' => Ville::class,
                            'label' => 'Ville de naissance',
                            'choice_label' => 'libLong',
                            'required' => true,
                            'choices' => $villesInDpt,
                        ]
                    );
                //dd($parentForm->get('villeNaissance')->getConfig()->getOption('choices'));
            });

        $uploadRepo = $this->em->getRepository(UploadDocument::class);
        $docUp = [];
        $docsBDD = $uploadRepo->findByUserAndIfGenerique($this->user);
        /*$docsBDD = $uploadRepo->findBy([
            'candidature' => $candi,
        ]);*/
        foreach ($docsBDD as $docBDD) {
            $docUp[] = 'files_' . $docBDD->getEtapeDocumentUploade()->getDocument()->getLibTechnique();
        }
        $this->doc($docToUp, $builder,$docUp);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Identite::class,
            'csrf_protection' => true,
            'csrf_field_name' => '_token',
            'csrf_token_id' => 'task_item',
        ]);
    }
}

</code>```

here is my controller :

```<code>#[Route('/deposer/reprise/{id}', name: 'app_deposer_reprise')]
    public function reprise(EntityManagerInterface $em, $id): Response
    {
        $candiRepo = $em->getRepository(Candidature::class);
        $candi = $candiRepo->findOneByIdentifiant($id);
        if ($candi) {
            if ($candi->isOwner($this->getUser())) {
                $crsRepo = $em->getRepository(Concours::class);
                $crs = $crsRepo->findOneByTypeAndOpen($candi->getConcoursType()->getId());

                if (!$crs) {
                    $this->request->getSession()->set('preInscription', true);
                }

                $this->request->getSession()->remove('lastRoute');
                $this->request->getSession()->set('typeConcours', $candi->getConcoursType()->getId());
                $this->request->getSession()->set('priseConnaissance', $candi->getPriseConnaissance());
                $this->request->getSession()->set('candidature', $candi->getId());

                $typeEtapeRepo = $em->getRepository(ConcoursTypeEtape::class);

                $candiEtapeRepo = $em->getRepository(CandidatureEtape::class);
                $candiEtape = $candiEtapeRepo->findLastByCandiByOrdre($candi->getId());

                /**
                 * cas du stop d une candidature dès la 1ere etape
                 * et donc pas d etape encore enregistrée en BDD
                 */
                if (!$candiEtape)
                {
                    $fstEtape = $typeEtapeRepo->findFirstByType($candi->getConcoursType()->getId());
                    if (!$fstEtape)
                    {
                        $this->request->getSession()->getFlashBag()->add('error', 'Aucune étape encore configurée pour ce type de recrutement');
                        return $this->redirectToRoute('app_home_index');
                    }
                    return $this->redirectToRoute($fstEtape->getEtape()->getRoute());
                }
                $route = $candiEtape?->getEtape()->getEtape()->getRoute();

                $allEtapeBefore = $typeEtapeRepo->findEnfantByTypeOrdered($candi->getConcoursType(), $candiEtape->getEtape()->getEtape()->getParent(), $candiEtape->getEtape()->getOrdre());
                foreach ($allEtapeBefore as $etapeCandi) {
                    $route = $etapeCandi->getEtape()->getRoute();
                    if (array_key_exists($route, $this->routeEntity)) {
                        $repo = $em->getRepository($this->routeEntity[$route]);
                        $last = $repo->findLastByUser($this->getUser());
                        if ($last) {
                            $this->request->getSession()->set($route, $last->getId());
                        }
                    }
                }

                $sess = $this->request->getSession();
                $sess->set('lastRoute', 'app_deposer_reprise');
                return $this->redirectToRoute($route);
            }
            $this->request->getSession()->getFlashBag()->add('error', 'La candidature recherché ne semble pas vous appartenir');
            return $this->redirectToRoute('app_home_index');
        }
        $this->request->getSession()->getFlashBag()->add('error', 'La candidature recherché ne semble plus exister');
        return $this->redirectToRoute('app_home_index');
    }
</code>```

Here is my twig

```<code>{{ form_start(formIdent, {attr: {novalidate: 'novalidate'}}) }}

        {{ form_row(formIdent._token) }}
        {{ form_row(formIdent.nom,{'attr': {'class': 'fr-input'}}) }}

        {{ form_row(formIdent.prenom1,{'attr': {'class': 'fr-input'}}) }}

        {{ form_row(formIdent.dateNaissance,{'attr': {'class': 'fr-input'}}) }}

        {{ form_row(formIdent.paysNaissance,{'attr': {'class': 'fr-input'}}) }}

        {{ form_row(formIdent.departementNaissance,{'attr': {'class': 'fr-input'}}) }}

        {{ form_row(formIdent.villeNaissance,{'attr': {'class': 'fr-input'}}) }}

        {{ form_row(formIdent.sexe,{'attr': {'class': 'fr-input'}}) }}

        {{ form_row(formIdent.nomUsage,{'attr': {'class': 'fr-input'}}) }}

        {{ form_row(formIdent.prenom2,{'attr': {'class': 'fr-input'}}) }}

        <div class="fr-checkbox-group">
            {{ form_row(formIdent.nonConcerne) }}
        </div>

        <ul class="fr-btns-group--center fr-btns-group--inline">
            <li>
                <button class="fr-btn fr-btn--secondary" type="reset" value="remise à zéro">
                    Annuler
                </button>
            </li>
            <li>
                <button class="fr-btn" type="submit">
                    Suivant
                </button>
            </li>
        </ul>

        {{ form_end(formIdent, {'render_rest': false}) }}

</code>```

and my JS :

```<code>domready(function() {
    const DPT = document.getElementById('identite_departementNaissance')
    DPT.addEventListener('change', e => {
        const selectedDPT = e.currentTarget.value
        const URL = '/api/villes?codePostal=' + selectedDPT + '&o[libLong]=asc'
        console.log('change dpt',selectedDPT)
        xhr.get(URL,true)
            .then(response => {
                if (response['hydra:totalItems']>0)
                {
                    let ville = document.getElementById('identite_villeNaissance')
                    let villes = response['hydra:member']

                    console.log('villes',villes)

                    ville.innerHTML = ''
                    villes.map(v=>{
                        let opt = document.createElement('option')
                        opt.value = v.code
                        opt.innerHTML = v.libLong
                        ville.appendChild(opt)
                    })
                }
            })
    })
})
</code>```

Body:
I have been trying for some time to modify an entity type form before its validation according to the data of another form.
The idea is that if someone changes the 'state' field, we propose the 'cities' of the 'state' in question.
So I use a PRE_SUBMIT event to modify the field but despite this, I always get an error at validation 'The selected choice is invalid'. Any idea what I'm missing?

My code :

$frm
->add(
                'villeNaissance',
                EntityType::class,
                [
                    'expanded' => false,
                    'multiple' => false,
                    'class' => Ville::class,
                    'label' => 'Ville de naissance',
                    'choice_label' => 'libLong',
                    'placeholder' => 'Séléctionnez un département',
                    'choices'=>[]
                    /*'query_builder' => static function (EntityRepository $er) {
                        return $er->createQueryBuilder('v')
                            ->where('v.code like :dpt')
                            ->setParameter('dpt', '01___')
                            ->orderBy('v.libLong', 'ASC');
                    },*/
                ]
            )
->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $evt) use ($villeRepo) {
                $dpt = $evt->getData()['departementNaissance'] ?? false;
                if ($dpt) {
                    $villesInDpt = $villeRepo->findByDpt($dpt);
                    //$evt->getForm()->remove('villeNaissance');
                    $evt->getForm()
                        ->add(
                            'villeNaissance',
                            EntityType::class,
                            [
                                'expanded' => false,
                                'multiple' => false,
                                'mapped' => false,
                                'class' => Ville::class,
                                'label' => 'Ville de naissance',
                                'choice_label' => 'libLong',
                                'required' => true,
                                'choices' => $villesInDpt,
                            ]
                        );

                }
            })

thx in advance

I tried to start from an empty 'choices' in the form, to delete or simply overwrite the form in question but the result is always the same.

so, i try the solution of @Marleen like that :
i remove the PRE_SUBMIT event on parent form and add that :

$builder->get('departementNaissance')->addEventListener(FormEvents::POST_SUBMIT,function(FormEvent $evt) use ($villeRepo){
               $dpt = $evt->getForm()->getData();
               $parentForm = $evt->getForm()->getParent();

                $villesInDpt = $villeRepo->findByDpt($dpt->getCode());
                $parentForm->remove('villeNaissance');
                $parentForm
                    ->add(
                        'villeNaissance',
                        EntityType::class,
                        [
                            'expanded' => false,
                            'multiple' => false,
                            'mapped' => false,
                            'class' => Ville::class,
                            'label' => 'Ville de naissance',
                            'choice_label' => 'libLong',
                            'required' => true,
                            'choices' => $villesInDpt,
                        ]
                    );
                //dd($parentForm->get('villeNaissance')->getConfig()->getOption('choices'));
            });

I didn't manage to add my new cities to the existing city form (in the example, they just create a new form, they dont modify an existing one), so I tried to delete it and add it again or add it directly from the parent but nothing works for the moment.

PS :
the error dumped :

DeposerController.php on line 234:
Symfony\Component\Form\FormErrorIterator {#10235 ▼
  -form: Symfony\Component\Form\Form {#2956 ▶}
  -errors: array:1 [▼
    0 => Symfony\Component\Form\FormError {#10438 ▼
      #messageTemplate: "The selected choice is invalid."
      #messageParameters: array:1 [▼
        "{{ value }}" => "02007"
      ]
      #messagePluralization: null
      -message: "The selected choice is invalid."
      -cause: Symfony\Component\Validator\ConstraintViolation {#10350 ▶}
      -origin: Symfony\Component\Form\Form {#4511}
    }
  ]
}

to be complete :
here is my FormType :

<?php

namespace App\Form;

use App\Entity\Agorha\ConcoursType;
use App\Entity\Agorha\Departement;
use App\Entity\Agorha\Pays;
use App\Entity\Agorha\Sexe;
use App\Entity\Agorha\Ville;
use App\Entity\Candidature;
use App\Entity\ConcoursTypeEtape;
use App\Entity\EtapeDocumentUploade;
use App\Entity\Identite;
use App\Entity\UploadDocument;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\BirthdayType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\GreaterThan;
use Symfony\Component\Validator\Constraints\LessThan;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class IdentiteType extends CompteCandidatType
{
    private $villeNaissance;
    private $prenom1;
    private $prenom2;
    private $identiteRepo;
    private $identiteId;
    private $identiteSess;
    private $session;
    private $user;

    public function __construct(private RequestStack $requestStack, private EntityManagerInterface $em, Security $security)
    {
        $this->session = $this->requestStack->getSession();
        $this->identiteRepo = $this->em->getRepository(Identite::class);
        $this->identiteSess = $this->session->get('app_deposer_identite');
        $this->user = $security->getUser();
        if (!is_null($this->identiteSess)) {
            $this->identiteId = $this->identiteSess;
        } else {
            $identite = $this->identiteRepo->findLastByUser($this->user);
            if ($identite) {
                $this->identiteId = $identite->getId();
            }
        }
        if ($this->identiteId) {
            $this->villeNaissance = $this->identiteRepo->find($this->identiteId)->getVilleNaissance();
            $identite = $this->identiteRepo->find($this->identiteId);
            $prenoms = $identite->getPrenoms();
            $this->prenom1 = $prenoms[0];
            $this->prenom2 = (array_key_exists(1, $prenoms) ? $prenoms[1] : false);
        }
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $request = $this->requestStack->getCurrentRequest();
        $sess = $request->getSession();
        if ($sess) {
            $candiRepo = $this->em->getRepository(Candidature::class);
            $candi = $candiRepo->find($sess->get('candidature'));
        }
        $etapeTypeRepo = $this->em->getRepository(ConcoursTypeEtape::class);
        $etapeType = $etapeTypeRepo->findOneByTypeAndRoute($this->session->get('typeConcours'), $this->requestStack->getCurrentRequest()->get('_route'));

        //$etape = $etapeTypeRepo->findOneByRoute($request->get('_route'));

        $docToUpRepo = $this->em->getRepository(EtapeDocumentUploade::class);
        if ($etapeType && $candi) {
            $docToUp = $docToUpRepo->findByEtapeAndUploaded($etapeType, $candi);
        } else {
            $docToUp = null;
        }

        $typeRepo = $this->em->getRepository(ConcoursType::class);
        $villeRepo = $this->em->getRepository(Ville::class);
        $type = $typeRepo->find($request->getSession()->get('typeConcours'));
        $now = new \DateTimeImmutable();
        $min = $now->modify("-" . $type->getContraintes()['ageMin'] . " years");
        $max = $now->modify("-" . $type->getContraintes()['ageMax'] . " years");

        $builder
            ->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $evt) use ($villeRepo) {
                $dpt = false;
                $data = $evt->getData() ?? false;

                if ($data) {
                    $dpt = $data->getDepartementNaissance();

                    if ($prenoms = $data->getPrenoms()) {
                        if (count($prenoms) == 1) {
                            $evt->getForm()->remove('nonConcerne');
                            $evt->getForm()->add('nonConcerne', CheckboxType::class, [
                                'label' => 'Non concerné pas un deuxième prénom',
                                'mapped' => false,
                                'attr'=>['checked'=>'checked']
                            ]);
                        }
                    }
                }
                if ($dpt) {
                    $villesInDpt = $villeRepo->findByDpt($dpt->getCode());
                    $evt->getForm()->remove('villeNaissance');
                    $evt->getForm()
                        ->add(
                            'villeNaissance',
                            EntityType::class,
                            [
                                'expanded' => false,
                                'multiple' => false,
                                'mapped' => false,
                                'placeholder' => $this->villeNaissance,
                                'class' => Ville::class,
                                'label' => 'Ville de naissance',
                                'choice_label' => 'libLong',
                                'choices' => $villesInDpt,
                                'required' => true,
                            ]
                        );
                }
            })
            /*->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $evt) use ($villeRepo) {

                $dpt = $evt->getData()->getDepartementNaissance() ?? false;
                if ($dpt) {
                    $villesInDpt = $villeRepo->findByDpt($dpt);
                    //$evt->getForm()->remove('villeNaissance');
                    $evt->getForm()
                        ->add(
                            'villeNaissance',
                            EntityType::class,
                            [
                                'expanded' => false,
                                'multiple' => false,
                                'mapped' => false,
                                'class' => Ville::class,
                                'label' => 'Ville de naissance',
                                'choice_label' => 'libLong',
                                'required' => true,
                                'choices' => $villesInDpt,
                            ]
                        );

                }
                dd($evt);

            })*/
            ->add('nom', TextType::class, [
                'label' => 'Nom de naissance',
                'required' => true,
            ])
            ->add('nomUsage', TextType::class, [
                'label' => 'Nom d\'usage ou matrimonial',
                'required' => false,
            ])
            ->add('nonConcerne', CheckboxType::class, [
                'label' => 'Non concerné pas un deuxième prénom',
                'mapped' => false
            ])
            ->add(
                'prenom1',
                TextType::class,
                [
                    'data' => $this->prenom1,
                    'label' => 'Premier prénom',
                    'required' => true,
                    'constraints' => [
                        new NotBlank([], 'Le premier prénom ne peut être vide'),
                        new Regex('/\d/', 'Your prenom cannot contain a number', null, false)
                    ],
                ]
            )
            ->add(
                'prenom2',
                TextType::class,
                [
                    'label' => 'Deuxième prénom',
                    'data' => $this->prenom2,
                    'constraints' => [
                        new Callback(['callback' => static function (?string $data, ExecutionContextInterface $context) {
                            $form = $context->getRoot();
                            if (!$data && !$form->get('nonConcerne')->getData()) {
                                $context->buildViolation('Merci d\'entrer votre deuxième prénom ou de cocher "Non concerné"')
                                    ->addViolation();
                            }
                        }])
                    ]
                ]
            )
            ->add(
                'sexe',
                EntityType::class,
                [
                    'expanded' => false,
                    'multiple' => false,
                    'class' => Sexe::class,
                    'choice_label' => 'libLong',
                    'required' => true,
                    'label' => 'Sexe',
                    'query_builder' => static function (EntityRepository $er) {
                        return $er->createQueryBuilder('s')
                            ->orderBy('s.libLong', 'ASC');
                    },
                ]
            )
            ->add('villeEtrangerNaissance')
            ->add('codePostalEtrangerNaissance')
            ->add(
                'dateNaissance',
                BirthdayType::class,
                [
                    'attr'=>[
                        'max' => $min->format('Y-12-31'),
                        'min' => $max->format('Y-01-01'),
                    ],
                    'label' => 'Date de naissance',
                    'widget' => 'single_text',
                    'required' => true,
                    'by_reference' => true,
                    'constraints' => [
                        new LessThan("-" . $type->getContraintes()['ageMin'] . " years", null, 'La date de naissance doit être inférieure à ' . $min->format('d/m/Y') . ' ou une dérogation d\'age est obligatoire'),
                        new GreaterThan("-" . $type->getContraintes()['ageMax'] . " years", null, 'La date de naissance doit être supérieure à ' . $max->format('d/m/Y') . ' ou une dérogation d\'age est obligatoire')
                    ]
                ]
            )
            ->add(
                'paysNaissance',
                EntityType::class,
                [
                    'expanded' => false,
                    'multiple' => false,
                    'class' => Pays::class,
                    'label' => 'Pays de naissance',
                    'required' => true,
                    'query_builder' => static function (EntityRepository $er) {
                        return $er->createQueryBuilder('p')
                            ->orderBy("p.libLong", 'desc');
                    },
                ]
            )
            ->add(
                'departementNaissance',
                EntityType::class,
                [
                    'expanded' => false,
                    'multiple' => false,
                    'required' => true,
                    'class' => Departement::class,
                    'choice_value' => function (?Departement $entity) {
                        return $entity ? $entity->getCode() : '';
                    },
                    'placeholder' => 'Séléctionnez un département',
                    'label' => 'Département de naissance',
                    /*'query_builder' => static function (EntityRepository $er) {
                        return $er->createQueryBuilder('d')
                            ->orderBy('d.code', 'ASC');
                    },*/
                ]
            )
            ->add(
                'villeNaissance',
                EntityType::class,
                [
                    'expanded' => false,
                    'multiple' => false,
                    'class' => Ville::class,
                    'label' => 'Ville de naissance',
                    'choice_label' => 'libLong',
                    'placeholder' => 'Séléctionnez un département',
                    'choices'=>[]
                    /*'query_builder' => static function (EntityRepository $er) {
                        return $er->createQueryBuilder('v')
                            ->where('v.code like :dpt')
                            ->setParameter('dpt', '01___')
                            ->orderBy('v.libLong', 'ASC');
                    },*/
                ]
            );

            $builder->get('departementNaissance')->addEventListener(FormEvents::POST_SUBMIT,function(FormEvent $evt) use ($villeRepo){
               $dpt = $evt->getForm()->getData();
               $parentForm = $evt->getForm()->getParent();

                $villesInDpt = $villeRepo->findByDpt($dpt->getCode());
                $parentForm->remove('villeNaissance');
                $parentForm
                    ->add(
                        'villeNaissance',
                        EntityType::class,
                        [
                            'expanded' => false,
                            'multiple' => false,
                            'mapped' => false,
                            'class' => Ville::class,
                            'label' => 'Ville de naissance',
                            'choice_label' => 'libLong',
                            'required' => true,
                            'choices' => $villesInDpt,
                        ]
                    );
                //dd($parentForm->get('villeNaissance')->getConfig()->getOption('choices'));
            });

        $uploadRepo = $this->em->getRepository(UploadDocument::class);
        $docUp = [];
        $docsBDD = $uploadRepo->findByUserAndIfGenerique($this->user);
        /*$docsBDD = $uploadRepo->findBy([
            'candidature' => $candi,
        ]);*/
        foreach ($docsBDD as $docBDD) {
            $docUp[] = 'files_' . $docBDD->getEtapeDocumentUploade()->getDocument()->getLibTechnique();
        }
        $this->doc($docToUp, $builder,$docUp);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Identite::class,
            'csrf_protection' => true,
            'csrf_field_name' => '_token',
            'csrf_token_id' => 'task_item',
        ]);
    }
}

here is my controller :

#[Route('/deposer/reprise/{id}', name: 'app_deposer_reprise')]
    public function reprise(EntityManagerInterface $em, $id): Response
    {
        $candiRepo = $em->getRepository(Candidature::class);
        $candi = $candiRepo->findOneByIdentifiant($id);
        if ($candi) {
            if ($candi->isOwner($this->getUser())) {
                $crsRepo = $em->getRepository(Concours::class);
                $crs = $crsRepo->findOneByTypeAndOpen($candi->getConcoursType()->getId());

                if (!$crs) {
                    $this->request->getSession()->set('preInscription', true);
                }

                $this->request->getSession()->remove('lastRoute');
                $this->request->getSession()->set('typeConcours', $candi->getConcoursType()->getId());
                $this->request->getSession()->set('priseConnaissance', $candi->getPriseConnaissance());
                $this->request->getSession()->set('candidature', $candi->getId());

                $typeEtapeRepo = $em->getRepository(ConcoursTypeEtape::class);

                $candiEtapeRepo = $em->getRepository(CandidatureEtape::class);
                $candiEtape = $candiEtapeRepo->findLastByCandiByOrdre($candi->getId());

                /**
                 * cas du stop d une candidature dès la 1ere etape
                 * et donc pas d etape encore enregistrée en BDD
                 */
                if (!$candiEtape)
                {
                    $fstEtape = $typeEtapeRepo->findFirstByType($candi->getConcoursType()->getId());
                    if (!$fstEtape)
                    {
                        $this->request->getSession()->getFlashBag()->add('error', 'Aucune étape encore configurée pour ce type de recrutement');
                        return $this->redirectToRoute('app_home_index');
                    }
                    return $this->redirectToRoute($fstEtape->getEtape()->getRoute());
                }
                $route = $candiEtape?->getEtape()->getEtape()->getRoute();

                $allEtapeBefore = $typeEtapeRepo->findEnfantByTypeOrdered($candi->getConcoursType(), $candiEtape->getEtape()->getEtape()->getParent(), $candiEtape->getEtape()->getOrdre());
                foreach ($allEtapeBefore as $etapeCandi) {
                    $route = $etapeCandi->getEtape()->getRoute();
                    if (array_key_exists($route, $this->routeEntity)) {
                        $repo = $em->getRepository($this->routeEntity[$route]);
                        $last = $repo->findLastByUser($this->getUser());
                        if ($last) {
                            $this->request->getSession()->set($route, $last->getId());
                        }
                    }
                }

                $sess = $this->request->getSession();
                $sess->set('lastRoute', 'app_deposer_reprise');
                return $this->redirectToRoute($route);
            }
            $this->request->getSession()->getFlashBag()->add('error', 'La candidature recherché ne semble pas vous appartenir');
            return $this->redirectToRoute('app_home_index');
        }
        $this->request->getSession()->getFlashBag()->add('error', 'La candidature recherché ne semble plus exister');
        return $this->redirectToRoute('app_home_index');
    }

Here is my twig

{{ form_start(formIdent, {attr: {novalidate: 'novalidate'}}) }}

        {{ form_row(formIdent._token) }}
        {{ form_row(formIdent.nom,{'attr': {'class': 'fr-input'}}) }}

        {{ form_row(formIdent.prenom1,{'attr': {'class': 'fr-input'}}) }}

        {{ form_row(formIdent.dateNaissance,{'attr': {'class': 'fr-input'}}) }}

        {{ form_row(formIdent.paysNaissance,{'attr': {'class': 'fr-input'}}) }}

        {{ form_row(formIdent.departementNaissance,{'attr': {'class': 'fr-input'}}) }}

        {{ form_row(formIdent.villeNaissance,{'attr': {'class': 'fr-input'}}) }}

        {{ form_row(formIdent.sexe,{'attr': {'class': 'fr-input'}}) }}

        {{ form_row(formIdent.nomUsage,{'attr': {'class': 'fr-input'}}) }}

        {{ form_row(formIdent.prenom2,{'attr': {'class': 'fr-input'}}) }}

            {{ form_row(formIdent.nonConcerne) }}

                <button class="fr-btn fr-btn--secondary" type="reset" value="remise à zéro">
                    Annuler
                </button>

                <button class="fr-btn" type="submit">
                    Suivant
                </button>

        {{ form_end(formIdent, {'render_rest': false}) }}

and my JS :

domready(function() {
    const DPT = document.getElementById('identite_departementNaissance')
    DPT.addEventListener('change', e => {
        const selectedDPT = e.currentTarget.value
        const URL = '/api/villes?codePostal=' + selectedDPT + '&o[libLong]=asc'
        console.log('change dpt',selectedDPT)
        xhr.get(URL,true)
            .then(response => {
                if (response['hydra:totalItems']>0)
                {
                    let ville = document.getElementById('identite_villeNaissance')
                    let villes = response['hydra:member']

                    console.log('villes',villes)

                    ville.innerHTML = ''
                    villes.map(v=>{
                        let opt = document.createElement('option')
                        opt.value = v.code
                        opt.innerHTML = v.libLong
                        ville.appendChild(opt)
                    })
                }
            })
    })
})