send POST data from calendar to json_events.php - fullcalendar

I imagine this is simple but I can't quite get the concept clear.
Basically I am working on loading events on prev/next click
viewDisplay: function(view) { var next = view.title; }, //alert(next);
gives me "November 2012"
split this
then
events: {
url: 'json-events.php',
type: 'POST', <br/>
data: { month: month,
year: year } },
So, how to read the POST val in json-events.php
Assuming I am on the right track here. [super newbie]

use as object reference http://arshaw.com/fullcalendar/docs/event_data/Event_Object/
<?php
//obtain params
$month = $_POST["month"];
$year = $_POST["year"];
//... get the list of events due to month and year
//create an events array due to docs
$events = array(array('id' => 1, 'title' => 'Event', 'allDay' => true));
//return json feed
echo json_encode($events);
?>

Related

how can I configure a simple eventlistener on symfony

``I tried to add an event listener on a field of a formular, but it doesn't work at all ; a var_dump on the variable gives allways the value "null", whatever I can do.
Is there something to do in the folder services.yaml, or some javascript to add somewhere ?
I'm total beginner, but I love this project and I would really like to succed in it.
->add('tournamentGame', ChoiceType::class, [
'choices' => [
'oui'=>true,
'non'=>false,
],
'data'=>true,
"attr"=>[
'class'=>'ms-2',
],
'multiple'=> false,
'label'=>'Mode Tournoi',
'mapped' => true,
'required' => false
])
;
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) {
$form = $event->getForm();
// this would be your entity, i.e. SportMeetup
$tournamentGame = $event->getData();
$multiplayer = $tournamentGame->isTournamentGame();
$nbTotalPlayer = null === $tournamentGame ? [] : $multiplayer;
$choice = false === $multiplayer ? ['2 joueurs'=>2,
'4 joueurs'=>4,
'6 joueurs'=>6,
'8 joueurs'=>8,
'10 joueurs'=>10,
'12 joueurs'=>12,
'14 joueurs'=>14,
'16 joueurs'=>16,
'18 joueurs'=>18,
'20 joueurs'=>20,] :
[];
$form->add('nbTotalPlayer', ChoiceType::class, [
'label' => 'Nombres de joueurs',
'choices'=>$choice,
]);
var_dump($multiplayer);
}
);
I've joined this jquery to the template, In the console I can see that the variable tournament has the correct values, but I need to return it into the the form in php, maybe it would be easier for you to understand what I want to do, I have to change the part with function(html), but I don' know what I can replace it with.
<script>
var tournamentGame = $('#game_tournamentGame');
// When sport gets selected ...
tournamentGame.change(function() {
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// Simulate form data, but only include the selected sport value.
var data = {};
data[tournamentGame] = parseInt(tournamentGame.val());
// Submit data via AJAX to the form's action path.
console.log(data[tournamentGame]);
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
complete: function(html) {
// Replace current position field ...
$('#game_nbTotalPlayer').replaceWith(
// ... with the returned one from the AJAX response.
$(html.responseText).find('#game_nbTotalPlayer')
);
// Position field now displays the appropriate positions.
}
});
});
</script>
dd($tournamentGame)

Woocommerce update_status() Only Works for Admin Orders

