问:
Symfony 5 form : 2 dynamic select
I am using Symfony 5. I have managed to link up to two select box with form events, but I need to have three dynamic select box. This is the relation between my entities: category(Famille) -> sub_category(sous_famille) -> sub_sub_category (sous_sous_famille). The sub_sub_category is linked to an Article entity like this:

a category -> many sub_categorys

a sub_category -> many sub_sub_category

a sub_sub_category -> many articles

When I add a new article, I should be able to select a Category and have the sub_category dropdown updated in accordance with category selection; the same thing for the sub_sub_category dropdown after I have selected a sub_category. I have made things work for category and sub_category following a [french video][1] because the one in Symfony guide doesn't work(i don't know why).
This is the Category(Famille) entity:

```<code>/**
 * @ORM\Entity(repositoryClass=FamilleRepository::class)
 * @UniqueEntity("fam_code")
 */
class Famille
{

    /**
     * @ORM\Id
     * @ORM\Column(type="string", length=255,unique=true)
     * @Assert\NotBlank
     */
    private $fam_code;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $fam_libelle_a;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $fam_libelle_f;

    /**
     * @ORM\OneToMany(targetEntity=SousFamille::class, mappedBy="fam_code")
     *
     */
    private $sousFamilles;
...
}
</code>```

This is the sub_category(sous_famille) entity:

```<code>/**
 * @ORM\Entity(repositoryClass=SousFamilleRepository::class)
 * @UniqueEntity("sf_code")
 */
class SousFamille
{

    /**
     * @ORM\Id
     * @ORM\Column(type="string", length=255, unique=true)
     * @Assert\NotBlank
     */
    private $sf_code;

    /**
     *
     * @ORM\ManyToOne(targetEntity=Famille::class, inversedBy="sousFamilles")
     * @ORM\JoinColumn(name="fam_code", referencedColumnName="fam_code",nullable=false)
     * @Assert\NotBlank
     */
    private $fam_code;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $sf_libelle_a;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $sf_libelle_f;

    /**
     * @ORM\OneToMany(targetEntity=SousSousFamille::class, mappedBy="sf_code")
     */
    private $sousSousFamilles;
...

}
</code>```

This is the sub_sub_category(sous_sous_famille):

```<code>/**
 * @ORM\Entity(repositoryClass=SousSousFamilleRepository::class)
 * @UniqueEntity("ssf_code")
 */
class SousSousFamille
{

    /**
     * @ORM\Id
     * @ORM\Column(type="string", length=255,unique=true)
     * @Assert\NotBlank
     */
    private $ssf_code;

    /**
     * @ORM\ManyToOne(targetEntity=SousFamille::class, inversedBy="sousSousFamilles")
     * @ORM\JoinColumn(name="sf_code", referencedColumnName="sf_code",nullable=false)
     * @Assert\NotBlank
     */
    private $sf_code;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $ssf_libelle_a;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $ssf_libelle_f;

    /**
     * @ORM\OneToMany(targetEntity=Article::class, mappedBy="ssf_code")
     */
    private $articles;

    /**
     * @return Collection|Article[]
     */
    public function getArticles(): Collection
    {
        return $this->articles;
    }
...
}
</code>```

this is the article entity:

```<code>/**
 * @ORM\Entity(repositoryClass=ArticleRepository::class)
 * @UniqueEntity("art_code")
 */

class Article
{

 /**
 * @ORM\Id
 * @ORM\Column(type="string", length=255,unique=true)
 * @Assert\NotBlank
 */
private $art_code;

/**
 * @ORM\ManyToOne(targetEntity=SousSousFamille::class, inversedBy="articles")
 * @ORM\JoinColumn(name="ssf_code", referencedColumnName="ssf_code",nullable=false)
 * @Assert\NotBlank
 */
private $ssf_code;

/**
 * @ORM\Column(type="string", length=255)
 * @Assert\NotBlank
 */
private $art_libelle_a;

/**
 * @ORM\Column(type="string", length=255)
 * @Assert\NotBlank
 */
private $art_libelle_f;
...
</code>```

}

UPDATED !!!
i have two forms, a ArticleType form and a CategorySelectionType form like this:

CategorySelectionType :

```<code>class CategorySelectionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('fam_code', EntityType::class, [
                'class' => Famille::class,
                'placeholder' => 'Choisir une Catégorie',
                'required' => 'true',
                'mapped' => false,
                'query_builder' => function (FamilleRepository $code) {
                    return $code->createQueryBuilder('c')->orderBy('c.fam_libelle_f', 'ASC');
                }
            ])
            ->add('sf_code', EntityType::class, [
                'class' => SousFamille::class,
                'mapped' => false,
                'required' => true,
                'placeholder' => 'Choisir une Sous Catégorie',
                'query_builder' => function (SousFamilleRepository $code) {
                    return $code->createQueryBuilder('c')->orderBy('c.sf_libelle_f', 'ASC');
                }
            ]);
        $fm = function (FormInterface $form, Famille $fam = null) {
            $sf = (null === $fam) ? [] : $fam->getSousFamilles();
            $form->add('sf_code', EntityType::class, [
                'class' => SousFamille::class,
                'choices' => $sf,
                'mapped' => false,
                'required' => true,
                'placeholder' => 'Choisir une Sous Catégorie',
                'query_builder' => function (SousFamilleRepository $code) {
                    return $code->createQueryBuilder('c')->orderBy('c.sf_libelle_f', 'ASC');
                }

            ]);
        };
        $builder->get('fam_code')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $e) use ($fm) {
                $fam = $e->getForm()->getData();
                $fm($e->getForm()->getParent(), $fam);
            }
        );
    }
..}
</code>```

