Quantcast
Channel: Active questions tagged symfony4 - Stack Overflow
Viewing all articles
Browse latest Browse all 3925

Symfony 4 - How to display data and form in the same page?

$
0
0

I want to display the form and the data which is from BIN database file. I want to let the user enter the IP address, so they will get the information. However, it only shows the form, can't show the result out.

Here is the code in Controller.php:

class DefaultController extends AbstractController
{
    /**
     * 
     * @Route("/default", name="default")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function index(Request $request)
    {
        $db = new \IP2Location\Database('./Database/IP2LOCATION.BIN', \IP2Location\Database::FILE_IO);

        $form = $this->createFormBuilder()
        ->add('ip', TextType::class, [
            'attr' => [
                'class' => 'form-control'
            ]
        ])
        ->add('submit', SubmitType::class, [
            'attr' => [
                'class' => 'btn btn-primary'
            ]
        ])
        ->getForm();

        $form->handleRequest($request);

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

            $db = $form->getData();
            $records = $request->request->get('ip');
            $records = $db->lookup('ip', \IP2Location\Database::ALL);
        }

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

Here is the code in form.html.twig

{% extends 'base.html.twig' %}

{% block body %}
<h3>IP2Location Symfony Demo</h3>
<form action="" method="POST">
    <table>
         <tr>
             <td>IP Address: </td>
             <td>{{form_widget(form.ip)}}</td>
             <td><input type="submit" value="Submit" name="submit"/></td>
        </tr>
    </table>
</form>
{% if form.submit is defined %}
{% for records in records %}

<table class="table table-bordered table-striped">
        <tbody>
            <tr>
                <td>IP Number: </td>
                <td>{{ records.ipNumber }}</td>
            </tr>
            <tr>
                <td>IP Version: </td>
                <td>{{ records.ipVersion }}</td>
            </tr>
            <tr>
                <td>IP Address: </td>
                <td>{{ records.ipAddress }}</td>
            </tr>
        </tbody>
    </table>

{% endfor %}
{% endif %}
{% endblock %}

Does anyone have any advise on how to go about this?


Viewing all articles
Browse latest Browse all 3925

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>