Assign value to twig variable using JavaScript in Symfony version 3.4

Hello everyone, I am currently working on a form that is functioning well. However, I am facing an issue with setting the localization of a place manually using latitude and longitude values. To address this, I decided to create a map with a draggable marker. When I move the marker, the lat and lng values change in the console. Now, my goal is to dynamically set these updated values in the form so that they can be saved properly. Specifically, I want the latitude field to reflect the lat value and the longitude field to reflect the lng value.

Below is the HTML structure of my form (using Twig with Symfony):

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

{% block body %}
<!-- Left and right buttons -->
<div class="col-8 mx-auto">
    <br/><br/><br/><br/>
    <div class="card">
        <div class="card-header header-elements-inline">
            <h6 class="card-title">Create a place</h6>
        </div>
        <br/>
        <div class="card-body">
            {{ form_start(form) }}
            <div class="form-group">
                <label for="form_username">Content :</label>
                {{ form_widget(form.content) }}
            </div>
            // Other form fields here...
            <div class="form-group">
                <label for="form_username">Longitude:</label>
                {{ form_widget(form.longitude) }}
            </div>
            <div class="form-group">
                <label for="form_username">Latitude:</label>
                {{ form_widget(form.latitude) }}
            </div>

            <div class="card px-3">
                <br/>
                <div class="map-container" id="map_marker_simple"></div>
                    {% block javascripts_map %}
                    {% endblock %}
                <br/>
            </div>
            </div>
            // Submit button and ending form tag
        </div>
    </div>
</div>
// Additional content

In addition, below is my JS script handling the form:

{% extends 'admin/user/new_place.html.twig' %}
{% block javascripts_map %}
<script type="text/javascript">
// JavaScript code for working with Google Maps and markers
// Initialize module functions
var GoogleMapMarkerBasic = function() {

    var _googleMapMarkerBasic = function() {
        if (typeof google == 'undefined') {
            console.warn('Warning - Google Maps library is not loaded.');
            return;
        }

        function initialize() {
            var map_marker_simple_element = document.getElementById('map_marker_simple');
            var myLatlng = new google.maps.LatLng(('{{ place.latitude }}'), ('{{ place.longitude }}'));
            var mapOptions = {
                zoom: 10,
                center: myLatlng
            };

            var map = new google.maps.Map(map_marker_simple_element, mapOptions);
            var contentString = 'Marker';

            var infowindow = new google.maps.InfoWindow({
                content: contentString
            });

            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                draggable: true,
                title: ('{{ place.title }}'),
                animation: google.maps.Animation.DROP
            });

            marker.addListener('drag', function() {
                infowindow.open(map,marker);
                var lat = marker.getPosition().lat();
                var lng = marker.getPosition().lng();
                console.log(lat, lng)
            });
        };

        google.maps.event.addDomListener(window, 'load', initialize);
    };

    return {
        init: function() {
            _googleMapMarkerBasic();
        }
    }
}();

document.addEventListener('DOMContentLoaded', function() {
    GoogleMapMarkerBasic.init();
});
</script>
{% endblock %}

This screenshot shows how the form appears visually:

https://i.sstatic.net/fdd0l.png

Thank you in advance to anyone who can provide assistance with this matter. :)

Answer №1

To update the latitude and longitude values, simply modify the input fields using JavaScript.

For plain JavaScript:

document.getElementById("latitudeInput").value = marker.getPosition().lat();
document.getElementById("longitudeInput").value = marker.getPosition().lng();

Using jQuery:

$("#latitudeInput").val(marker.getPosition().lat());
$("#longitudeInput").val(marker.getPosition().lng());

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

No elements can be located within the iframe as per Cypress's search