ArticleType:

```<code>    class ArticleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('art_code', TextType::class, ['label' => 'Code Article', 'required' => 'true'])
            ->add('art_libelle_a', TextType::class, ['label' => 'Libellé Article en Arabe', 'required' => 'true'])
            ->add('art_libelle_f', TextType::class, ['label' => 'Libellé Article en Français', 'required' => 'true'])
            ->add('ssf_code', EntityType::class, [
                'class' => SousSousFamille::class,
                'choices' => $options['ssfs'],
                'placeholder' => 'Choisir une Sous Sous Catégorie',
                'required' => 'true',
                'query_builder' => function (SousSousFamilleRepository $code) {
                    return $code->createQueryBuilder('c')->orderBy('c.ssf_libelle_f', 'ASC');
                }
            ]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Article::class,
            'ssfs' => [],
        ]);
    }
}
</code>```

In the controller:

```<code>/**
     * @Route("/ajoutArticle", name="app_ajoutA")
     */
    public function ajoutA(Request $req, EntityManagerInterface $em, SousFamilleRepository $ssrep): Response
    {
        $step = 1;
        $art = new Article();
        $sel = $this->createForm(CategorySelectionType::class);
        $sel->handleRequest($req);
        $ssf = [];
        if ($sel->isSubmitted() && $sel->isValid()) {
            $rep = $sel->get('sf_code')->getData();
            $ssf = $ssrep->find($rep->getSFCODE())->getSousSousFamilles();
            $step = 2;
        }
        $form = $this->createForm(ArticleType::class, $art, ['ssfs' => $ssf]);
        dd($req->get('ssf_code'));
        $form->handleRequest($req);

        if ($form->isSubmitted() && $form->isValid()) {

            $em->persist($art);
            $em->flush();
            $this->addFlash('success', 'Article créé avec succès !');
            return $this->redirectToRoute('app_article');
        }

        return $this->render('fr/gestion-articles/Articles/ajoutA.html.twig', ['form' => $form->createView(), 'sel' => $sel->createView(), 'step' => $step]);
    }
</code>```

here is my script template:

```<code><script>
window.onload = () => {
let fam = document.querySelector("#category_selection_fam_code");
fam.addEventListener("change", function () {
let form = this.closest("form").closest("form");
let data = this.name + "=" + this.value;
fetch(form.action, {
method: form.getAttribute("method"),
body: data,
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset:ut_8"
}
}).then(response => response.text()).then(html => {
let content = document.createElement("html");
content.innerHTML = html;
let nouvSelect = content.querySelector("#category_selection_sf_code");
document.querySelector("#category_selection_sf_code").replaceWith(nouvSelect);
})
});
}
</script>
</code>```

But I have new problem, when submitting the form (ArticleType), the field ssf_code is set to null i don't know why it didn't take the value that i selected.
can you please help me?
[1]: https://www.youtube.com/watch?v=f7tdb30evUk

答:
I think that the class diagram for your category class need to be a recursive relation, which where you will need to add a parent attribut, because the way you are doing it is not flexible and very limited (imagine you need to add a future subcategory SousSousSousCategory).
And the maintenance of the code will be difficult in case you need to add an attribut or a method to Famille, you need to add the same to every subcategory.

Check this image to understand

You need set your class this way

```<code><?php

namespace App\Entity;

use App\Repository\FamilleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=FamilleRepository::class)
 */
class Famille
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $fam_code;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $fam_libelle_a;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $fam_libelle_f;

    /**
     * @ORM\ManyToOne(targetEntity=Famille::class, inversedBy="sous_familles")
     */
    private $parent;

    /**
     * @ORM\OneToMany(targetEntity=Famille::class, mappedBy="parent")
     */
    private $sous_familles;

    public function __construct()
    {
        $this->sous_familles = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getFamCode(): ?string
    {
        return $this->fam_code;
    }

    public function setFamCode(string $fam_code): self
    {
        $this->fam_code = $fam_code;

        return $this;
    }

    public function getFamLibelleA(): ?string
    {
        return $this->fam_libelle_a;
    }

    public function setFamLibelleA(string $fam_libelle_a): self
    {
        $this->fam_libelle_a = $fam_libelle_a;

        return $this;
    }

    public function getFamLibelleF(): ?string
    {
        return $this->fam_libelle_f;
    }

    public function setFamLibelleF(string $fam_libelle_f): self
    {
        $this->fam_libelle_f = $fam_libelle_f;

        return $this;
    }

    public function getParent(): ?self
    {
        return $this->parent;
    }

    public function setParent(?self $parent): self
    {
        $this->parent = $parent;

        return $this;
    }

    /**
     * @return Collection|self[]
     */
    public function getSousFamilles(): Collection
    {
        return $this->sous_familles;
    }

    public function addSousFamille(self $sousFamille): self
    {
        if (!$this->sous_familles->contains($sousFamille)) {
            $this->sous_familles[] = $sousFamille;
            $sousFamille->setParent($this);
        }

        return $this;
    }

    public function removeSousFamille(self $sousFamille): self
    {
        if ($this->sous_familles->contains($sousFamille)) {
            $this->sous_familles->removeElement($sousFamille);
            // set the owning side to null (unless already changed)
            if ($sousFamille->getParent() === $this) {
                $sousFamille->setParent(null);
            }
        }

        return $this;
    }
}
</code>```

