Hi there, I wrote a Form Object, that is using Googles map Autocomplete Module, to Enter an address and get suggestions and GeoLocation after selecting one of the suggestions.
I want to use this FormField inside the CMSForm a a Page Object.
The necessary Javascript gets required on the Field Method.
/**
* @return string
*/
function Field($properties = array()) {
$mapsApiUrl = (GoogleMaps::getApiKey())?'https://maps.googleapis.com/maps/api/js?js?v=3.exp&signed_in=true&sensor=false&libraries=places&language='.i18n::get_tinymce_lang().'&key='.GoogleMaps::getApiKey():'https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&sensor=false&libraries=places&language='.i18n::get_tinymce_lang();
$name = $this->name;
$js = <<<JS
console.log('executed');
(function($){
console.log('executed');
function initializeGoogleMaps(){
var autocomplete;
// Create the autocomplete object, restricting the search
// to geographical location types.
autocomplete = new google.maps.places.Autocomplete(
(document.getElementById('{$name}-Address')),
{ types: ['geocode'] }
);
// When the user selects an address from the dropdown,
// populate the address fields in the form.
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
$("#{$name}-Latitude").val(place.geometry.location.lat());
$("#{$name}-Longditude").val(place.geometry.location.lng());
});
}
function loadGoogleMapsScript(){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '{$mapsApiUrl}' +
'&callback=initializeGoogleMaps';
document.body.appendChild(script);
}
window.initializeGoogleMaps = initializeGoogleMaps;
window.onload = loadGoogleMapsScript;
})(jQuery);
JS;
Requirements::customScript($js, 'GeoLocationField_Js_'.$this->ID());
$css = <<<CSS
/* make the location suggest dropdown appear above dialog */
.pac-container {
z-index: 2000 !important;
}
CSS;
Requirements::customCSS($css, 'GeoLocationField_Css_'.$this->ID());
return "<div class=\"fieldgroup\">" .
$this->fieldLatitude->Field() . //SmallFieldHolder() .
$this->fieldLongditude->Field() . //SmallFieldHolder() .
"<div class=\"fieldgroupField\">" . $this->fieldAddress->Field() . "</div>" .
"</div>";
}
My Problem ist, that the Javascript doesn't get loaded, when I'm selecting the Page by traversing the pages tree inside the CMS Backend. Only after a Pagereload the Javascript gets loaded. Also when the Javascript was loaded by Pagereload and I submitted the form (or selected another page), the javascript needs to be executet again (which does not happen automatically) to bind the new ajax loaded form elements to the desired method.
How can I achieve my desired behaviour?