How could I cast to DateTimeInterface from String?? Symfony Ajax - javascript

My real problem is that I am sending an Ajax Jquery Request to an API of mine, the server response is 'Argument #1 of ::setDate() must be DateTimeInterface, string given'
I tried to cast but it was useless.
My Ajax at JQUERY:
$.ajax({
type: "PUT",
url: "/api/distribucion",
data: JSON.stringify(dist),
dataType: "json",
success: function (response) {
console.log("mesa " + response.id + " actualizada");
}
});
My API at PHP (Symfony's controller):
public function putDistribucion(ManagerRegistry $mr, Request $request): Response
{
$datos = json_decode($request->getContent());
$datos = $datos->distribucion;
// Cogemos el ID de el Distribucion a editar
$id = $datos->id;
// Obtenemos el Distribucion
$distribucion = $mr->getRepository(Distribucion::class)->find($id);
// Cambiamos todos sus campos
$distribucion->setPosicionX($datos->pos_x);
$distribucion->setPosicionY($datos->pos_y);
$distribucion->setFecha($datos->fecha);
$distribucion->setMesaId($datos->mesa_id);
$distribucion->setAlias($datos->alias);
$distribucion->setReservada($datos->reservada);
$manager = $mr->getManager();
try {
// Lo mandamos a actualizar
$manager->persist($distribucion);
$manager->flush();
} catch (PDOException $e) {
$this->json(['message' => $e->getMessage(), "Success" => false], 400);
}
# Creado con éxito => Devolvemos la ID
return $this->json(
[
"message" => "Éxito al editar la distribucion " . $id,
"Success" => true
],
202 // Aceptado
);
}
The Object I'm sending:

Your entity Distribucion probably has a setter that look like this:
public function setFecha(DateTimeInterface $fecha): self
{
$this->fecha = $fecha;
return $this;
}
The setter is typehinted with DateTimeInterface so you need to use a DateTime object and not a string.
You may create a DateTime easily with DateTime::createFromFormat
So $distribucion->setFecha($datos->fecha); will turn into something like:
$distribucion->setFecha(DateTime::createFromFormat('YYYY-MM-DD HH:ii:ss.u', $datos->fecha));
You may want to verify the date format I used as the first parameter of DateTime::createFromFormat
public static DateTime::createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null)

Related

I can't create a file download controller