This code is generated with php bin/console make:entity command

Title: Symfony 5 form : 2 dynamic select

Body:
I am using Symfony 5. I have managed to link up to two select box with form events, but I need to have three dynamic select box. This is the relation between my entities: category(Famille) -> sub_category(sous_famille) -> sub_sub_category (sous_sous_famille). The sub_sub_category is linked to an Article entity like this:

a category -> many sub_categorys

a sub_category -> many sub_sub_category

a sub_sub_category -> many articles

When I add a new article, I should be able to select a Category and have the sub_category dropdown updated in accordance with category selection; the same thing for the sub_sub_category dropdown after I have selected a sub_category. I have made things work for category and sub_category following a [french video][1] because the one in Symfony guide doesn't work(i don't know why).
This is the Category(Famille) entity:

/**
 * @ORM\Entity(repositoryClass=FamilleRepository::class)
 * @UniqueEntity("fam_code")
 */
class Famille
{

    /**
     * @ORM\Id
     * @ORM\Column(type="string", length=255,unique=true)
     * @Assert\NotBlank
     */
    private $fam_code;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $fam_libelle_a;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $fam_libelle_f;

    /**
     * @ORM\OneToMany(targetEntity=SousFamille::class, mappedBy="fam_code")
     *
     */
    private $sousFamilles;
...
}

This is the sub_category(sous_famille) entity:

/**
 * @ORM\Entity(repositoryClass=SousFamilleRepository::class)
 * @UniqueEntity("sf_code")
 */
class SousFamille
{

    /**
     * @ORM\Id
     * @ORM\Column(type="string", length=255, unique=true)
     * @Assert\NotBlank
     */
    private $sf_code;

    /**
     *
     * @ORM\ManyToOne(targetEntity=Famille::class, inversedBy="sousFamilles")
     * @ORM\JoinColumn(name="fam_code", referencedColumnName="fam_code",nullable=false)
     * @Assert\NotBlank
     */
    private $fam_code;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $sf_libelle_a;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $sf_libelle_f;

    /**
     * @ORM\OneToMany(targetEntity=SousSousFamille::class, mappedBy="sf_code")
     */
    private $sousSousFamilles;
...

}

This is the sub_sub_category(sous_sous_famille):

/**
 * @ORM\Entity(repositoryClass=SousSousFamilleRepository::class)
 * @UniqueEntity("ssf_code")
 */
class SousSousFamille
{

    /**
     * @ORM\Id
     * @ORM\Column(type="string", length=255,unique=true)
     * @Assert\NotBlank
     */
    private $ssf_code;

    /**
     * @ORM\ManyToOne(targetEntity=SousFamille::class, inversedBy="sousSousFamilles")
     * @ORM\JoinColumn(name="sf_code", referencedColumnName="sf_code",nullable=false)
     * @Assert\NotBlank
     */
    private $sf_code;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $ssf_libelle_a;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $ssf_libelle_f;

    /**
     * @ORM\OneToMany(targetEntity=Article::class, mappedBy="ssf_code")
     */
    private $articles;

    /**
     * @return Collection|Article[]
     */
    public function getArticles(): Collection
    {
        return $this->articles;
    }
...
}

this is the article entity:

/**
 * @ORM\Entity(repositoryClass=ArticleRepository::class)
 * @UniqueEntity("art_code")
 */

class Article
{

 /**
 * @ORM\Id
 * @ORM\Column(type="string", length=255,unique=true)
 * @Assert\NotBlank
 */
private $art_code;

/**
 * @ORM\ManyToOne(targetEntity=SousSousFamille::class, inversedBy="articles")
 * @ORM\JoinColumn(name="ssf_code", referencedColumnName="ssf_code",nullable=false)
 * @Assert\NotBlank
 */
private $ssf_code;

/**
 * @ORM\Column(type="string", length=255)
 * @Assert\NotBlank
 */
private $art_libelle_a;

/**
 * @ORM\Column(type="string", length=255)
 * @Assert\NotBlank
 */
private $art_libelle_f;
...

}

UPDATED !!!
i have two forms, a ArticleType form and a CategorySelectionType form like this:

CategorySelectionType :

class CategorySelectionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('fam_code', EntityType::class, [
                'class' => Famille::class,
                'placeholder' => 'Choisir une Catégorie',
                'required' => 'true',
                'mapped' => false,
                'query_builder' => function (FamilleRepository $code) {
                    return $code->createQueryBuilder('c')->orderBy('c.fam_libelle_f', 'ASC');
                }
            ])
            ->add('sf_code', EntityType::class, [
                'class' => SousFamille::class,
                'mapped' => false,
                'required' => true,
                'placeholder' => 'Choisir une Sous Catégorie',
                'query_builder' => function (SousFamilleRepository $code) {
                    return $code->createQueryBuilder('c')->orderBy('c.sf_libelle_f', 'ASC');
                }
            ]);
        $fm = function (FormInterface $form, Famille $fam = null) {
            $sf = (null === $fam) ? [] : $fam->getSousFamilles();
            $form->add('sf_code', EntityType::class, [
                'class' => SousFamille::class,
                'choices' => $sf,
                'mapped' => false,
                'required' => true,
                'placeholder' => 'Choisir une Sous Catégorie',
                'query_builder' => function (SousFamilleRepository $code) {
                    return $code->createQueryBuilder('c')->orderBy('c.sf_libelle_f', 'ASC');
                }

            ]);
        };
        $builder->get('fam_code')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $e) use ($fm) {
                $fam = $e->getForm()->getData();
                $fm($e->getForm()->getParent(), $fam);
            }
        );
    }
..}

ArticleType:

    class ArticleType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('art_code', TextType::class, ['label' => 'Code Article', 'required' => 'true'])
            ->add('art_libelle_a', TextType::class, ['label' => 'Libellé Article en Arabe', 'required' => 'true'])
            ->add('art_libelle_f', TextType::class, ['label' => 'Libellé Article en Français', 'required' => 'true'])
            ->add('ssf_code', EntityType::class, [
                'class' => SousSousFamille::class,
                'choices' => $options['ssfs'],
                'placeholder' => 'Choisir une Sous Sous Catégorie',
                'required' => 'true',
                'query_builder' => function (SousSousFamilleRepository $code) {
                    return $code->createQueryBuilder('c')->orderBy('c.ssf_libelle_f', 'ASC');
                }
            ]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Article::class,
            'ssfs' => [],
        ]);
    }
}

In the controller:

/**
     * @Route("/ajoutArticle", name="app_ajoutA")
     */
    public function ajoutA(Request $req, EntityManagerInterface $em, SousFamilleRepository $ssrep): Response
    {
        $step = 1;
        $art = new Article();
        $sel = $this->createForm(CategorySelectionType::class);
        $sel->handleRequest($req);
        $ssf = [];
        if ($sel->isSubmitted() && $sel->isValid()) {
            $rep = $sel->get('sf_code')->getData();
            $ssf = $ssrep->find($rep->getSFCODE())->getSousSousFamilles();
            $step = 2;
        }
        $form = $this->createForm(ArticleType::class, $art, ['ssfs' => $ssf]);
        dd($req->get('ssf_code'));
        $form->handleRequest($req);

        if ($form->isSubmitted() && $form->isValid()) {

            $em->persist($art);
            $em->flush();
            $this->addFlash('success', 'Article créé avec succès !');
            return $this->redirectToRoute('app_article');
        }

        return $this->render('fr/gestion-articles/Articles/ajoutA.html.twig', ['form' => $form->createView(), 'sel' => $sel->createView(), 'step' => $step]);
    }

here is my script template:

But I have new problem, when submitting the form (ArticleType), the field ssf_code is set to null i don't know why it didn't take the value that i selected.
can you please help me?
[1]: https://www.youtube.com/watch?v=f7tdb30evUk

Body:
I think that the class diagram for your category class need to be a recursive relation, which where you will need to add a parent attribut, because the way you are doing it is not flexible and very limited (imagine you need to add a future subcategory SousSousSousCategory).
And the maintenance of the code will be difficult in case you need to add an attribut or a method to Famille, you need to add the same to every subcategory.

Check this image to understand

You need set your class this way

<?php

namespace App\Entity;

use App\Repository\FamilleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=FamilleRepository::class)
 */
class Famille
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $fam_code;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $fam_libelle_a;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $fam_libelle_f;

    /**
     * @ORM\ManyToOne(targetEntity=Famille::class, inversedBy="sous_familles")
     */
    private $parent;

    /**
     * @ORM\OneToMany(targetEntity=Famille::class, mappedBy="parent")
     */
    private $sous_familles;

    public function __construct()
    {
        $this->sous_familles = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getFamCode(): ?string
    {
        return $this->fam_code;
    }

    public function setFamCode(string $fam_code): self
    {
        $this->fam_code = $fam_code;

        return $this;
    }

    public function getFamLibelleA(): ?string
    {
        return $this->fam_libelle_a;
    }

    public function setFamLibelleA(string $fam_libelle_a): self
    {
        $this->fam_libelle_a = $fam_libelle_a;

        return $this;
    }

    public function getFamLibelleF(): ?string
    {
        return $this->fam_libelle_f;
    }

    public function setFamLibelleF(string $fam_libelle_f): self
    {
        $this->fam_libelle_f = $fam_libelle_f;

        return $this;
    }

    public function getParent(): ?self
    {
        return $this->parent;
    }

    public function setParent(?self $parent): self
    {
        $this->parent = $parent;

        return $this;
    }

    /**
     * @return Collection|self[]
     */
    public function getSousFamilles(): Collection
    {
        return $this->sous_familles;
    }

    public function addSousFamille(self $sousFamille): self
    {
        if (!$this->sous_familles->contains($sousFamille)) {
            $this->sous_familles[] = $sousFamille;
            $sousFamille->setParent($this);
        }

        return $this;
    }

    public function removeSousFamille(self $sousFamille): self
    {
        if ($this->sous_familles->contains($sousFamille)) {
            $this->sous_familles->removeElement($sousFamille);
            // set the owning side to null (unless already changed)
            if ($sousFamille->getParent() === $this) {
                $sousFamille->setParent(null);
            }
        }

        return $this;
    }
}

