Manually add a comment in JComments - joomla

Anybody know if there's a function I can call to add a comment quickly to a certain object_id in JComments?
I have been looking through the JComments classes, but don't see anything apparent.
It would be great if I don't have to manually do the SQL insert.

What I did in the end was populate the jcomments textarea with the value of the comment and then called jcomments.saveComment() with a timeout to give it time to actually process.
$( "#dialog-accept-ed-confirm" ).dialog({
autoOpen: false,
resizable: false,
modal: true,
buttons: {
"Accept plan": function() {
// Proceed with click here
var $comment = $(".dialog_comment.accept").val();
var $setTimeout = 0;
if ($comment) {
$comment = "ACCEPTANCE: "+$comment;
addComment($comment, '.$plan_id.');
$setTimeout = 2000;
}
if ($setTimeout) {
setTimeout(function() {
location = href;
}, $setTimeout);
}
},
Cancel: function() {
$(this).dialog( "close" );
}
}
});
$("#accept_ed_plan").click(function(e) {
href=this.href;
$("#dialog-accept-ed-confirm").dialog("open");
return false;
});
function addComment($comment, $plan_id) {
$("#comments-form-comment").val($comment);
jcomments.saveComment();
alert("Comment added to plan");
}
});

Related

Laravel 8 get data from DB and show in Full calendar JS plugin Not working

Route
Route::get('getEvents', [App\Http\Controllers\CalenderController::class, 'index'])->name('event.getEvents');
Controller
public function index(Request $request)
{
$getEvents = Appointment::select('patient_id', 'start_time', 'end_time')->get();
$events = [];
foreach ($getEvents as $values) {
$start_time_format = $values->start_time;
$end_time_format = $values->end_time;
$event = [];
$event['title'] = $values->patient_id;
$event['start'] = $start_time_format;
$event['end'] = $end_time_format;
$events[] = $event;
Debugbar::info($events);
}
return $events;
}
Full Calendar Script
var calendar = new FullCalendar.Calendar(calendarEl, {
editable: true,
droppable: true,
selectable: true,
initialView: getInitialView(),
themeSystem: 'bootstrap',
// responsive
windowResize: function(view) {
var newView = getInitialView();
calendar.changeView(newView);
},
eventDidMount: function(info) {
if (info.event.extendedProps.status === 'done') {
// Change background color of row
info.el.style.backgroundColor = 'red';
// Change color of dot marker
var dotEl = info.el.getElementsByClassName('fc-event-dot')[0];
if (dotEl) {
dotEl.style.backgroundColor = 'white';
}
}
},
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listMonth'
},
eventClick: function(info) {
addEvent.modal('show');
formEvent[0].reset();
selectedEvent = info.event;
$("#event-title").val(selectedEvent.title);
$('#event-category').val(selectedEvent.classNames[0]);
newEventData = null;
modalTitle.text('Edit Event');
newEventData = null;
},
dateClick: function(info) {
addNewEvent(info);
},
editable: true,
events: 'getEvents',
displayEventTime: true,
eventRender: function(event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
});
calendar.render();
I have specified the route correctly in this script as events: 'getEvents', you can see that at the end part of the above script.
Now the result in the frontend is:
There is no data displayed from the DB.
And I am getting a console error as: Failed to load resource: the server responded with a status of 404 (Not Found): http://127.0.0.1:8000/getEvents?start=2021-09-26T00%3A00%3A00%2B05%3A30&end=2021-11-07T00%3A00%3A00%2B05%3A30
As you can see there are some unwanted characters in the URL obtained.
The debugging is not working here, I do not know why.. when I add dd($data) or something other there is no debugger part in Frontend.
Please help me to solve this thing.
Thank you.
It is worked. All I was done is correct. The issue was with my route, Due to one function to redirect invalid routes to the 404 page, My route to the controller was not working..
When I put the 404 route to the bottom of all other routes, It is worked.

What causes jqgrid events to fire multiple times?

