One form for multiple addresses in Symfony - Twig

First, I want to clarify that I do not use Entities / Doctrine for my forms (or even). I use webservices to add / edit data fields for the database

I am working on a project where I need to edit company information with several addresses. The first address is always a physical address, so I take it in the same cycle as the company data.

However, the second (and third, or fourth, if any) address is placed in a separate database record. I can edit the company data and the company address (physical address) using one form (since all the data is in one set). For this, I need only one form, and I do not need to use a loop for the address.


Now I want to edit the second address. I look at the addresses in twig and print out all the other addresses for this company. Since I know that Symfony does not allow multiple instances of the same form, because it is associated with an identifier, etc.

The question is how should I display the form for a specific address only. which I want to edit with the click of a button (use the bootstrap to collapse to hide the form if it is not being edited)

My code is as follows:

Controller:

public function editcompany(Request $request, $klantnr)
{

    [...]

    $result = [
        'gegevens' => [],
        'addresses' => [],
    ];

    foreach ($company as $row) {
        $dataFields = [
            [...] // The data fields of the company (including the physical address)
        ];
        foreach ($dataFields as $dataField) {
            if (empty($result['gegevens'][$dataField])) {
                $result['gegevens'][$dataField] = $row[$dataField];
            }
        }
        if($row['AdrGid'] != $result['gegevens']['AdrGid']) {
            $result['addresses'][$row['AdrGid']] = [
                [...] // The data fields for the other addresses 
            ];
        }
    }

    // The form creation of the company data form
    $form = $this->createForm(EditcompanyForm::class);

    // The form of the other addresses
    $form_adres = $this->createForm(EditcompanyAdresForm::class, array(
        [...]
    ));
    $form->handleRequest($request);
    $form_adres->handleRequest($request);


    if($form->isSubmitted() && $form->isValid()) {
        [...] // Handling the submitted data for the company data
    }

    // GEKOPPELDE ADRESSEN company
    if($form_adres->isSubmitted() && $form_adres->isValid()) {

        [...]

        $data = array(
            [...] // Setting the data for the other addresses
        );

        [...]

        // Passing the data and other options to the webservices
        $this->get('http')->companyRequest($data, $admincode, $service, $token);

        $request->getSession()
            ->getFlashBag()
            ->add('success', 'Linked address successfully edited');

        return $this->redirect($request->getUri());
    }

    return $this->render('pages/company/edit.html.twig', array(
        'client' => $result,
        'form_company' => $form->createView(),
        'form_company_adres' => $form_adres->createView()
    ));
 }

Formbuilder (AbstractType):

class EditcompanyAdresForm extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $factuuradres = $options['NawFactuurAdres'];
        $lands = $options['lands'];

        $data = array();
        $builder
            [...] // Add the necessary fields
    }
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            [...] // setting defaults here
        ));
    }
    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'appbundle_form_editcompanyadresform';
    }
}

Twig template (showing addresses:

{% for address in client.addresses %}
    <div class="right-cont-grey">
        [...] // showing addresses
    </div>
{% endfor %}

Twig template (edit form):

{% for address in client.addresses %}
    {{ form_start(form_company_adres, {'  method': 'POST'}) }}
    {{ form_row(form_company_adres._token) }}
        <section class="collapse" id="adres_plus">
            <div id="adres" class="new-adres collapse right-cont-grey">
                <div class="col-sm-12">
                    [...] // Form_widgets with values from database
            </div>
        </section>
    {{ form_end(form_company_adres) }}
{% endfor %}

In short:

? , () twig ? , .

+4
2

, :

, , . .

:

:

public function editCompanyAction(Request $request)
{
    // get the data anyway you see fit and produce a model (this could also be a dedicated DTO)
    $company = $this->getInput();

    // create the form
    $form = $this
        ->createForm(CompanyWithAddressesType::class, $company)
        ->handleRequest($request)
    ;

    // handle submission
    if ($form->isSubmitted() && $form->isValid()) {
        dump($form->getData()); // === $company
    }

    return $this->render('default/index.html.twig', [
        'form' => $form->createView(),
    ]);
}

, , !

class CompanyWithAddressesType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // combine the company with a collection of addresses:
        $builder
            ->add('gegevens', CompanyType::class)
            ->add('addresses', CollectionType::class, [
                'entry_type' => AddressType::class,
            ])
        ;
    }
}

class CompanyType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // all the fields that are *extra* for companies, address fields are inherited
        // because this type extends the address type (see below getParent)
        $builder
            ->add('NawWebsite', TextType::class)
            ->add('email1', TextType::class)
            ->add('AdrNaam1', TextType::class)
        ;
    }

    /**
     * @return @inheritdoc
     */
    public function getParent()
    {
        return AddressType::class;
    }
}

class AddressType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // all the fields that define an address
        $builder
            ->add('AdrStraat', TextType::class)
            ->add('AdrHuisnummer', TextType::class)
            ->add('AdrPostcode', TextType::class)
            ->add('NawFactuurAdres', CheckboxType::class)
        ;
    }
}

.

{{ form_start(form) }}
    <div>
        <h4>Company</h4>
        {{ form_row(form.gegevens.NawWebsite) }}
        {{ form_row(form.gegevens.email1) }}
        {{ form_row(form.gegevens.AdrNaam1) }}
    </div>

    <div>
        <h4>Main address</h4>
        {{ form_rest(form.gegevens) }}
    </div>

    <div>
        <h4>Extra addresses</h4>
        {% for address in form.addresses %}
            {{ form_errors(address) }}
            {{ form_widget(address) }}
        {% endfor %}
    </div>

    <button>Submit</button>
{{ form_end(form) }}
+1

, , , , . , , . , Javascript .

Twig ( ):

{{ form_start(form_company_adres, {'  method': 'POST'}) }}
{% for address in client.addresses %}
    <div id="address-{{ loop.index }}" class="address">
        <input type="hidden" name="address-number" value="{{ loop.index }}"/>
        {{ form_row(form_company_adres._token) }}
            <section class="collapse" id="adres_plus">
                <div id="adres" class="new-adres collapse right-cont-grey">
                    <div class="col-sm-12">
                        [...] // Form_widgets with values from database
                </div>
            </section>
    </div>
{% endfor %}
{{ form_end(form_company_adres) }}
0

Source: https://habr.com/ru/post/1690855/


All Articles