This code is generated with php bin/console make:entity command


来源: stackexchange

问:
SQL nesting BEGIN END Blocks gives SQL Error (102)
I'm getting the following error for this simple piece of SQL code. Any ideas why? Any BEGIN ... END block causes this error to occur

/* SQL Error (156): Incorrect syntax near the keyword 'END'. */

```<code>DECLARE @PROCESSEDCOUNT INT = 0
WHILE (@PROCESSEDCOUNT < 10)
BEGIN
    SET @PROCESSEDCOUNT +=1
    IF 1=1
    BEGIN
        -- Stuff happens here
    END
END
</code>```

This is running on SQL Server - MSSQL15

答:
You must put something in between the BEGIN and END block
For example:</p>
```<code>DECLARE @PROCESSEDCOUNT INT= 1

WHILE (@PROCESSEDCOUNT < 10)
BEGIN
    SET @PROCESSEDCOUNT +=1
    IF 1=1
    BEGIN
        PRINT '1'
    END
END
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm getting the following error for this simple piece of SQL code. Any ideas why? Any BEGIN ... END block causes this error to occur

/* SQL Error (156): Incorrect syntax near the keyword 'END'. */

DECLARE @PROCESSEDCOUNT INT = 0
WHILE (@PROCESSEDCOUNT < 10)
BEGIN
    SET @PROCESSEDCOUNT +=1
    IF 1=1
    BEGIN
        -- Stuff happens here
    END
END

This is running on SQL Server - MSSQL15

Body:
You must put something in between the BEGIN and END block
For example:

DECLARE @PROCESSEDCOUNT INT= 1

WHILE (@PROCESSEDCOUNT < 10)
BEGIN
    SET @PROCESSEDCOUNT +=1
    IF 1=1
    BEGIN
        PRINT '1'
    END
END


问:
CSS :where() selector not usable in Electron app
I am currently trying to embed a website into the MS Teams desktop app. As far as I know this is an Electron app. The integration works fine but the styles are broken. From what I have discovered so far, it seems that the CSS :where() selector is not working.

Is there any information about known problems in this direction? Are workarounds or polyfills for this issue available?

答:
I didn't find information about this problem, but according to the documentation, here is a workaround :

/* Selects any paragraph inside a header, main
   or footer element that is being hovered */
:where(header, main, footer) p:hover {
  color: red;
  cursor: pointer;
}

/* The above is equivalent to the following */
header p:hover,
main p:hover,
footer p:hover {
  color: red;
  cursor: pointer;
}
```


问:
CSS pseudo element positioning - partial border above header
I am struggling to position the partial border directly above the title without the title floating to the left of the 'before' pseudo element.  It works fine on pages without an image but I need the title and text to wrap around the image on some pages where an image exists but not on others and this is causing the issue.

I have tried absolute positioning, different displays but nothing works.

https://codepen.io/lol4000/pen/dyZvmGK

```<code> <img width="420" height="195" src="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="PIM" srcset="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg 420w, https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS-300x139.jpg 300w" sizes="(max-width: 420px) 100vw, 420px">            <h2 class="sub-title">Test English subtitle</h2><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lacinia porta velit, ornare lobortis tortor aliquam at. Vivamus tristique, nulla vitae tempus vehicula, ante arcu lobortis est, nec maximus nunc ipsum et nunc.</p> <p>Donec mattis vulputate tellus, vel tincidunt purus condimentum vel. </p>Cras vehicula, ex non varius faucibus, felis orci consectetur dui, vitae auctor lectus ex ornare ligula. Maecenas nec lectus turpis. <p>In varius ligula eu leo rhoncus fringilla. Nullam blandit iaculis cursus. Sed pulvinar sollicitudin rhoncus. </p><p>Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.</p> <p>Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.</p><p>Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.</p> <p>Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.</p>

h2.sub-title {font-size:28px;display: block;}
h2.sub-title::before{ position: relative; height: 8px;width: 130px;left: 0;  top: -10px;background: #441A6D;display:block;content: ""}

.wp-post-image {
    float: left;
    margin: 0 15px 10px 0;}
</code>```

答:
Use flex instead float:

h2.sub-title {
  font-size: 28px;
  display: block;
}

h2.sub-title::before {
  position: relative;
  height: 8px;
  width: 130px;
  left: 0;
  top: -10px;
  background: #441A6D;
  display: block;
  content: ""
}

div {
  display: flex;
}

