I send data with this code to JS:
$user = User::where('id' , $this->selectedItem)->first();
$this->dispatchBrowserEvent('userModal', [
'name' => $user->name,
'signup' => jdate($user->created_at),
]);
jDate() Is a function to convert to Persian date
but in frontend for signup I will receive a empty value
and this is JS code to receive data :
window.addEventListener('userModal', event => {
console.log(event.detail);
});
I would suggest to simply use Carbon instead of jDate().
'signup' => \Carbon\Carbon::parse($user->created_at)->setTimezone('Asia/Tehran'),
Related
I've tried checking the data and console logging it and the data exist , but when I check the request from the back-end it was not passed . Is this how we pass data to the back-end service in angular ? or I have issue with my code ? Thanks.
Code
checkExistingFeedbackRequest(formGroup: FormGroup, respondents: Identity[]): Observable<FeedbackRequest[]> {
let request = formGroup.value
const data = respondents
.map(respondent => cleanUpFeedbackRequestAssociations({
...request,
respondent,
respondentId: respondent.id
}) as FeedbackRequest);
console.log("data:" , data)
return from(this.service.find<FeedbackRequest>(data)
.pipe(
map((result) => result.data)
);
}
It's my first time with JQuery and Ajax validation in Laravel. I'm trying to validate a form using Laravel Request rules.
Seems the server validate the fields because it sends me back the errors when I don't fill up the requests ones but when I do it I get this error on the console SyntaxError: JSON Parse error: Unrecognized token '<'
That's the code I wrote:
TechnicianFormRequest
public function rules()
{
return [
'nome' => 'required',
'cognome' => 'required',
'ruolo_principale' => '',
'antincendio' => '',
'primosoccorso' => '',
'rischioelettrico' => '',
'lavoroinquota' => '',
//
];
TechnicianController (store method)
public function store(TechnicianFormRequest $request)
{
$validated = $request->validated();
$technician = Tecinfo::create($validated);
return redirect()->action('TechnicianController#index')->with('success', 'Tecnico aggiunto con successo!');
// return dd($request->all());
}
Ajax Code:
(can't paste js code, so I add a pic)
Ajax code image
Thank you to everyone who will help me
Valerio
You are parsing Json in your ajax but not returning json from your store method
As Per Laravel Documentation:
The json method will automatically set the Content-Type header to application/json, as well as convert the given array to JSON using the json_encode PHP function
Use below in your controller to return json
return response()->json([
'success' => 'Tecnico aggiunto con successo!',
]);
I'm trying to set a default value in an input. The value is sent from the Controller to the Twig as shown below
ClienteController.php
$loc_default = $em->getRepository('AppBundle:Localidad')->findOneBy(
array('nombre' => 'aaaa'));
$localidad_default = $loc_default;
return $this->render('cliente/new.html.twig', array(
'localidad_default' => $localidad_default,
'form' => $form->createView(),
'form2' => $form2->createView(),
));
and this is my Twig View with the javascript line
$("#appbundle_cliente_localidad").val({{localidad_default['localidad_default']}});
but it shows the following error
Impossible to access a key "localidad_default" on an object of class "AppBundle\Entity\Localidad" that does not implement ArrayAccess interface.
Thanks for the answer
Try this:
$loc_default = $em->getRepository('AppBundle:Localidad')->findOneBy(array(
'nombre' => 'aaaa')
);
$localidad_default = $loc_default->getSomething();
return $this->render('cliente/new.html.twig', array(
'localidad_default' => $localidad_default,
'form' => $form->createView(),
'form2' => $form2->createView(),
));
And in the template:
$("#appbundle_cliente_localidad").val({{ localidad_default }});
Change getSomething() to a valid public method of your Localidad entity!
Or if you need the whole entity in your twig template:
$loc_default = $em->getRepository('AppBundle:Localidad')->findOneBy(array(
'nombre' => 'aaaa')
);
return $this->render('cliente/new.html.twig', array(
'localidad_default' => $loc_default,
'form' => $form->createView(),
'form2' => $form2->createView(),
));
And in the template:
$("#appbundle_cliente_localidad").val({{ localidad_default.something }});
In my opinion is too much code, if the controller sends the default data from the same action the form is sended just set the value at form or controller like this:
Inside the form
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name',TextType::class,[
'attr'=>[
'value' => 'some_default_value'
]
]);
}
Inside the controller
...
$form = $this->createForm('AppBundle\Form\SomeFormType', $data);
$form->get('somefield')->setData('default_data');
...
This way is better for you, less code and test. Also if you need to access database or something it is easier.
Hope it helps!
I've managed to get x-editable (https://vitalets.github.io/x-editable/) to work with a page, in so far as when I click on a field, it displays inline and I can edit it, and I'm able to successfully submit to a POST URI.
The idea here is that I'm sending three key-value pairs:
array:3 [▼
"name" => "name"
"value" => "mathematics"
"pk" => "1"
]
and my update() method catches the array, and it successfully updates the record in the database. But I'm failing to validate the data.
This is how my controller looks:
public function update(Request $request)
{
//
$id = $request->pk;
$subject = Subject::findOrFail($id);
$rules = array (
'name' => 'bail|required|max:20|unique:subjects,name,'.$id
);
This validation pass easily even if I try to fail it
$validator = Validator::make ( $request->all(), $rules );
if ($validator->fails ()) {
return response()->json ( array (
'errors' => $validator->getMessageBag ()->toArray ()
) );
} else {
$subject->update([$request->name => $request->value]);
}
return response ()->json ( $subject );
}
So it's as if I'm somehow not passing the "correct" Request object to validate()? There is no form submission, but the documentation clearly states that:
Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.1
Route:
Route::post('/subjects/update/', 'SubjectsController#update');
script:
$('#subjects').editable({
container:'body',
selector:'td.name',
type:'post',
dataType:'JSON',
validate:function(value){
if ($.trim(value) === '') {
return "Field is required";
}
}
});
1https://laravel.com/docs/5.4/validation#quick-ajax-requests-and-validation
If I'm not mistaken, name is the field to be edited (the DB column), and value is, well, the value. It looks like you are updating the name column, so you have to validate the uniqueness of the value in the request, not the "name".
Also, I'd suggest you use the validate method of your controller (provided by the ValidatesRequests trait):
public function update(Request $request)
{
$id = $request->pk;
$subject = Subject::findOrFail($id);
$this->validate($request, [
'name' => 'required', // this should be the column to update
'value' => 'bail|required|max:20|unique:subjects,name,'.$id
];
$subject->update([$request->name => $request->value]);
return $subject;
}
Here validate will automatically reject with a 422 code and the validation errors in the JSON response. If it passes, it will continue with the update. (return $subject also returns a JSON representation of the object in the response.)
i am using laravel with pusher to send an event message to pusher. the code is in my controller which is a post controller, triggered when an input form is submitted. below is my code. what am i doing wrong? there is no event received.
this is an ajax call route based controller.
$pusher = new Pusher( env('PUSHER_KEY'), env('PUSHER_SECRET'), env('PUSHER_APP_ID'), array( 'encrypted' => true ) );
$pusher->trigger( 'test_channel', 'my_event', 'hello world' );
I am also assuming you have set up your Pusher account correctly and that your environment variables are correct.
If so, you may need to ensure you are using the correct Cluster (the default is fine for the US, but outside the East coast of the US for example, the cluster must be explicitly defined).
Update:
Controller code:
<?php
namespace App\Http\Controllers;
use Vinkla\Pusher\Facades\Pusher;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class TestPusherController extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function test(){
$arr = array('test' => 'hello world 2') ;
$pusher = new Pusher( env('PUSHER_KEY'), env('PUSHER_SECRET'), env('PUSHER_APP_ID'), array( 'encrypted' => true, 'cluster' => 'ap1' ) );
$pusher::trigger( 'test_channel', 'my_event', $arr);
return $arr;
}
public function shortenedTest(){
$message = 'Hello world';
Pusher::trigger('my-channel', 'my-event', ['message' => $message]);
}
}
In web routes:
Route::get('testPusherController', 'TestPusherController#test');
Route::get('shortenedTestPusherController', 'TestPusherController#shortenedTest');
I have got this working on a fresh install of vinkla/pusher following the setup steps in https://github.com/vinkla/laravel-pusher, on Laravel 5.3, using the built in PHP server and Connecting to the EU server (I do not have any Pusher apps using ap1 at this time).
You will notice a small number of changes to the coding in the controller to get the correct format. You must 'use' the Pusher facade above the controller.
For completeness, I have added a neater way of working with this where you can set the Pusher credentials in the Config/pusher.php file without the need to setup the connection for each use. This can be seen in the shortenedTest() method on the controller.
<?php
return [
'connections' => [
'main' => [
'auth_key' => env('PUSHER_KEY'),
'secret' => env('PUSHER_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_CLUSTER')
],
'host' => null,
'port' => null,
'timeout' => null,
],
'alternative' => [
'auth_key' => 'your-auth-key',
'secret' => 'your-secret',
'app_id' => 'your-app-id',
'options' => [],
'host' => null,
'port' => null,
'timeout' => null,
],
],
];