Question
I'm trying to create a ECK Entity Content programmatically. I know, because I've used it elsewhere, I have the right code for creating the Entity Content but in my current setup it is not working anymore.
What I have is the following:
.routing.yml
timetracking.ajax_check:
path: '/js/timetracking/ajax/{nid}'
defaults:
_controller: '\Drupal\timetracking\Controller\TimeTrackingController::timetrackingAjaxCheck'
requirements:
_csrf_token: 'TRUE'
TimeTrackingControlle.php
<?php
namespace Drupal\timetracking\Controller;
use Drupal\Core\Controller\ControllerBase;
/**
* Controller routines for user routes.
*/
class TimeTrackingController extends ControllerBase {
public function timetrackingAjaxCheck($nid) {
$user = $this->currentUser();
$timer = (int) $this->timeSpentConfig->get('time_spent_timer');
/* @ -- Save One Test Entity */
$test_entity = \Drupal::entityTypeManager()->getStorage('time_tracking')->create([
'type' => 'time',
'title' => 'test-2',
'field_id' => 1,
]);
$test_entity->save();
}
}
.js
(function ($, Drupal) {
Drupal.behaviors.timetracking = {
attach: function(context, settings) {
// Fetch ajax callback url
var callbackUrl = '/js/timetracking/ajax/10';
function timetrackingSendTimer() {
$.ajax({
type: 'get',
url: callbackUrl,
dataType: 'json',
data: 'js=1&timer=10'
});
}
timetrackingSendTimer();
}
}
})(jQuery, Drupal);
When I put the Save One Test Entity in a .module file it creates an Enitity but when I put it inside the controller it is not. The controller is running as expected when I am debugging it using DPM
I get a nice output.
I'm wondering if it is possible to do this inside the Controller? And if not how can I use Ajax to create an ECK Entity?
Solution
In your route you require CSRF token and your ajax call is missing the CSRF token.
Get a CSRF token from ur drupal site using url "/session/token" and send it with your Ajax request.
But is it wise to do it this way? i don't know.
For making ECK Entity with ajax Post i would use REST resource or make a custom REST resource with basic_auth or cookie authentication, that way you wont need a CSRF Token.