.wp-post-image {
  margin: 0 15px 10px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div><img width="420" height="195" src="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="PIM" srcset="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg 420w, https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS-300x139.jpg 300w"
    sizes="(max-width: 420px) 100vw, 420px">
  <h2 class="sub-title">Test English subtitle</h2>
</div></code>```

Body:
I am struggling to position the partial border directly above the title without the title floating to the left of the 'before' pseudo element.  It works fine on pages without an image but I need the title and text to wrap around the image on some pages where an image exists but not on others and this is causing the issue.

I have tried absolute positioning, different displays but nothing works.

https://codepen.io/lol4000/pen/dyZvmGK

Test English subtitle

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lacinia porta velit, ornare lobortis tortor aliquam at. Vivamus tristique, nulla vitae tempus vehicula, ante arcu lobortis est, nec maximus nunc ipsum et nunc.

Donec mattis vulputate tellus, vel tincidunt purus condimentum vel.
Cras vehicula, ex non varius faucibus, felis orci consectetur dui, vitae auctor lectus ex ornare ligula. Maecenas nec lectus turpis.
In varius ligula eu leo rhoncus fringilla. Nullam blandit iaculis cursus. Sed pulvinar sollicitudin rhoncus.

Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.

Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.

Pellentesque vulputate luctus ante non luctus. Integer tincidunt, tellus at maximus fermentum, lorem ante sagittis elit, in varius dui nulla et est. In hac habitasse platea dictumst. Integer eget nunc nec augue congue vestibulum. Vestibulum id libero enim.

Etiam vulputate efficitur erat a viverra. Mauris eu malesuada lacus. Sed vestibulum est in velit euismod, quis porttitor velit rhoncus.

h2.sub-title {font-size:28px;display: block;}
h2.sub-title::before{ position: relative; height: 8px;width: 130px;left: 0;  top: -10px;background: #441A6D;display:block;content: ""}

.wp-post-image {
    float: left;
    margin: 0 15px 10px 0;}

Body:
Use flex instead float:

h2.sub-title {
  font-size: 28px;
  display: block;
}

h2.sub-title::before {
  position: relative;
  height: 8px;
  width: 130px;
  left: 0;
  top: -10px;
  background: #441A6D;
  display: block;
  content: ""
}

div {
  display: flex;
}

.wp-post-image {
  margin: 0 15px 10px 0;
}

<div><img width="420" height="195" src="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="PIM" srcset="https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS.jpg 420w, https://heuristic-hypatia.91-134-228-53.plesk.page/wp-content/uploads/2013/02/Fotolia_50400145_XS-300x139.jpg 300w"
    sizes="(max-width: 420px) 100vw, 420px">
  <h2 class="sub-title">Test English subtitle</h2>
</div>


问:
Unhandled Runtine error on Google Sign In (Next.js+FIrebase)
I am getting the following error when trying to sign in using firebase native google sign in methods,

Unhandled Runtime Error

Error: Network Error

Call Stack

Nj/</</</f<

node_modules/@firebase/auth/dist/auth.esm.js (273:408)

and after this the popup automatically closes and I get this error,

Unhandled Runtime Error

Error: The popup has been closed by the user before finalizing the operation.

Here is my code for sign in button and auth function,

```<code>import { auth, firestore, googleAuthProvider} from '../lib/firebase';
import { useContext, useEffect, useState, useCallback } from 'react';
import { UserContext } from '../lib/context';
import debounce from 'lodash.debounce';

export default function Enter(props) {
  const { user, username } = useContext(UserContext);
  return (
    <main>
      {user ? !username ? <UsernameForm /> : <SignOutButton /> : <SignInButton />}
    </main>
  );
}

// Sign in with Google button
function SignInButton() {
  const signInWithGoogle = async () => {
    await auth.signInWithPopup(googleAuthProvider);
  };

  return (
    <>
      <button className="btn-google" onClick={signInWithGoogle}>
        <img src={'/google.png'} width="30px" /> Sign in with Google
      </button>
      <button onClick={() => auth.signInAnonymously()}>
        Sign in Anonymously
      </button>
    </>
  );
}

// Sign out button
function SignOutButton() {
  return <button onClick={() => auth.signOut()}>Sign Out</button>;
}
</code>```

firebase.js

```<code>import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/storage';

const firebaseConfig = {
  apiKey: "...",
  authDomain: "craft-share-1288c.firebaseapp.com",
  projectId: "craft-share-1288c",
  storageBucket: "craft-share-1288c.appspot.com",
  messagingSenderId: "960895737878",
  appId: "1:960895737878:web:e003d00478721bd0a6d537",
  measurementId: "G-0R8HZCSTD4"
};
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}
// Auth exports
export const auth = firebase.auth();
export const googleAuthProvider = new firebase.auth.GoogleAuthProvider();
</code>```

My package.json is,

```<code>{
  "name": "craft-share",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "firebase": "^8.2.1",
    "lodash.debounce": "^4.0.8",
    "lodash.kebabcase": "^4.1.1",
    "next": "12.0.1",
    "react": "17.0.1",
    "react-dom": "17.0.1",
    "react-firebase-hooks": "^2.2.0",
    "react-hook-form": "^6.14.2",
    "react-hot-toast": "^1.0.2",
    "react-markdown": "^5.0.3"
  },
  "devDependencies": {
    "eslint": "8.8.0",
    "eslint-config-next": "12.0.10"
  }
}
</code>```

答:
Try this, maybe this could do the trick?

```<code>async function SignInButton() {
  const signInWithGoogle = await auth.signInWithPopup(googleAuthProvider);
};
</code>```

or

```<code>auth.signInWithPopup(googleAuthProvider).then((results) => {
  // do whatever here with the results
}).catch((error) => {
     console.error(error)
})
</code>```

Body:
I am getting the following error when trying to sign in using firebase native google sign in methods,

Unhandled Runtime Error

Error: Network Error

Call Stack

Nj/</</</f<

node_modules/@firebase/auth/dist/auth.esm.js (273:408)

and after this the popup automatically closes and I get this error,

Unhandled Runtime Error

Error: The popup has been closed by the user before finalizing the operation.

Here is my code for sign in button and auth function,

import { auth, firestore, googleAuthProvider} from '../lib/firebase';
import { useContext, useEffect, useState, useCallback } from 'react';
import { UserContext } from '../lib/context';
import debounce from 'lodash.debounce';

export default function Enter(props) {
  const { user, username } = useContext(UserContext);
  return (

      {user ? !username ? <UsernameForm /> : <SignOutButton /> : <SignInButton />}

  );
}

// Sign in with Google button
function SignInButton() {
  const signInWithGoogle = async () => {
    await auth.signInWithPopup(googleAuthProvider);
  };

  return (
    <>
      <button className="btn-google" onClick={signInWithGoogle}>
         Sign in with Google
      </button>
      <button onClick={() => auth.signInAnonymously()}>
        Sign in Anonymously
      </button>
    </>
  );
}

// Sign out button
function SignOutButton() {
  return <button onClick={() => auth.signOut()}>Sign Out</button>;
}

firebase.js

import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/storage';

const firebaseConfig = {
  apiKey: "...",
  authDomain: "craft-share-1288c.firebaseapp.com",
  projectId: "craft-share-1288c",
  storageBucket: "craft-share-1288c.appspot.com",
  messagingSenderId: "960895737878",
  appId: "1:960895737878:web:e003d00478721bd0a6d537",
  measurementId: "G-0R8HZCSTD4"
};
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}
// Auth exports
export const auth = firebase.auth();
export const googleAuthProvider = new firebase.auth.GoogleAuthProvider();

My package.json is,

{
  "name": "craft-share",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "firebase": "^8.2.1",
    "lodash.debounce": "^4.0.8",
    "lodash.kebabcase": "^4.1.1",
    "next": "12.0.1",
    "react": "17.0.1",
    "react-dom": "17.0.1",
    "react-firebase-hooks": "^2.2.0",
    "react-hook-form": "^6.14.2",
    "react-hot-toast": "^1.0.2",
    "react-markdown": "^5.0.3"
  },
  "devDependencies": {
    "eslint": "8.8.0",
    "eslint-config-next": "12.0.10"
  }
}

Body:
Try this, maybe this could do the trick?

async function SignInButton() {
  const signInWithGoogle = await auth.signInWithPopup(googleAuthProvider);
};

or

auth.signInWithPopup(googleAuthProvider).then((results) => {
  // do whatever here with the results
}).catch((error) => {
     console.error(error)
})


问:
Accessing equal earth projection with sf
I'm a little confused why I'm not able to iplement the equal earth projection using sf in R, or how to diagnose why this is.

When I check my crs options with sf_proj_info("proj") it appears as an option.

But if whenever I try to implement it with st_crs("+proj=eqearth") or st_crs("eqearth") I'm told that it is an invalid crs.

Am I misunderstanding whether this is an available option? implementing it incorrectly for transforming/projecting? Or all of the above?

Just trying to display the whole earth without grossly distorting areas near the poles...

答:
You may want to update your PROJ version; I am running this code with 8.2.1 and it seems to work as expected...

```<code>library(sf)
library(giscoR) # for the world dataset

