So i have an object thats draggable to multiple columns and I need to make it so that when it is dropped a variable in that object gets updated depending on what column that is, as another object manipulates that variable for display. i have been unable to get the (ondrop) event to work from the tag, and the dragula event listener's value doesnt pass me any information that would allow me to get the object. Is there anyway to force the event listener to pass the object instead of the html tags? or is there some method im missing?
I think you can update data on drop. I've done it like this:
var drake = dragula({...});
function updateMyObject(elementId, listId) {
// update the object here, for example:
if (listId === 'firstList') {
// use the element id to find the item in your object and update it
myDataObject.filter(function(x) {
return x.id === elementId;
})[0].propertyToUpdate = listId;
}
}
drake.on('drop', function(el, target, source, sibling) {
var elementId = el.id;
updateMyObject(el.id, target.id);
});
This pen may help. I'm mixing Dragula with Angular.js for the data modelling. The event needs to update the data model on drop.
http://codepen.io/chris22smith/pen/37459a002cbe6b6cd37aa5e927698fba
The only solution I have found (short from using a different drag'n'drop module) is to save the order when the user closes the page or goes to something else. Or since the drop event is catch-able, but does not seem to be able to give a class object, you can still detect when there was a change and have it update everything, however that is not the best work around as it is far more taxing on system resources than updating one variable.
Pass the order # as an attribute in your element so it's accessible in your drake.on function. With the oder# and the ID you should be able to figure out what to do with it and make the right updates on the backend.
Related
I have a following problem: I have a scheduler that is used by different users. When a user adds an event to scheduler, a session variable containing his id must be passed to a processor where it is inserted into a database.
My first question is how do I bind a session variable to a form that is created with a scheduler.config.lightbox.sections:
scheduler.config.lightbox.sections=[
{name:"Customer Code", height:21, map_to:"text", type:"textarea" , focus:false},
{name:"Photographer", height:21, map_to:"pid", type:"select",
options:scheduler.serverList("type")},
{name:"time", height:72, type:"time", map_to:"auto"}
]
Is it possible to bind a session variable to it?
My second question is how do I get session variable in processor.php?
Please, correct me if I'm wrong, but according to the documentation it's going to be something like this:
//... connect here
function myInsert($action){
$new_value = rand(0,100);
$action->set_value("name",$new_value);
}
$conn->event->attach("beforeInsert","myInsert");
// ...some code here
$conn->render_table("photographers_at_work", "id", "time, end_time, customer_code, pid");
You can use onEventCreated to assign default values (such as user id) to a newly created event:
scheduler.attachEvent("onEventCreated", function(id,e){
var event = scheduler.getEvent(id);
event.pid = userId;
});
https://docs.dhtmlx.com/scheduler/api__scheduler_oneventcreated_event.html
This API event fires before lightbox is opened, so the lightbox will receive assigned values.
As for backend - yes, something like this should work. Couple of notes
$action->set_value - the first parameter is a column name
this column must be listed in properties columns you provide to connector (i.e. if you set value of column you don't have in your render_table parameters - connector will ignore it)
So something following should do:
//... connect here
function myInsert($action){
global $userId;
$action->set_value("pid",$userId);// ! set value of "pid" column
}
$conn->event->attach("beforeInsert","myInsert");
// ...some code here
$conn->render_table("photographers_at_work", "id", "time, end_time, customer_code, pid");
you can enable connector logging to see actual sql requests connector generates: https://docs.dhtmlx.com/connector__php__errors.html#serversidelogging
I am trying to create a plugin that will take the value of a listbox TV and set the document's createdby field to match that TV's setting onDocFormSave. The TV populates itself automatically with all active users and output's their ID.
I have the following code for the plugin, but when I try to save any resource it simply hangs and never saves. setCreatedBy is the name of the listbox TV:
switch ($modx->event->name) {
case 'onDocFormSave':
$created_by = $resource->getTVValue('setCreatedBy')
if ($resource->get('createdby') != $created_by) {
$modx->resource->set('createdby', $created_by));
}
break;
}
Untested.
It looks like setting also has to be done on the resource, not via the Modx-class.
$resource->set('createdby', $created_by); // You also have a ) too much in your code.
Inspected the docs.
If you omit the $resource->set... and run the plugin, will it pass? I'm wondering if you might be causing a loop, i.e $resource->set triggers another onDocFormSave. Do you have access to the server error.log? It probably contains whatever is crashing.
Those on the Modx forums were able to give me a leg up.
switch ($modx->event->name) {
case 'OnDocFormSave':
$created_by = $resource->getTVValue('setCreatedBy');
if (!empty($created_by) && $resource->get('createdby') != $created_by) {
$resource->set('createdby', $created_by);
$resource->save();
}
break;}
For reference, the way I handled gathering the names and user id's of Modx users and placing them in a selectbox TV was to use the Peoples snippet in an #EVAL binding:
#EVAL return $modx->runSnippet('Peoples',array('tpl'=>'peoplesTpl','outputSeparator'=>'||','active'=>'1'));
This is a petty dirty and slow way of doing things, but a request to have this be a standard field on Modx resources has been submitted to GitHub
I have a PHP page that uses jQuery to let a user update a particular item without needing to refresh the page. It is an availability update where they can change their availability for an event to Yes, No, or Maybe. Each time they click on the link the appropriate jQuery function is called to send data to a separate PHP file (update_avail.php) and the appropriate data is returned.
Yes
Then when clicked the params are sent to a PHP file which returns back:
No
Then, if clicked again the PHP will return:
Maybe
It all works fine and I'm loving it.
BUT--
I also have a total count at the bottom of the page that is PHP code to count the total number of users that have selected Yes as their availability by simply using:
<?php count($event1_accepted); ?>
How can I make it so that if a user changes their availability it will also update the count without needing to refresh the page?
My thoughts so far are:
$var = 1;
while ($var > 0) {
count($day1_accepted);
$var = 0;
exit;
}
Then add a line to my 'update_avail.php' (which gets sent data from the jQuery function) to make $var = 1
Any help would be great. I would like to stress that my main strength is PHP, not jQuery, so a PHP solution would be preferred, but if necessary I can tackle some simple jQuery.
Thanks!
In the response from update_avail.php return a JSON object with both your replacement html and your new counter value.
Or to keep it simple, if they click "yes" incriment the counter, if they click No or maybe and their previous action wasn't No or Maybe decrease the counter.
Assuming your users are logged into the system I'd recommend having a status field in the user table, perhaps as an enum with "offline", "available", "busy", "unavailable" or something similar and use the query the number of available users whilst updating the users status.
If you were to do this you'd need to include in extend your methods containing session)start() and session_destroy() to change the availability of the user to available / offline respectively
The best way is the one suggested by Scuzzy with some improvements.
In your php, get the count from the database and return a JSON object like:
{ count: 123, html: 'Yes' }
In your page, in the ajax response you get the values and update the elements:
...
success: function(data) {
$("#linkPlaceholder").html(data.html);
$("#countPlaceholder").html(data.count);
}
...
I currently have a page defined which displays some data in rows. At the end of each row, there is a view which shows a total which is extracted from mysql.
$r->add('View_PointsLeft', 'pleft', 'pointsleft')
->setPoints($row['points_left'])
->setBacklog($row['backlog_ref'])
->setID($row['id'].'-points-left');
The view is defined with a template like this
<!-- points left -->
<div class='target points_left'>
<div class='sticky green'>
<div class='story'><?$backlog?></div>
<div id='<?$name?>' class='big_points big_point_margin'><?$pointsleft?></div>
</div>
</div>
<!-- end 0000-points-left -->
The data to populate the view is selected using a sql in the page which is looped through and the /lib/view/pointsleft.php code has set methods which are passed parameters from the page and update the fields in the template.
class View_PointsLeft extends View_Sticky {
function init(){
parent::init();
}
function setPoints($points){
$this->template->set('pointsleft',$points);
return $this;
}
function setBacklog($backlog){
$this->template->set('backlog',$backlog);
return $this;
}
function defaultTemplate(){
return array('view/scrumwall/pointsleft');
}
}
I want to update the database when something is changed on the page and also update the total view (to decrement the counter).
First, I'm wondering if i have approached this the wrong way (should each view should be self contained) - should i just pass the id field to the view, attach the relevant model to the view inside lib/view/pointsleft.php and call the set fields using the model values ?
Secondly, If i change it that way, does it then make it easier to update the view with a particular id when the database value is changed using ajax and if so , how do i do this ?
Thirdly - if i want to also trigger an update into the database based on an action on the client side javascript, where would i put this code e.g. in the non atk4 version of my code, i had a script called using $.post("update.php") which would update mysql. Where would i put such a script in ATK4 ?
Thanks in advance.
Update after answer from Romans
Man, ATK4 rocks ! - it does more than i expected and i was busy creating functions inside the view to populate each field name, so now having redone it using addModel,
the call from the page looks like this
$r->add('View_PointsLeft', 'pleft', 'pointsleft')
->loadData($row['id']);
the templates/view looks like this
<div id='<?$name?>' class='target points_left'>
<div class='sticky green'>
<div class='story'><?$backlog_ref?></div>
<div class='big_points big_point_margin'><?$points_left?></div>
</div>
</div>
and the lib/view code looks like this
<?php
class View_PointsLeft extends View_Sticky {
function loadData($id){
$this->setModel('Story')->loadData($id);
}
function init(){
parent::init();
}
function defaultTemplate(){
return array('view/scrumwall/pointsleft');
}
}
Update after code example from Romans
After following the code example Romans provided, i now add the URL call using jquery selectors at the bottom of my page code and do some jiggery pokery to get the task and status from the id fields (not sure about using HTML5 only stufff using data-id so just set the normal id and extract from that). Previously the drop code was in my own univ.js script but i dont have access to the php variables from there so i move it into the page
$p->js(true)->_selector('.movable')->draggable();
$p->js(true)->_selector('.target')->droppable(array(
'drop'=>$this->js(null,'function(event,ui){'.
' target=$(this).attr("id").split("-");'.
' zone=target[2];'.
' sticky=$(ui.draggable).attr("id").split("-");'.
' task=sticky[1];'.
' switch (zone) {'.
' case "verify": newStatus="V";'.
' break;'.
' case "in": newStatus="P";'.
' break;'.
' case "to": newStatus="I";'.
' break;'.
' case "done": newStatus="D";'.
' break;'.
'}
$.univ().ajaxec({ 0:"'.$this->api->getDestinationURL().'",'.
'task: task, status: newStatus }); } ')
));
and i have a if block which looks like this in the page. I add Model_Task and load the values based on the GET parameter so i then also have more information including the story it relates to so i can also update the points if the status is now done.
if($_GET['task'] && $_GET['status'])
{
$new_status=$_GET['status'];
$task_id=$_GET['task'];
$t=$p->add('Model_Task')->loadData($task_id);
$old_status=$t->get('status');
$task_points=$t->get('points');
if ($new_status<>$old_status & ($new_status=='D' | $old_status=='D'))
{
$s=$p->add('Model_Story')->loadData($t->get('story_id'));
if ($old_status='D')
{
$s->set('points_left',$s->get('points_left')+$task_points);
} else {
$s->set('points_left',$s->get('points_left')-$task_points);
}
$s->update();
$story=$t->get('story_id');
}
$t->set('status',$new_status);
$t->update();
}
i can then calculate the new number of points and update the story with points left and update the task with the new_status by setting the model values and using update().
If i now move one of the draggables, it works but opens a new window showing again the whole page and reporting
Error in AJAXec response: SyntaxError: syntax error
I think opening the extra window is because of the error but the error is something to do with the response having all the html for the whole page. I dont actually want any reload from the ajax call unless the status is a particular one.
Also the last thing i need to do is only reload one view on the page for the particular story that was updated.
I've tried by creating an array and adding the short variables to it like this when the page is first loaded
$this->pl_arr[$row['id']]=$r->add('View_PointsLeft', 'pleft', 'pointsleft')
->loadData($row['id']);
and then in the if block while processing the GET, to recall it
$pleft=$this->pl_arr[$story];
$pleft->js()->reload()->execute();
but it fails with an error
Error in AJAXec response: SyntaxError: missing ; before statement
Fatal error: Call to a member function js() on a non-object in C:\wamp\www\paperless\page\scrumwall.php on line 247
Final update
The last error is caused because i didnt use for the id in the outer div of the whole view i wanted to update. Once i changed this it is no longer null.
So the first time the page is loaded, i store all the view names in an associative array in a loop as i put them on the page
$st = $p->add('Model_Story');
$result = $st->getRows();
foreach ($result as $row) {
if (is_array($row)) {
$r=$p->add('View_Scrumwall_StoryRow')
->setWorkspace('ws-'.$row['id']);
... other code here ...
$points_left[$row['id']]=$r->add('View_PointsLeft', null, 'pointsleft')
->loadData($row['id']);
}
and then have the if GET block like this
if($_GET['task'] && $_GET['status'])
{
$new_status=$_GET['status'];
$task_id=$_GET['task'];
$t=$p->add('Model_Task')->loadData($task_id);
$old_status=$t->get('status');
$task_points=$t->get('points');
if ($new_status<>$old_status && ($new_status=='D' || $old_status=='D'))
{
$s=$p->add('Model_Story')->loadData($t->get('story_id'));
if ($new_status=='D')
{
$s->set('points_left',$s->get('points_left')-$task_points);
} else {
$s->set('points_left',$s->get('points_left')+$task_points);
}
$s->update();
$story=$t->get('story_id');
//reload the points left sticky note for the story of the task
$js[]=$points_left[$story]->js()->reload();
}
$t->set('status',$new_status);
$t->update();
$js[]=$this->js()->reload();
$this->js(null,$js)->execute();
}
Note that if I only want to update one view on the page, i can just call that chaing that object with reload and execute e.g.
$pl->js()->reload()->execute
but if i want to update several views on the page, i need to put them in an array (here called js[]) and then call execute like this - you can also see an example of this in Roman's codepad example.
$js[]=$points_left[$story]->js()->reload();
$js[]=$this->js()->reload();
$this->js(null,$js)->execute();
Problem solved with ATK4 :)
Ok, for a cleaner answer, I've put together a sample:
http://codepad.agiletoolkit.org/dragaction.html
Probably example here answers the question better.
In your case, since you are working with models, it should be easier to set this up. For the performance I decided to use 2 Listers, but in theory you can also have each person and task as a view.
I'm storing associations in session (through memorize) in your case you would store them in database.
Your structure seem to be OK. If you use setModel() on it which would have "pointsleft" and "backlog" fields, those would be automatically filled in.
I don't see how setID is defined though, but you could extend setModel, call parent and then execute that too.
Another thing I noticed, is in your template the most top-level div should have id=''. This gives your view unique selector which js() uses by default.
The .post function you are looking for is univ()->ajaxec(). It sends data to the server, receives javascript and executes it, hence the name. It behaves similarly to the form.
$mybutton->js('click')->ajaxec($this->getDestinationURL(null,array('a'=>'b'));
if($_GET['a']){
// update database
$r->getElement('plfat')->js()->reload()->execute();
}
Usually to make your code universal, you can drop this above code inside the view, but instead of 'a' you should better use the name of the object, like this. This eliminates the need for a separate page handling update:
$this->mybutton->js('click')->ajaxec($this->getDestinationURL(null,
array($this->name=>'reload'));
if($_GET[$this->name]){
// update database
$this->js()->reload()->execute();
}
Update
To clarify the sequence of how it's executed:
The page is rendered into HTML sent to your browser.
Along with the page Javascript chains are sent. All of them which define 1st argument to js, such as js(true), js('click'). in my code i have js('click') so it's sent to browser.
User performs the action such as clicking on a button. This triggers ajaxec() function
ajaxec function performs AJAX request to the page with the arguments you specify there.
PHP again is executed, but this time it goes inside if() branch. A js() without argument is created and ->execute() sends javascript to the browser.
browser receives output of the js()...->execute() and evaluates it. In our case it contains reload() for some other element.
atk4_loader widget is used to perform reload of other part of the page it sends AJAX request to server
PHP is executed with cut_object argument. It re-initializes original page, but renders only one object selectively. Output for that object is sent back to the frontend.
PHP also re-generates JS chains like in #2 but only relevant to that object
Frontend's atk4_loader receives the code, replaces HTML of the element and re-evaluates the javascript.
back to #3
It sounds like a lot of actions. In reality that's 2 requests per click and you can eliminate one if you do reload right away. Note that you can also pass arguments to reload() which you can then fetch from "get". I don't fully understand what triggers the action in your original script, perhaps we can find this out in https://chat.stackoverflow.com/rooms/2966/agile-toolkit-atk4 ?
I am using Symfony 1.3.2 with Propel ORM on Ubuntu 9.10.
I have developed a form that dynamically populates a select widget with cities in a selected country, using AJAX.
Before the data entered on the form is saved, I validate the form. If validation fails, the form is presented back to the user for correction. However, because the country list is dynamically generated, the form that is presented for correction does not have a valid city selected (it is empty, since the country widget has not changed yet).
This is inconvenient for the user, because it means they have to select ANOTHER country (so the change event is fired), and then change back to the original country they selected, then FINALLY select the city which they had last selected.
All of this is forced on the user because another (possibly unrelated) field did not vaildate.
I tried $form->getValue('widget_name'), called immediately after $form->bind(), but it seems (infact, IIRC, if form fails to validate, all the values are reset to null) - so that does not work.
I am currently trying a nasty hack which involves the use of directly accesing the input (i.e. tainted) data via $_POST, and setting them into a flash variable - but I feel its a very nasty hack)
What I'm trying to do is a common use case scenario - is there a better way to do this, than hacking around with $_POST etc?
What I do for this exact issue is that I post the form to the same action that generated it, and in that action, I grab any selected countries/regions/cities as POST variables and pass them back to the template (regardless of validation). In the template, I then use JQuery to set the select values to what they were. When validation passes, they get used. When not, they get passed back to template.
If you can tolerate a little PHP in your JQuery, you could do this in the template:
$(document).ready(function()
{
$("#country-select").val('<?php echo $posted_country; ?>');
});
If you use this approach, don't forget to initialise $this->posted_country in your template the first time around or Jquery will get confused.
I guess you could also use $this->form->setWidget(...)->setDefault(...) or something similar, but I havent found a way around using $_POST as accessing the elements seems to need binding the form otherwise.
UPDATED CODE IN RESPONSE TO COMMENTS BELOW:
if($_POST['profile']['country_id'] != '')
{
$this->posted_country = $_POST['profile']['country_id'];
$q = Doctrine_Query::create()
->select('c.city_id, c.city_name')
->from('City c')
->where('c.country_id = ?', $this->posted_country);
$cities = $q->execute(array(), Doctrine_Core::HYDRATE_NONE);
foreach($cities as $city) $list[$city[0]] = $city[1];
$this->form->setWidget('city_id', new sfWidgetFormChoice(array('choices' => array('' => 'Please select') + $list)));
}
So... I get the country from the post, I query db with that, get cities, and craft cities back into a dropdown. Then in the template, you can set a default selected city with something like $this->posted_city (which would be a POST variable too, if exists).