Very odd issue. I have built a plugin (for a client, not a public one) that creates a couple of REST endpoints that a shipping service (Shippo) passes data to (all this is fine and working). The plugin takes the data, gets an Order Number, and attempts to set a Completed status.
The code only works perfectly if the Order is from the Admin account. But any other custom account and the status will not save. An order note is generated claiming the status was changed, and I can set meta data on the order. But the status will not change.
In the code, I have attempted to use update_status() and set_status() both with and without .save();
add_action('rest_api_init', function () {
register_rest_route('lab/v1', '/shipment_label_created_shippo', ['methods' => 'POST', 'callback' => 'rest_shipment_label_created_shippo', 'permission_callback' => '__return_true', ]);
register_rest_route('lab/v1', '/shipment_label_updated_shippo', ['methods' => 'POST', 'callback' => 'rest_shipment_label_updated_shippo', 'permission_callback' => '__return_true', ]);
register_rest_route('lab/v1', '/shipment_tracking_updated_shippo', ['methods' => 'POST', 'callback' => 'rest_shipment_tracking_updated_shippo', 'permission_callback' => '__return_true', ]);});
// Label Created in Shippo (transaction_created)
function rest_shipment_label_created_shippo($data){
$log = new WC_Logger();
$response = new WP_REST_Response("Failed");
$response->set_status(200);
$meta_order_number = $data['data']['metadata'];
$woo_order_number = explode(" ", $meta_order_number);
$order_number = intval($woo_order_number[1]);
if ($shippo_status == "SUCCESS" && !is_null($shippo_order_id)) {
if( class_exists('WC_Order') && $order_number > 0 ) {
$order = wc_get_order($order_number);
if ($order) {
$payment_method = $order->get_payment_method();
$payment_method_title = $order->get_payment_method_title();
$date_paid = $order->get_date_paid();
// Update the Order Meta as well for tracking
$update_order_was_shipped = update_post_meta($order_number, '_order_was_shipped', $date_shipped);
// Add the Shippo Transaction ID
$update_transactionid = update_post_meta($order_number, '_shippo_transaction_id', $shippo_transaction_id);
if ($payment_method == "invoice" && !is_null($date_paid))
{
$order->update_status('shipped-invoiced');
$saved_order_id = $order->save();
}
else
{
$order->update_status('completed');
$saved_order_id = $order->save();
}
}
Thanks in advance for any thoughts you might have!
Just in case someone else stumbles onto this I wanted to answer the question.
The reason it appears as though only Admin orders (orders I placed) are working is because I never had the order tab up. Our client, always had the Order open that they were updating via a 3rd party. When the Rest API was hit by the 3rd party, order details were not saved because the order was locked.
This makes sense of course, but was not top of mind for me.

How do i use onHourShow callback in a date_popup control with the Drupal Form API

I have a drupal form with a single date_popup field. I would like it to just provide the options of 12, 15 and 17 for the hours.
$form['order-group']['delivery'] = array(
'#title' => t('I Need The Equipment Ready By'),
'#type' => 'date_popup',
'#date_format' => 'd-M-Y H:i',
'#timepicker' => 'timepicker',
'#timepicker_options' => array(
'rows' => 3,
'hours' => array(
'starts' => 12,
'ends' => 17,
),
'onHourShow' => 'onHourShowCallback',
'minutes' => array(
'starts' => 0,
'ends' => 0,
),
'showCloseButton' => TRUE,
'closeButtonText' => t('Close'),
),
'#default_value' => date('Y-m-d 12:00',time()),
'#date_label_position' => '',
);
I then added the following to my javascript file (included with drupal_add_js, earlier in the script)
function onHourShowCallback(hour) {
return hour == 12 || hour == 15 || hour == 17;
};
However I get the following error:
Uncaught TypeError: onHourShow.apply is not a function
at Timepicker._generateHTMLHourCell (jquery.ui.timepicker.js?psw6eo:797)
at Timepicker._generateHTML (jquery.ui.timepicker.js?psw6eo:622)
at Timepicker._updateTimepicker (jquery.ui.timepicker.js?psw6eo:467)
at Timepicker._setTimeFromField (jquery.ui.timepicker.js?psw6eo:1112)
at Timepicker._attachTimepicker (jquery.ui.timepicker.js?psw6eo:190)
at HTMLInputElement.<anonymous> (jquery.ui.timepicker.js?psw6eo:1474)
at Function.each (jquery.min.js?v=1.7.2:2)
at $.fn.init.each (jquery.min.js?v=1.7.2:2)
at $.fn.init.$.fn.timepicker (jquery.ui.timepicker.js?psw6eo:1470)
at Object.attach (date_popup_timepicker.timepicker.js?psw6eo:8)
I tried asking this in the Drupal stack exchange but was put "On Hold" and told this is a programming question, so I am asking here instead.
jQuery UI Timepicker invokes callback functions such as 'beforeShow', 'onSelect', etc. using the method apply(), e.g. :
var beforeShow = $.timepicker._get(inst, 'beforeShow');
extendRemove(inst.settings, (beforeShow ? beforeShow.apply(input, [input, inst]) : {}));
Thus, the type of the callback must be a function - not a string.
The problem is that the module date_popup_timepicker does not map string callbacks (passed in from the server) to actual js function callbacks before initializing the timepicker, so once jquery.ui.timepicker.js code runs it throws an Uncaught TypeError: <callback>.apply is not a function.
On the client side, the datePopup settings object (from Drupal.settings) potentially contains string callbacks, so any of these strings must be converted to its corresponding function before calling the timepicker() method. What was missing to get there :
var timepicker_callbacks = {
beforeShow: null,
onSelect: null,
onClose: null,
onHourShow: null,
onMinuteShow: null
};
function timepicker_callbacks_assign (settings) {
for (var setting in settings) {
if (setting in timepicker_callbacks && typeof settings[setting] === 'string') {
var namespace = window,
ns_callback = settings[setting].split('.'),
func = ns_callback.pop();
for (var i = 0; i < ns_callback.length; i++) {
namespace = namespace[ns_callback[i]];
}
settings[setting] = namespace[func];
}
}
}
The timepicker() initialization occurs in Drupal.behaviors.DatePopupTimepicker, we just need to execute timepicker_callbacks_assign() first for the timepicker to get the proper settings.
I created an issue and submitted a patch on drupal.org, it still "Needs Review" so don't hesitate to apply from there and review it.

Laravel - multiple forms/tables - carry over variable in URL to fill table column

I am quite new to coding and to Laravel (using 5.7). I understood how to create a basic one-page form to populate a table in a database, including relashionship and authentication but I have difficulties reaching the next level.
The app I want to design will have multiple forms and tables and I can't figure out how to link info collected from the first form to the following one.
Let's consider a Database with:
- a Clients table (populated thru form page A) ex: one field is a client_id field.
- a Products table (populated thru form page B)
- (ultimately they will be more)
When the user (e.g. an employee of a compagny analyzing clients behavior) is done filling the form page A (URL: /clients, GET method: Clientcontroller#create, view clients.create.blade.php), he/she click Next.
My idea is that the Next button should:
- submit information to the Client table (POST method: Clientscontroller#store)
- and redirect the user to the page B of the form, carrying over the client_id in the URL (URL: /products/{client_id}/create, GET method: Productscontroller#create, view products.create.blade.php).
In the Product table, I have a client_id column and I have a one to many relashionship between the Clients and Products model.
Upon submission of form B, I would like to retrieve the {client_id} from URL to fill the client_id column of the Product table but I am stuck here. I would appreciate pieces of guidance and advices. For simplification during the learning process, I consider that Clients only buy one product.
THE MAIN QUESTION IS:
- How to retrieve the {client_id} parameter from the URL of the products.create.blade.php view to inject it onto the client view (already tried a lot of thing from answer to similar questions in stackoverflow)
ALSO:
- Am I using the right approach? Any suggestions/advices?
EXTRA QUESTION a bit out of the scope:
- Any hint on how implement add/remove fields for products?
WEB ROUTES FILE:
> <?php
> Route::get('/', 'PagesController#welcome')->name('welcome');
> Auth::routes();
> //ROUTES FOR CLIENT
> Route::resource('clients','ClientsController');
> //ROUTES FOR PRODUCT (please note the {client_id} parameter)
> Route::get('/products/{client_id}/create', 'ProductsController#create')->name('products.create');
> Route::post('/products/{client_id}', 'ProductsController#store')->name('products.store');
> //not sure if it should be Route::post('/products', 'ProductsController#store')->name('products.store');
CLIENTS CONTROLLER:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Client; //THIS IS THE CLIENT MODEL
use App\User; ////THIS IS THE USER MODEL
class ClientsController extends Controller
{
AUTH
public function __construct()
{
$this->middleware('auth');
}
//INDEX (CLIENT)
public function index()
{
//my code here
}
//CREATE (CLIENT)
public function create()
{
$datas=[
'controllermethod' => 'ClientsController#store',
'client_id_field' => [
'input_type_l' => 'textinput',
'input_name_l' => 'client_id', //this what i am carrying over in URL
'input_label_l' => 'Client ID :',
'input_placeholder_l' => 'XXXXX',
'input_default_l' => ''
],
'client_info_1_field' => [
'input_type_l' => 'textinput',
'input_name_l' => 'client_info_1'
'input_label_l' => 'Client Info 1 :',
'input_placeholder_l' => 'XXXXX',
'input_default_l' => ''
],
'client_info_2_field' => [
'input_type_l' => 'textinput',
'input_name_l' => 'client_info_2'
'input_label_l' => 'Client Info 2 :',
'input_placeholder_l' => 'XXXXX',
'input_default_l' => ''
]
],
return view ('clients.create')->with($datas);
}
//STORE (CLIENT)
public function store(Request $request)
{
$this->validate($request, [
'client_id' => 'required',
]);
$client = new Client;
$client->client_id = $request->input('client_id');
$client->client_info_1 = $request->input('client_info_1');
$client->client_info_2 = $request->input('client_info_2');
$client->user_id = auth()->user()->id; //one to many relashionship betw user/client models
$client->save();
//
//this is how I inject the {client_id} parameter onto the URL
//this works, the products.create view is displayed, the URL contain the client_id from formA entered by the user
$client_id = $request->client_id;
return redirect("/products/$client_id/create")->with('client_id', $client_id)
->with('success','New client record created');
//SHOW/DESTROY/EDIT/UPDATE FUNCTIONS....all this work
PRODUCTS CONTROLLER = THAT's WERE I AM STUCK + NOT SURE IF IT's THE RIGHT APPROACH
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
//note sure if I need that
//use Illuminate\Routing\Route;
use App\Product;
use App\Client;
use App\User;
class ProductsController extends Controller
{
//AUTH
public function __construct()
{
$this->middleware('auth');
}
//INDEX (PRODUCT)
public function index()
{
//no code so far
}
//INDEX (PRODUCT)
public function create()
{
$datas=[
'controllermethod' => 'ProductsController#store',
//planning of having dynamic add/remove products fields but let's keep it simple (1 client -> 1 product)
'product_id_field' => [
'input_type_l' => 'textinput',
'input_name_l' => 'product_id',
'input_label_l' => 'Date of cancer diagnosis :',
'input_default_l' => ''
],
'product_info_1_field' => [
'input_type_l' => 'textinput',
'input_name_l' => 'product_info_1'
'input_label_l' => 'Product Info 1 :',
'input_placeholder_l' => 'XXXXX',
'input_default_l' => ''
],
'product_info_2_field' => [
'input_type_l' => 'textinput',
'input_name_l' => 'product_info_2'
'input_label_l' => 'Product Info 2 :',
'input_placeholder_l' => 'XXXXX',
'input_default_l' => ''
]
],
//Below, I am not sure I should do that
return view ('products.create')->with($datas);
}
// STORE (PRODUCT) = THAT's WHERE I AM STUCK
// everything works except that the client_id column in the products table stays empty or filled with crap
public function store(Request $request)
{
//NOT SURE WHAT TO DO HERE TO RETRIEVE THE {client_id} from the "/products/$client_id/create" ...
//TO FURTHER INJECT IT AS A VALUE IN THE client_id COLUMN OF THE PRODUCT TABLE
//I KNOW IT's CRAP, but I TRIED THINGS ALONG THOSE LINES:
//return $client_id;
//$client_id = request()->route()->paremeters('client_id');
//$client_id = request()->route('client_id');
//$client_id = $request->client_id;
//$client_id = url('client_id');
$product = new Diagnosis;
$product->product_id = $request->input('product_id');
$product->product_info_1 = $request->input('product_info_1');
$product->product_info_2 = $request->input('product_info_2');
$product->user_id = auth()->user()->id;
//I KNOW IT's CRAP, but I TRIED THINGS ALONG THOSE LINES:
//$diagnosis->client_id = $client_id; //NB: if I write $diagnosis->client_id = 'whatever'; it works
$diagnosis->save();
//redirect to client.index view
return redirect('/clients')->with('success','New patient diagnosis (-es) created');
}
our solution will start by looking to this route :
Route::get('/products/{client_id}/create','ProductsController#create')->name('products.create');
this is the route that contains your client_id that we want to retrieve, and since this value is on the link, we can use the Request object to access to it!
like i said, the $request object already contains the client_id value, so what we need is to retrieve it and send it as a parameter to the view using the with function, so basically your ProductsController#create will be like this :
public function create(Request $request)
{
// all your code ...
return view ('products.create')->with("data",$datas)->with("client_id",$request->client_id);
}
so now, we access this value from our view right ? the idea is to add this value as a hidden input on the product form! ( something like this )
<form>
<!-- other inputs .... -->
<input type="hidden" value="{{$client_id}}" name="client_id" />
</form>
after submitting the form, this route will be called :
Route::post('/products/{client_id}', 'ProductsController#store')->name('products.store');
since the client_id will be sent through the form and not using the link, it would be better if you change your route to
Route::post('/products', 'ProductsController#store')->name('products.store');
now, we can have access to our value on the store function just by using
$client_id = $request->input('client_id')
Here is an alternative solution which works too:
ROUTES:
Route::get('/products/{client_id}/create', 'ProductsController#create')-name('products.create');
Route::post('/products', 'ProductsController#store')->name('products.store');
PRODUCTS CONTROLLER CREATE FUNCTION:
public function create() //keep as in the original question
{
// all your code ...
return view ('products.create')->with("data",$datas)->with("client_id",$request->client_id);
}
IN THE VIEW:
<form>
<!-- other inputs .... -->
<input type="hidden" value="{{Request::segment(2)}}" name="client_id" /> //access the URL segmment 2 which correspond to the client_id
</form>
IN THE PRODUCTS CONTROLLER STORE FUNCTION:
$client_id = $request->input('client_id')
It would have be nice to use the Request::segment(2) directly in the store function like this but this triggers a "Non-static method Illuminate\Http\Request::segment() should not be called statically" error that I have not been able to resolve. I don't need an answer to that, however an hint would be appreciated anyway. Maybe I'll post a new question if this has not been resolved already.

can't insert event starting on a defined date into fullCalendar

I'm working on a codeIgniter project.I use fullCalendar to insert events. The concept that I want to implement is similar to google Calendar. When a user clicks on a day in the calendar, he inserts an event starting on the date of the clicked day.
I did an ajax call from my view and post the date to the controller.Once in the controller, all what I want to do is to set the start date with this value and to insert the event in the calendar. Here is my code (controller)
function add_event()
{
$click_date = $this->input->post('date');
$date= explode(" ", "$click_date ");
$month= (int)$date[1];
$day= (int)$date[2];
$year= (int)$date[3];
$date_start = $this->unix_timestamp($year.'-'.$month.'-'.$day);
$this->load->library('gcal');
$date_end = $this->unix_timestamp('2012-08-15');
$params = array(
'calendarId' => 'my Google calendar id',
'allday' => true,
'start' => $date_start,
'end' => $date_end,
'summary' => 'event',
'description' => "My first event"
);
$response = $this->gcal->eventInsert($params);
if($response)
{
echo "true";
}
}
Here is my unix_timestamp function :
function unix_timestamp($date)
{
$date = str_replace(array(' ', ':'), '-', $date);
$c = explode('-', $date);
$c = array_pad($c, 6, 0);
array_walk($c, 'intval');
return mktime($c[3], $c[4], $c[5], $c[1], $c[2], $c[0]);
}
On the calendar, the event is inserted but not on the right starting date. It starts on 2012-01-01 which is the default date I guess. I don't understand why my starting date isn't set correctly.
What I am doing wrong? Could someone please help me?
I found the answer. I should convert the fullCalendar date format into string before posting it to the controller. One line was missing :
date_format = $.fullCalendar.formatDate(date,"yyyy-MM-dd HH:mm:ss");`
Hope that it would help people who have the same problem
`

Resources