sf_extSoftVersion()
#          GEOS           GDAL         proj.4 GDAL_with_GEOS     USE_PROJ_H           PROJ
#      "3.10.2"        "3.4.1"        "8.2.1"         "true"         "true"        "8.2.1"

world <- gisco_countries %>%
  st_geometry() # no data are required...

# ugly!
plot(world)
</code>```

```<code>a_better_world <- world %>%
  st_transform(crs = "+proj=eqearth")

# much nicer!
plot(a_better_world)
</code>```

Body:
You may want to update your PROJ version; I am running this code with 8.2.1 and it seems to work as expected...

library(sf)
library(giscoR) # for the world dataset

sf_extSoftVersion()
#          GEOS           GDAL         proj.4 GDAL_with_GEOS     USE_PROJ_H           PROJ
#      "3.10.2"        "3.4.1"        "8.2.1"         "true"         "true"        "8.2.1"

world <- gisco_countries %>%
  st_geometry() # no data are required...

# ugly!
plot(world)

a_better_world <- world %>%
  st_transform(crs = "+proj=eqearth")

# much nicer!
plot(a_better_world)


问:
convert time to unix timestamps since epoch and send it tyo server flutter
how can i convert datetime to unix time using datetimepicker package? I need user can choose the date and time and after their choice the chosen date and time convert to unix timestamp and send this timestamp to server.

Now I am trying something like this:

```<code>var dateUnix = DateTime.now().toUtc().millisecondsSinceEpoch.toString();
    child: DateTimePicker(
                    type: DateTimePickerType.dateTimeSeparate,
                    dateMask: 'EEE, d MMM yyyy HH:mm:ss',
                    initialValue: dateUnix
                    firstDate: DateTime(2000),
                    lastDate: DateTime(2100),
                    icon: Icon(Icons.event),
                    dateLabelText: 'Date',
                    timeLabelText: "Hour",
                    onChanged: (val) => print(val),
                    validator: (val) {
                      print(val);
                      return null;
                    },
                    onSaved: (val) => print(val),
</code>```

the output is still:

```<code>I/flutter (11990): 2022-02-07 12:10
</code>```

I need it aoutomatucally converted to unix-time:

```<code>Epoch timestamp: 1644235837
</code>```

答:
Use the following in your print statement:</p>
```<code>print(val.toUtc().millisecondsSinceEpoch.toString())
</code>```

Body:
how can i convert datetime to unix time using datetimepicker package? I need user can choose the date and time and after their choice the chosen date and time convert to unix timestamp and send this timestamp to server.

Now I am trying something like this:

var dateUnix = DateTime.now().toUtc().millisecondsSinceEpoch.toString();
    child: DateTimePicker(
                    type: DateTimePickerType.dateTimeSeparate,
                    dateMask: 'EEE, d MMM yyyy HH:mm:ss',
                    initialValue: dateUnix
                    firstDate: DateTime(2000),
                    lastDate: DateTime(2100),
                    icon: Icon(Icons.event),
                    dateLabelText: 'Date',
                    timeLabelText: "Hour",
                    onChanged: (val) => print(val),
                    validator: (val) {
                      print(val);
                      return null;
                    },
                    onSaved: (val) => print(val),

the output is still:

I/flutter (11990): 2022-02-07 12:10

I need it aoutomatucally converted to unix-time:

Epoch timestamp: 1644235837

Body:
Use the following in your print statement:

print(val.toUtc().millisecondsSinceEpoch.toString())


问:
Connect remote SQL azure from web app within the Vnet with service endpoints enabled
Hope you are doing well. I have a use case that I am trying to set up, but no success.

Let me explain it.

I have a premium web app integrated with azure vnet and connecting SQL azure using service endpoints (I have created a vnet rule for the SQL server by enabling the service endpoints). that works fine. no issue with that.

But there is a requirement that I need to connect a different SQL Azure database that resides in a different Azure tenant and subscription. and their SQL database is not publicly accessible. they are fine to whitelist the public IP that I am connecting to. I told the IP addresses of my azure web app, but it seems this doesn't use public IP when connecting remote SQL server when vnet integration and service endpoints are enabled. it tries to connect the database using private IP and service endpoints.

I have tried to create a private endpoint for remote SQL server within the network the web app resides, but it seems it does not work either (still trying.)

I am not sure the problem is clear but I need help if you have any idea.

Thanks.

答:
As your web app is integrated with VNET (VNET1), your web app will be able to connect to the resources that are connected to the VNET and the other peered VNETs

If you want to connect to Azure SQL which is placed in a VNET in different subscription and tenant (VNET2), you need to peer both the VNETs (VNET1 & VNET2)

To peer the virtual networks in different subscriptions and tenants, you can refer the below document:
Create a VNet peering - different subscriptions | Microsoft Docs


答:
You don't have any condition for the inner BEGIN...END. You can remove it.</p>
```<code>DECLARE @PROCESSEDCOUNT INT = 0
WHILE (@PROCESSEDCOUNT < 10)
BEGIN
    SET @PROCESSEDCOUNT +=1
        -- Stuff happens here
END
</code>```

Title: SQL nesting BEGIN END Blocks gives SQL Error (102)

Body:
You don't have any condition for the inner BEGIN...END. You can remove it.

DECLARE @PROCESSEDCOUNT INT = 0
WHILE (@PROCESSEDCOUNT < 10)
BEGIN
    SET @PROCESSEDCOUNT +=1
        -- Stuff happens here
END


问:
[PHP][MySQL]How To SELECT data with two constrain?
I'm new to PHP+MySQL programming

I want to SELCET data using tow constrain at once,

the cons1 is

```<code>Tid=user02 and Fid=user01
</code>```

and cons2 is

```<code>Tid=user01 and Fid=user02
</code>```

the data I want to output is something like:

```<code>$result1 = mysql_query("SELECT * FROM myTable WHERE Tid='user02' AND Fid='user01');
</code>```

+

```<code>$result2 = mysql_query("SELECT * FROM myTable WHERE Tid='user01' AND Fid='user02');
</code>```

= what I want

can it be done in single line?

or can make a result which stored $result1 and $result2

thanks for taking time reading my question

答:
Try this one:    </p>

```<code> $result1 = mysql_query("SELECT * FROM chat WHERE Tid='user02' AND Fid='user01'
                        UNION SELECT * FROM chat WHERE Tid='user01' AND Fid='user02'");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm new to PHP+MySQL programming

I want to SELCET data using tow constrain at once,

the cons1 is

Tid=user02 and Fid=user01

and cons2 is

Tid=user01 and Fid=user02

the data I want to output is something like:

$result1 = mysql_query("SELECT * FROM myTable WHERE Tid='user02' AND Fid='user01');

+

$result2 = mysql_query("SELECT * FROM myTable WHERE Tid='user01' AND Fid='user02');

= what I want

can it be done in single line?

or can make a result which stored $result1 and $result2

thanks for taking time reading my question

Body:
Try this one:

 $result1 = mysql_query("SELECT * FROM chat WHERE Tid='user02' AND Fid='user01'
                        UNION SELECT * FROM chat WHERE Tid='user01' AND Fid='user02'");