When I try to use the .pipe() function in my controller I get an error and I don't know why. Attached my code below, thank you very much for the help in advance
const fs =require('fs');
module.exports={
inputs:{
name_file:{
type:"string",
required:true
}
},
exits: {
success: {
description: "Return matching data.",
},
defaultError: {
description: "It catches any error.",
responseType: "defaultError",
},
},
fn:function (inputs,exits){
//Comprobamos si el fichero viene en la peticion
if (!inputs.name_file) return exits.defaultError("No se ha adjuntado el nombre del archivo")
var nameFile=inputs.name_file
//Creamos ruta completa del fichero
var URL_FILE=process.cwd()
URL_FILE= URL_FILE.concat("\\.tmp\\uploads\\",nameFile,'.csv')
//Comprobamos si el fichero existe
fs.access(URL_FILE,fs.constants.F_OK,(err)=>{
return "El fichero no existe"
})
var response={}
var SkipperDisk = require('skipper-disk');
var fileAdapter = SkipperDisk(/* optional opts */);
// Stream the file down
var filedown=fileAdapter.read(URL_FILE)
filedown.on('error', function (err){
return exits.defaultError(err);
})
filedown.on('line',(linea)=>{
console.log(linea)
})
filedown.pipe(exits.success(response))
}
}
TypeError: Cannot read property 'on' of undefined```

Wordpress how to use Ajax to show new data returned from successful insert_post()?

After a successful Ajax insert of an entry, I would like to see what the ID and url of that same entry is and display it in a modal window without refreshing the page
Any way to get this data from success: function (response) {}? This is the code I have to make a new entry with ajax which works perfect:
<script>
$("#enquiry_email_form").on("submit", function (event) {
event.preventDefault();
var form= $(this);
var ajaxurl = form.data("url");
var detail_info = {
post_title: form.find("#post_title").val(),
post_description: form.find("#post_description").val()
}
if(detail_info.post_title === "" || detail_info.post_description === "") {
alert("Fields cannot be blank");
return;
}
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
post_details : detail_info,
action: 'save_post_details_form' // this is going to be used inside wordpress functions.php// *esto se utilizará dentro de las functions.php*
},
error: function(error) {
alert("Insert Failed" + error);
},
success: function(response) {
modal.style.display = "block"; * abre la ventana modal*
body.style.position = "static";
body.style.height = "100%";
body.style.overflow = "hidden";
}
});
})
</script>
<button id="btnModal">Abrir modal</button>
<div id="tvesModal" class="modalContainer">
<div class="modal-content">
<span class="close">×</span> <h2>Modal</h2> * Ventana modal mostrar le url y ID generado *
<p><?php ***echo $title_post, $url, $ID*** ?></p>
</div>
</div>
Archive funtions.php
function save_enquiry_form_action() {
$post_title = $_POST['post_details']['post_title'];
$post_description = $_POST['post_details']['post_description'];
$args = [
'post_title'=> $post_title,
'post_content'=>$post_description,
'post_status'=> 'publish',
'post_type'=> 'post',
'show_in_rest' => true,
'post_date'=> get_the_date()
];
$is_post_inserted = wp_insert_post($args);
if($is_post_inserted) {
return "success";
} else {
return "failed";
}
}
When you use wp_insert_postDocs function, it'll return the post id.
It returns the post ID on success. The value 0 or WP_Error on failure.
First you could initiate an empty array and call it, let's say, $response and populate it based on the returned value from wp_insert_post function.
Then, we could use the id to get the permalink as well, using get_permalinkDocs.
And at last, we could send that array back to the client-side by using wp_send_json_successDocs function.
So your code on the php side would be something like this:
function save_enquiry_form_action() {
$response = array(
'error' => '',
'success' => '',
'post_id' => '',
'post_url' => '',
);
$post_title = sanitize_text_field($_POST['post_details']['post_title']);
// Note we could have used 'sanitize_title()' function too!
$post_description = sanitize_textarea_field($_POST['post_details']['post_description']);
$args = array(
'post_title' => $post_title,
'post_content' => $post_description,
'post_status' => 'publish',
'post_type' => 'post',
'show_in_rest' => true,
'post_date' => get_the_date()
);
$post_id = wp_insert_post($args);
if($post_id){
$response['success'] = true;
$response['error'] = false;
$response['id'] = $post_id;
$response['post_url'] = get_permalink($post_id);
}else{
$response['success'] = false;
$response['error'] = true;
}
wp_send_json_success($response);
exit;
}
Note:
I've used sanitize_text_fieldDocs function to sanitize the $_POST['post_details']['post_title'] value and sanitize_textarea_fieldDocs function to sanitize the $_POST['post_details']['post_description'] value.
When you receive the response on the client-side, you could check for $response['success'] and $response['error'] values.
On the javascript side
As you can see on the following screenshot, data returns as data object. To access data you could use response.data.success, response.data.error, response.data.id and response.data.post_url.

Symfony form validation from an AJAX render

I'm new to symfony, I render forms throughout a JSON so whenever I click on an icon it shows different forms (to change firstname, lastname...).
I return thoses forms as a JSON :
public function profileSettings()
{
$user = $this->getUser();
// Formulaire d'informations concernant le compte
$formAccountSettings = $this->createForm(AccountSettingsType::class, $user, [
'userEmail' => $user->getEmail(),
'userUsername' => $user->getUsername(),
]);
// Formulaire d'informations personnel
$formPersonnalSettings = $this->createForm(PersonnalSettingsType::class, $user, [
'userFirstname' => $user->getFirstname(),
'userLastname' => $user->getLastname(),
]);
// Retour en format JSON des 3 requêtes sous tableau
return $this->json(
[
'formAccountSettingsView' =>
$this->render('user/_accountSettings.html.twig', [
'form' => $formAccountSettings->createView(),
]),
'currentUser' => $user,
'formPersonnalSettingsView' => $this->render('user/_accountSettings.html.twig', [
'form' => $formPersonnalSettings->createView(),
]),
]
);
}
Here is how I display this :
$('#settings-user li').on('click', function (e) {
$.ajax({
type: 'GET',
url: "/website-skeleton/public/index.php/json/profile",
success: function (response) {
if ($(e.target).hasClass('profile')) {
$('.display').empty().append(
`
<p id="welcome">Bonjour, <em><strong>${response['currentUser']['username']}</strong></em> vous êtes enregistré sous le nom de <strong>${response['currentUser']['firstname']} ${response['currentUser']['lastname']}</strong>.
<br>
Votre adresse email est : <strong>${response['currentUser']['email']}</strong>.
<br>
Pour modifiez vos informations veuillez cliquez sur le menu de navigation.
</p>`);
} else if ($(e.target).hasClass('security')) {
$('.display').empty().append(response['formAccountSettingsView']['content']);
} else if ($(e.target).hasClass('informations')) {
$('.display').empty().append(response['formPersonnalSettingsView']['content'])
}
}
})
});
The problem now is that I don't know how to handle thoses forms from another controller and validate it with the constraints I set on my entity User this is how I validate :
public function editCredentials(Request $request, UserPasswordEncoderInterface $encoder)
{
$user = $this->getUser();
$formPersonnalSettings = $this->createForm(PersonnalSettingsType::class, $user);
if ($request->isMethod('POST')) {
if ($request->request->has('personnal_settings')) {
if ($formPersonnalSettings->isSubmitted() && $formPersonnalSettings->isValid()) {
$user->setFirstname($request->request->get('personnal_settings')['firstname']);
$user->setLastname($request->request->get('personnal_settings')['lastname']);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->addFlash('personnal_success', 'Vos informations personnels ont bien été enregistrées !');
return $this->redirectToRoute('user_profile');
}
}
Is that a good method? should I handle everything with ajax ? Thanks for your time !
You should use the handlerequest which automatically sets the values in the form to the entity added to it once the form has been submitted.
$form = $this->createCreateForm($entity); // private function to create the form
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$em->persist($entity);
$em->flush();
}
}
return $response;
Once handled you just need to return an ok response, or return the form back to the view if something has gone wrong.
If I remember well, the asserts set on the entity are also automatically processed with the handleRequest(), it depends on how you declared them.
Yo can also add other errors after the submit, just add them between the isSumbmitted() and isValid(). Documentation
I leave you here some documentation that may help.
Handle request
Validation
Validation in the form itself

Getting json from an URL and displaying specific data

I got a problem when I try to get the json from an URL in my reverse geocoding method :
I tried this based on a solution found on stackoverflow.
When I try to show the json in my alert it shows: undefined
adressReverseGeoCode(item: any, elementId: any) {
var getJSON = (url: any, callback: any) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = () => {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON('http://nominatim.openstreetmap.org/reverse?format=json&lat=' + item.latitude + '&' + 'lon=' + item.longitude + '&addressdetails=1',
(err: any, data: any) => {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
alert(data.result);
}
});
}
I want to get the "display_name" from the json in order to put it in a text input later.
You can try this link to see the json file
{
"place_id":"154253419",
"licence":"Data © OpenStreetMap contributors, ODbL 1.0. http:\/\/www.openstreetmap.org\/copyright",
"osm_type":"way",
"osm_id":"424211755",
"lat":"-23.56183",
"lon":"-46.6598392",
"display_name":"Alameda Ministro Rocha Azevedo, Jardim Paulista, São Paulo, Microrregião de São Paulo, RMSP, Mesorregião Metropolitana de São Paulo, São Paulo, Southeast Region, 01410-001, Brazil",
"address":{"road":"Alameda Ministro Rocha Azevedo","suburb":"Jardim Paulista","city_district":"Jardim Paulista","city":"São Paulo","county":"Microrregião de São Paulo","state_district":"Mesorregião Metropolitana de São Paulo","state":"São Paulo","postcode":"01410-001","country":"Brazil","country_code":"br"},
"boundingbox":["-23.5642064","-23.5601209","-46.662319","-46.6580485"]
}
Thank you in advance for any help you can give me !
There is not data.result! thats why it is undefined. Your data is the JSON. so just do data.display_name. Probably!
var obj = JSON.parse(data); // as suggested by #charlietfl
console.log(obj.display_name);
alert(obj.display_name);

POST 500 (Internal Server Error) when I use the JEditable plugin

I'm trying to use JEditable plugin in my Symfony2 application. PYS entity is a a films and TV shows entity; then I've got Usuario and Critica entities. I want to manage the user's critics with the plugin. I've analyzed more and more examples, but I can not get it to work. The value (in this case the title of critic) is update in the template but not in the db; when I refresh the browser the old value appears.
THE ERROR:
This is my JS:
$('.edit').editable(function(value, settings) {
var data = {};
data[this.id] = value;
console.log(path);
console.log(data);
$.post(path, data);
return(value);
}, {
indicator : 'Saving...',
tooltip : 'Click to edit...'
});
This is the route:
critica_ajax:
locales: { es: "/gestion-critica/{pysStr}/", en: "/manage-critic/{pysStr}/" }
defaults: { _controller: UsuarioBundle:Default:gestionarCritica }
This is the controller:
public function gestionarCriticaAction($pysStr)
{
$em = $this->getDoctrine()->getManager();
$pys = $em->getRepository('PYSBundle:Pys')->findPys($pysStr);
$usuario = $this->get('security.context')->getToken()->getUser();
$critica = $em->getRepository('UsuarioBundle:Usuario')->findCritica($usuario, $pys);
if(!$critica)
{
$critica = new Critica($usuario, $pys);
}
$criTitulo = $this->request->get('value');
$critica->setCriTitulo($criTitulo);
$critica->setCriContenido($criContenido);
$critica->setCriFecha(new \DateTime("now"));
$em->persist($critica);
$em->flush();
return new Response($criTitulo);
}
The Twig template:
<h2 class="edit">{{ critica.criTitulo }}</h2>
<script>
var path = "{{ path('critica_ajax', { 'pysStr': pelicula.pysStr}) }}";
</script>
EDIT (The Symfony's return)
Notice: Undefined property: Filmboot\UsuarioBundle\Controller\DefaultController::$request
in C:\Programming\xampp\htdocs\filmboot\src\Filmboot\UsuarioBundle\Controller\DefaultController.php line 236
THIS IS THE LINE 236: $criTitulo = $this->request->get('value');
at ErrorHandler ->handle ('8', 'Undefined property: Filmboot\UsuarioBundle\Controller\DefaultController::$request', 'C:\Programming\xampp\htdocs\filmboot\src\Filmboot\UsuarioBundle\Controller\DefaultController.php', '236', array('pysStr' => 'machete', 'em' => object(EntityManager), 'pys' => object(Pys), 'usuario' => object(Usuario), 'critica' => object(Critica)))
in C:\Programming\xampp\htdocs\filmboot\src\Filmboot\UsuarioBundle\Controller\DefaultController.php at line 236 +
at DefaultController ->gestionarCriticaAction ('machete')
at call_user_func_array (array(object(DefaultController), 'gestionarCriticaAction'), array('machete'))
in C:\Programming\xampp\htdocs\filmboot\app\bootstrap.php.cache at line 1003 +
at HttpKernel ->handleRaw (object(Request), '1')
in C:\Programming\xampp\htdocs\filmboot\app\bootstrap.php.cache at line 977 +
at HttpKernel ->handle (object(Request), '1', true)
in C:\Programming\xampp\htdocs\filmboot\app\bootstrap.php.cache at line 1103 +
at ContainerAwareHttpKernel ->handle (object(Request), '1', true)
in C:\Programming\xampp\htdocs\filmboot\app\bootstrap.php.cache at line 413 +
at Kernel ->handle (object(Request))
in C:\Programming\xampp\htdocs\filmboot\web\app_dev.php at line 26 +
You need to get the request like this :
$request = $this->getRequest();
instead of
$request = $this->request;
the request is returned using a method its not a class property

Categories