I've been attempting to access elements within an iframe using the guidance provided in this article here, but I'm facing an issue where Cypress is unable to locate anything within the iframe. Below is a snippet of my test code: describe('s ...

Incorporating Only XSD Files into an HTML Input Tag: A Simple Guide

Is there a way to restrict a file input element to only display XSD files? I attempted the following: <input type="file" accept="text/xsd" > Unfortunately, this method is not working as it still allows all file formats to be disp ...

A simple guide to fetching JSON data and storing it in a variable, then parsing it and displaying it

I am looking to retrieve JSON data from the Yahoo Finance API, store it in a JavaScript variable, extract specific information such as "name" and "price", and then display it in an HTML table. The JSON data can be accessed via the following link: Current ...

Dynamically created HTML elements have no events attached to them in Angular and jQuery

Utilizing jQuery, I am dynamically generating new elements within an Angular Form that has been constructed using a Template Driven Forms approach. Despite successfully creating the dynamic elements, they do not seem to be assigned events/callbacks due to ...

Avoiding double tapping to zoom on Chrome Android while using the desktop version of a website

Is there a way to disable zooming when double clicking in Google Chrome with the desktop site enabled? I attempted to use <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> without success. I al ...

Learn how to default export React with withRouter, all while taking advantage of Material UI's makeStyles

I have been working on integrating Material UI makeStyles with class components, passing useStyles as props while default exporting it in an arrow function. export default () => { const classes = useStyles(); return ( <LoginClass classes={cl ...

Can someone explain why I can't find yarn dlx? And can you please provide instructions on how to run the yarn

After installing yarn with brew install yarn, I attempted to run yarn dlx storybook@latest upgrade. However, the result showed an error: yarn run v1.22.22 error Command "dlx" not found. info Visit https://yarnpkg.com/en It seems that commands like yarn ad ...

What steps are needed to have AJAX retrieve data from the controller within an MVC framework?

So, I am struggling with making an AJAX call in my project. I need to return a string as a JSON object from the controller back to the view where the ajax call is made. Despite numerous attempts, I have been unable to achieve this successfully. My main que ...

Converting a PHP array to a JavaScript array causes an issue of undefined variable when attempting to access a PHP array that has

I've been searching through other questions without finding the answer, so I'm reaching out for help with my specific issue. My problem is transferring a php array to a javascript array. In my code editor (phpStorm), I'm getting an error st ...

Issue with Angular UI-Router nested views: Content not displaying

I'm attempting to incorporate nested views for a webpage using angular ui-router. I have set up the state definitions according to various tutorials, but I am unable to display any content in the child views. Surprisingly, there are no errors showing ...

What are some creative ways to visually distinguish a TextField that is in readOnly mode?

I'm currently working on creating a form using the Material-UI library. I'm having difficulty figuring out how to distinguish my TextField when they are in readOnly mode versus edit mode. At the moment, they appear identical and I would like the ...

Updating a specific field in a document using Node.js and MongoDB

Hey, I'm a beginner in nodeJS and I could use some help. I've been able to update an entire document easily but I'm struggling to update just a single value. Here's my code: router.patch("/:id", async (req, res) => { console.log(re ...

Express JS res.send() with an array response data is posing a concern during the Checkmarx scan

When using the axios library in my express middleware to retrieve responses from APIs, I encountered a security concern raised by Checkmarx scan report. router.post(someurl,req,res) { axios .get(someurl) .then((response=>{ **res.send(response.data);**/ ...

What could be causing my randomly generated value to be overwritten so quickly?

I'm encountering an issue with my code. I am attempting to generate objects in random locations using drawHyperBall(), getRandomIntX(), and getRandomIntY(). However, the random value seems to be constantly overwritten. How can I resolve this problem? ...

The array used within the useEffect hook and the getCoordinates function appears to be distinct when printed with console

Utilizing GoogleMap API for Custom Location Display I have an imported array of JSON objects named data which includes an address property. The Google Maps API is used to retrieve coordinates from the addresses in order to generate custom markers displaye ...

Challenges arising with the express search feature

Currently, I am in the process of developing an API for a to-do application. I have successfully implemented the four basic functions required, but I am facing some challenges with integrating a search function. Initially, the search function worked as exp ...

Incorporate AJAX into your Javascript code for ordering

My issue arises when pointOnMap() is executed before xmlPreparer(), even though they are called in the correct order. I suspect this has something to do with the use of AJAX, as parseXML creates the object that pointOnMap() requires to be initialized befor ...

Verify Radio Buttons in AngularJS

I thought validating a selection from a radio group would be simple, but I'm struggling to find the right solution. In my form, I need to ensure that at least one option is selected from the radio buttons. Using the 'required' attribute on e ...

I am unable to populate MongoDB references using Node.js

I need to display the user's location details on the screen. For example: name: "Andy" surname : "Carol" City : "Istanbul" Town : "Kadıkoy" When the getuser function is called, I want to show the City and Town name. This is the implementation: U ...

Troubleshooting: Why Won't My Basic JQuery POST Request Work?

Can someone help me figure out how to use JQuery to send a POST request and display the data in a PHP file? Here is the HTML file: <html> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> ...