Our jqgrid is configured in an initgrid function that is called as the last statement of a ready handler. For some reason, the gridcomplete function is getting called multiple times. With the code below, it gets called twice, but it had been getting called 3 times. Twice is bad enough. After stepping through it multiple times, I don't see what is triggering the second execution of the gridComplete function.
When I hit the debugger at the start of gridComplete, the call stack is virtually identical each time, the only difference being a call to 'L' in the jqgrid:
Anyone have an idea why this is occurring? We are using the free version 4.13, in an ASP.net MVC application.
$(function(){
....
initGrid();
}
function initGrid(){
$gridEl.jqGrid({
xhrFields: {
cors: false
},
url: "/IAConsult/GetWorkFlowIARequests",
postData: {
showAll: showAllVal,
role: role,
IsIAArchitect: userIsIA
},
datatype: "json",
crossDomain: true,
loadonce: true,
mtype: 'GET',
sortable: true,
viewrecords: true,
pager: '#workFlowIAGridPager',
multiselect: true,
rowNum: 50,
autowidth: true,
colModel: [...],
beforeSelectRow: function (rowid, e) {
var $myGrid = $(this),
i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
cm = $myGrid.jqGrid('getGridParam', 'colModel');
return (cm[i].name === 'cb');
},
jsonReader: {
repeatitems: true,
root: "IAConsultWorkflowRequestsList"
},
beforeSubmitCell: function (rowid, name, value, iRow, iCol) {
return {
gridData: gridData
};
},
serializeCellData: function (postdata) {
return JSON.stringify(postdata);
},
gridComplete: function () {
console.log('grid complete');
let rowIDs = $gridEl.getDataIDs();
let inCompleteFlag = false;
let dataToFilter = $gridEl.jqGrid('getGridParam', 'lastSelectedData').length == 0
? $gridEl.jqGrid("getGridParam", "data")
: $gridEl.jqGrid('getGridParam', 'lastSelectedData');
let $grid = $gridEl, postfilt = "";
let localFilter = $gridEl.jqGrid('getGridParam', 'postData').filters;
let columnNames = columns.split(',');
$('.moreItems').on('click', function () {
$.modalAlert({
body: $(this).data('allitems'),
buttons: {
dismiss: {
caption: 'Close'
}
},
title: 'Design Participants'
});
});
rowCount = $gridEl.getGridParam('records');
gridViewRowCount = rowCount;
let getUniqueNames = function (columnName) {
... };
let buildSearchSelect = function (uniqueNames) {
var values = {};
values[''] = 'All';
$.each(uniqueNames,
function () {
values[this] = this;
});
return values;
};
let setSearchSelect = function (columnName) {
...
};
function getSortOptionsByColName(colName) {
...
}
$grid.jqGrid("filterToolbar",
{ stringResult: true, searchOnEnter: true });
if (localFilter !== "" && localFilter != undefined) {
globalFilter = localFilter;
}
let grid = $gridEl.jqGrid("setGridParam",
{
postData: {
"filters": globalFilter,
showAll: showAllVal,
role: role,
IsIAArchitect: userIsIA
},
search: true,
forceClientSorting: true
});
//grid.trigger("reloadGrid");
//Ending Filter code
for (i = 0; i < columnNames.length; i++) {
var htmlForSelect = '<option value="">All</option>';
var un = getUniqueNames(columnNames[i]);
var $select = $("select[id='gs_workFlowIAGrid_" + columnNames[i] + "']");
for (j = 0; j < un.length; j++) {
val = un[j];
htmlForSelect += '<option value="' + val + '">' + val + '</option>';
}
$select.find('option').remove().end().append(htmlForSelect);
}
debugger;
},
// all grid parameters and additionally the following
loadComplete: function () {
$gridEl.jqGrid('setGridWidth', $(window).width(), true);
$gridEl.setGridWidth(window.innerWidth - 20);
},
height: '100%'
});
I personally almost never use gridComplete callback. It exists in free jqGrid mostly for backwards compatibility. I'd recommend you to read the old answer, which describes differences between gridComplete and loadComplete.
Some additional advices: it's dangerous to register events inside of callbacks (see $('.moreItems').on('click', ...). If you need to make some actions on click inside of grid then I'd recommend you to use beforeSelectRow. Many events, inclusive click event supports event bubbling and non-handled click inside of grid will be bubbled to the parent <table> element. You use already beforeSelectRow callback and e.target gives you full information about clicked element.
I recommend you additionally don't use setGridParam method, which can decrease performance. setGridParam method make by default deep copy of all internals parameters, inclusive arrays like data, which can be large. In the way, changing one small parameter with respect of setGridParam can be expensive. If you need to modify a parameter of jqGrid then you can use getGridParam without additional parameters to get reference to internal object, which contains all jqGrid parameters. After that you can access to read or modify parameters of jqGrid using the parameter object. See the answer for example for small code example.
Also adding the property
loadonce: true
might help.

Execute validation with button

I'm looking to execute the Handsontable validation on the click of a button instead of on cell change. Something like this: validateCells() (return bool isValid). This function doesn't seem to be working for me.
var
data = [],
container = document.getElementById('hot-Handsontable'),
save = document.getElementById('save'),
hidden = document.getElementById('hot-Handsontable-value'),
hot,
hotIsValid = true,
emailValidator;
emptyValidator = function(value, callback) {
callback(false);
};
hot = Handsontable(container, {
data: data,
minRows: 1,
minCols: 21,
maxCols: 21,
minSpareRows: 1,
stretchH: 'all',
colHeaders: ['Test'],
columns: [{data:'Test',allowInvalid:true, validator: emptyValidator}]
});
// exclude empty rows from validation
$('.title-block .united-alert a[href^=#Handsontable]').click(function() {
var href = $(this).attr('href');
var row = href.getIdIndex();
var prop = /([^__]*)$/.exec(href)[0];
hot.selectCellByProp(parseInt(row), prop);
return false;
});
// Save event
Handsontable.Dom.addEvent(save, 'click', function(e) {
var test = hot.validateCells(); // test is undefined
if (hotIsValid === true) {
hidden.value = JSON.stringify(hot.getData());
} else {
e.preventDefault();
}
});
What you should be doing, instead of var test = hot.validateCells() is the following:
// Save event
Handsontable.Dom.addEvent(save, 'click', function(e) {
hot.validateCells(function(hotIsValid) {
if (hotIsValid === true) {
hidden.value = JSON.stringify(hot.getData());
} else {
e.preventDefault();
}
})
});
Notice that validateCells takes a callback and returns undefined. This is why you see test as undefined. One other thing to note is that the callback is executed for every cell in your table so be careful with it.

Ckeditor Get Content From Iframe

I have a iframe and i'm trying to use Dialog to get data in Iframe and output to current html, but i don't know how to get Ckeditor Content from the Iframe.
I tried to using CKEDITOR.instances['editor'].getData(); but look like cannot get it.
This is my code:
<textarea class='editor' name='description' id='description'></textarea>
$( "#dialog_custom" ).dialog({
autoOpen: false,
modal: true,
height: 768,
width: 1024,
buttons: {
Add: function() {
var model = $('.dialog_custom').contents().find('#model').val();
var product_id = $('.dialog_custom').contents().find('#product_id').val();
var product_name = $('.dialog_custom').contents().find('#product_name').val();
var qty = $('.dialog_custom').contents().find('#qty').val();
var total = $('.dialog_custom').contents().find('#total').val();
var category = $('.dialog_custom').contents().find('#category').val();
if(qty=='') { qty = '0'; }
if(total=='') { total = '0.00'; }
if(model=='') {
alert('Please input the correct Model Number.');
} else {
$(".product").append(InsertTableGetFromIframe);
$('.delete_custom_row').click(function() {
if(confirm("Are you sure want to delete this data?")) {
$(this).parents('.custom_row').next('.parts_row').remove();
$(this).parents('.custom_row').remove();
}
});
$('.dialog_custom').contents().find('#model').val('');
$('.dialog_custom').contents().find('#product_id').val('');
$('.dialog_custom').contents().find('#product_name').val('');
$('.dialog_custom').contents().find('#qty').val('');
$('.dialog_custom').contents().find('#total').val('');
$('.dialog_custom').contents().find('#category').val('');
$(this).dialog("close");
i++;
}
},
Close: function() {
$(this).dialog("close");
}
}
});
$( "#open_custom" ).click(function() {
$( "#dialog_custom" ).dialog( "open" );
});
</script>
Finally, I found out the solution to get the content in the iframe, i used jquery to submit the form then POST the value on the field and get it by Jquery again.
It's the most simple way that i found, actually I think we have another way better to do it...

backbone collection add does not trigger model validate

I am rather new to backbone and wanted to test a simple script that handles a to do list. Here is the code i used so far:
(function() {
window.App = {
Models: {},
Collections: {},
Views: {}
};
window.template = function(id) {
return _.template($('#' + id).html());
}
App.Models.Task = Backbone.Model.extend({
validate: function(attributes) {
if ( !$.trim(attributes.title) ) {
return 'Invalid title';
}
}
});
App.Collections.Tasks = Backbone.Collection.extend({
model: App.Models.Task
});
App.Views.Task = Backbone.View.extend({
tagName: 'li',
template: template('taskTemplate'),
initialize: function () {
this.model.on('change', this.render, this);
this.model.on('destroy', this.remove, this);
},
events: {
'click .edit': 'editTask',
'click .delete': 'destroy'
},
destroy: function() {
if (confirm('Are you sure?')) {
this.model.destroy();
}
},
remove: function() {
this.$el.remove();
},
editTask: function() {
var newTaskTitle = prompt('New title:', this.model.get('title'));
this.model.set('title', newTaskTitle, {validate: true});
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
App.Views.AddTask = Backbone.View.extend({
el: 'form#addTask',
initialize: function() {
},
events: {
'submit': 'submit'
},
submit: function(event) {
event.preventDefault();
var newTaskTitle = $(event.currentTarget).find('input[type=text]').val();
var task = new App.Models.Task({ title: newTaskTitle });
this.collection.add(task, {add: true, merge: false, remove: false});
}
});
App.Views.Tasks = Backbone.View.extend({
tagName: 'ul',
initialize: function() {
this.collection.on('add', this.addOne, this);
},
render: function() {
this.collection.each(this.addOne, this);
return this;
},
addOne: function(task) {
var taskView = new App.Views.Task({ model: task });
this.$el.append(taskView.render().el);
}
});
var tasks = new App.Collections.Tasks([
{
title: 'Go to store',
priority: 4
},
{
title: 'Go to mall',
priority: 3
},
{
title: 'Get to work',
priority: 5
}
]);
var addTaskView = new App.Views.AddTask({ collection: tasks });
var tasksView = new App.Views.Tasks({ collection: tasks });
$('div.tasks').append(tasksView.render().el);
})();
So the model validation works fine ... the only pb is that collection.add does not validate the newly added model .... is the a way to force the validation?
Thanks,
Rares
From the fine manual:
validate model.validate(attributes, options)
[...] By default validate is called before save, but can also be
called before set if {validate:true} is passed.
Collection#add does not call save nor does it call set with the validate: true option. If you want to validate during add, say so:
collection.add(models, { validate: true });
That will get validate:true all that way down to Model#set.
A quick look at a simplified example may be helpful:
var M = Backbone.Model.extend({
set: function() {
console.log('setting...');
Backbone.Model.prototype.set.apply(this, arguments);
},
validate: function() {
console.log('validating...');
return 'Never!';
}
});
var C = Backbone.Collection.extend({
model: M
});
var c = new C;
c.on('add', function() {
console.log('Added: ', arguments);
});
c.on('invalid', function() {
console.log('Error: ', arguments);
});
Now if we do this (http://jsfiddle.net/ambiguous/7NqPg/):
c.add(
{ where: 'is', pancakes: 'house?' },
{ validate: true }
);
You'll see that set is called with validate: true, validate will be called, and you'll get an error. But if you say this (http://jsfiddle.net/ambiguous/7b2mn/):
c.add(
{ where: 'is', pancakes: 'house?' },
{add: true, merge: false, remove: false} // Your options
);
You'll see that set is called without validate: true, validate will not be called, and the model will be added to the collection.
The above behavior is quite strongly implied but not explicitly specified so you may not want to trust it. Model#initialize does say:
you can pass in the initial values of the attributes, which will be set on the model.
and set does explicitly mention the validate option. However, there is no guarantee that Collection#add will send options to the model constructor or set or that the model's constructor will send the options to set. So if you want to be really paranoid and future proof, you could add a quick check for this "options get all the way down to set" behavior to your test suite; then, if it changes you'll know about it and you can fix it.
if you pass options to your collection add method, the validation method will not be called and as your arguments in this case are all set to the default value, there is not need to pass them
this.collection.add(task);
you may want to take a look at this question.
Prevent Backbone.js model from validating when first added to collection

Resources