Creating a re-organizable list of Items using Drag and Drop in Oracle ADF

Sometimes the requirement is to create a list of UI Items which can be rearranged using Drag and Drop in Oracle ADF, similar to the one in jQuery.

Oracle ADF Drag and Drop doesn’t provide the ability to identify, where the drag object is being dropped in the drag target. Thus we cannot know where to place the dropped element in the list.

here is the solution to the same:
Assumption:
–each element is same and is being iterated in a for loop over a list.
–Here dummy data is being used
Here is the below jsff segment:

<af:forEach var="v" varStatus="vi" begin="0" end="10">
    <af:panelGroupLayout id="pgl1">
      <af:dropTarget dropListener="#{managedBean.itemInsertAbove}"
                     actions="MOVE">
        <af:dataFlavor flavorClass="javax.faces.component.UIComponent"/>
      </af:dropTarget>
    </af:panelGroupLayout>
    <h:panelGroup styleClass="" id="pg1232">
              <af:outputText value="#{vi.index}" id="ot1"><af:componentDragSource/></af:outputText>
    </h:panelGroup>
    <af:panelGroupLayout id="pgl1">
      <af:dropTarget dropListener="#{managedBean.itemInsertBelow}"
                     actions="MOVE">
        <af:dataFlavor flavorClass="javax.faces.component.UIComponent"/>
      </af:dropTarget>
    </af:panelGroupLayout>
</af:forEach>

below is the Java Code for the managed bean:

needed imports:

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import oracle.adf.view.rich.component.rich.layout.RichPanelGroupLayout;
import oracle.adf.view.rich.context.AdfFacesContext;
import oracle.adf.view.rich.datatransfer.DataFlavor;
import oracle.adf.view.rich.datatransfer.Transferable;
import oracle.adf.view.rich.dnd.DnDAction;
import oracle.adf.view.rich.event.DropEvent;

import org.apache.myfaces.trinidad.change.ChangeManager;
import org.apache.myfaces.trinidad.change.MoveChildComponentChange;
import org.apache.myfaces.trinidad.context.RequestContext;

    /**
     * @param dropEvent
     * @return
     */
    public DnDAction itemInsertBelow(DropEvent dropEvent) {
        Transferable transferable = dropEvent.getTransferable();
        UIComponent dragComponent = null;
        dragComponent = transferable.getData(DataFlavor.UICOMPONENT_FLAVOR);
        UIComponent dropTarget = dropEvent.getDropComponent();
        UIComponent grp = dropTarget.getParent().getParent();
        UIComponent compToMove = dragComponent.getParent();
        grp.getChildren().remove(compToMove);
        int targetIndex = grp.getChildren().indexOf(dropTarget.getParent());
        grp.getChildren().add(targetIndex + 1, compToMove);
        ADFUtils.refreshComponent(grp);
        return DnDAction.NONE;
    }

    /**
     * @param dropEvent
     * @return
     */
    public DnDAction itemInsertAbove(DropEvent dropEvent) {
        Transferable transferable = dropEvent.getTransferable();
        UIComponent dragComponent = null;
        dragComponent = transferable.getData(DataFlavor.UICOMPONENT_FLAVOR);
        UIComponent dropTarget = dropEvent.getDropComponent();
        //        System.out.println(dropTarget.getParent());
        UIComponent grp = dropTarget.getParent().getParent();
        UIComponent compToMove = dragComponent.getParent();
        grp.getChildren().remove(compToMove);
        int targetIndex = grp.getChildren().indexOf(dropTarget.getParent());
        grp.getChildren().add(targetIndex, compToMove);
        ADFUtils.refreshComponent(grp);
        return DnDAction.NONE;
    }

this code allows you place rearrange the list of items using drag and drop:

I1
I2
I3
I4
I5
I6
I7
I8

can be converted to by picking up I3 and placing it between I5 and I6 :

I1
I2
I4
I5
I3
I6
I7
I8

How to include a JavaScript file in another JavaScript file

There are two main ways to achieve this:

1 – You can load it with an Ajax call and then use eval.

This is the most straightforward way, but it’s limited to your domain because of the JavaScript safety settings, and using eval is opening the door to bugs and hacks.

2 – Add a script tag with the script URL in the HTML.

This is definitely the best way to go. You can load the script even from a foreign server, and it’s clean as you use the browser parser to evaluate the code. You can put the <script /> tag in the head of the web page, or at the bottom of the body.

Both of these solutions are discussed and illustrated in JavaScript Madness: Dynamic Script Loading.

Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performance.

It means that if you use these tricks directly, you won’t be able to use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.

For example: my_lovely_script.js contains MySuperObject:

var js = document.createElement("script");

js.type ="text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);var s =newMySuperObject();Error:MySuperObjectisundefined

Then you reload the page hitting F5. And it works! Confusing…

So what to do about it ?

Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses en event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. For example:

function loadScript(url, callback){// Adding the script tag to the head as suggested beforevar head = document.getElementsByTagName('head')[0];var script = document.createElement('script');
    script.type ='text/javascript';
    script.src = url;// Then bind the event to the callback function.// There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;// Fire the loading
    head.appendChild(script);}

Then you write the code you want to use AFTER the script is loaded in a lambda function:

var myPrettyCode =function(){// Here, do what ever you want};

Then you run all that:

loadScript("my_lovely_script.js", myPrettyCode);

OK, I got it. But it’s a pain to write all this stuff.

Well, in that case, you can use as always the fantastic free jQuery library, which let you do the very same thing in one line:

$.getScript("my_lovely_script.js",function(){

   alert("Script loaded and executed.");// Here you can use anything you defined in the loaded script});

 

Source: StackOverflow Question

How to make a dropdown as readonly in html

I encountered a problem where in it was required to make a drop down readonly.

While searching over internet i found THIS
But the solution mentioned there, didn’t appeal me much. As i had to make server side code changes while saving the value using the hidden field.

How do we do this? The common thought is to disable the drop down menu. Well, yes, but there’s a choice

When you use disabled, it prevents the user from using the drop down, or form element. You can see the year, but it is grayed out. Your mouse can’t select or change it, and you can’t tab to it with the keyboard. Disabled is used a lot with checkboxes. Sounds like just what we want, but you unknowingly might have caused yourself a small development problem.

The problem is “disabled” does just that. Disabled means that in your $_POST or $_GET that element will not show up in your controller. If you want to use the year in your controller, you won’t be able to recover it from that form. All you can do it look at the value on the web page.

What if we want to read the year, prevent the user from changing the year, and recover the year in the form data sent back to the controller. The solution for this is

Make a replica of your dropdown with a different name and different id.

Hide your original drop down with
This makes the element available in the form, so it will flow to the server side as well.
At the same time, it will give a look and feel of disabled to the user.

Example :



            
                  
            




            
      

How to expand collapse (toggle) div layer using jQuery

Thanks to http://designgala.com/how-to-expand-collapse-toggle-div-layer-using-jquery

In almost all of my projects, I have been using jQuery to toggle the layer. So, I thought of sharing how easy it is to expand div layer and collapse panel using jQuery. When user clicks on the header, the content gets displayed by sliding down and when you again click on the header, the content collapses.

Step 1: Include jQuery Library in head section of your html file.

Step 2:

Come up with your own html elements in body section. I chose div ‘layer1′ to be the main container where collapsible/expandable content would reside.

Next, class ‘heading’ is given to header while div ‘content’ holds the show hide layer for that heading


Header-1


Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit

Header-2


Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit

Header-3


Lorem ipsum dolor sit amet, consectetuer adipiscing elit orem ipsum dolor sit amet, consectetuer adipiscing elit

Step 3:

CSS: Now it totally depends on you to write css for your heading, div. Here’s my version of CSS for this example.

.layer1 {
margin: 0;
padding: 0;
width: 500px;
}

.heading {
margin: 1px;
color: #fff;
padding: 3px 10px;
cursor: pointer;
position: relative;
background-color:#c30;
}
.content {
padding: 5px 10px;
background-color:#fafafa;
}
p { padding: 5px 0; }

Step 4:

Again lets go to head section to add few more javascript codes.


jQuery(document).ready(function() {
jQuery(".content").hide();
//toggle the componenet with class msg_body
jQuery(".heading").click(function()
{
jQuery(this).next(".content").slideToggle(500);
});
});

Thats it!! Expandible-Collapsible panel is ready.

What? You want to see a demo…….This post is the demo in itself 🙂

Caution: When using this in blogger

Because the blogger already has a div with class content which is the parent of all the divs in the page. Hence You need to rename the content class to some other suitable name, before you try to use it with blogger.

How to get old Value with onchange() event in text box

You’ll need to store the old value manually. You could store it a lot of different ways. You could use a javascript object to store values for each textbox, or you could use a hidden field (I wouldn’t recommend it – too html heavy), or you could use an expando property on the textbox itself, like this:

<input type="text" onfocus="this.oldvalue = this.value;" 
onchange="onChangeTest(this);this.oldvalue = this.value;" />

Then your javascript function to handle the change looks like this:


function onChangeTest(textbox) {
alert("Value is " + textbox.value + "n" + "Old Value is " + textbox.oldvalue);
}

Source : http://stackoverflow.com/questions/1909992/how-to-get-old-value-with-onchange-event-in-text-box

How to replace in Javascript, when replacement string is a variable

How to replace in Javascript, when replacement string is a variable

Very often we use replace method in javascript while replacing a string literal by another string literal.
But what if we need to replace a string whose value is held in a variable.

Here is the solution…

You can use a regular expression (often referred to as a RegEx or a RegExp). Regular expressions are much more powerful than standard string matching as they can use very complicated logic

// Let's take a look at the above example using regular expressions.
strReplaceSimple = strText.replace( new RegExp( "th", "" ), "[X]" );

alert( strReplaceSimple );

As you can see, we have the same replace happening. So let’s take a look at what’s going on. Instead of passing simple target string to the replace() method, we are passing in a regular expression (new RegExp()) object instance. The RegExp() takes two arguments, the expression and the search flags (left blank in our example). There are two universally valid flags: [g] which means globally replace and [i] which
means case INsensitive. By default, the regular expression is NOT global and case sensitive.

// So let's try to do a global replace using regular expressions.
strReplaceAll = strText.replace( new RegExp( "th", "g" ), "[X]" );

alert( strReplaceAll );

We just did a global replace in ONE line of code.

strReplaceAll = strText.replace( new RegExp( "th", "gi" ), "[X]" );

alert( strReplaceAll );

We just replaced out that additional “Th” simply by adding the flag [i] into the regular expression. That’s how powerful regular expressions are. But there’s more. Regular expressions are more than just flags. Much more!

Image that for some reason, you knew about regular expressions, but you didn’t know about the case insensitive flag [i]. You could have performed the same replace using this:

strReplaceAll = strText.replace( new RegExp( "(T|t)(H|h)", "g" ), "[X]" );

alert( strReplaceAll );

This groups the two letters together, and for each letter it tells the replacing algorithm to match t OR T followed by h OR H. There is sooo much more that regular expressions can do. Unfortunately, that is outside the scope of this entry. You should really look into regular expression both in Javascript and in ColdFusion / Java. They are amazing.

But what happens if you don’t want to do a simple replace? The replace method allows some very interesting flexibility. Up until now, we have been passing a simple string in a the “replace-in” argument ([X]). But, you don’t have to. You can pass in a function pointer instead.

For this example, let’s replace out the target string with a random letter in the brackets, not necessarily the X. First we have to create a function that will return the resultant random string

function RandomString(){
// Create an array of letters.
var arrLetters = ["A","B","C","D","E","V","W","X","Y","Z"];

// Use the random() method and the modulus (%) operator to
// pick a random letter from the above array.
var intLetter = (Math.floor( Math.random() * 10 ) % 9);

// Return the random letter string we get from the
// array of letters above.
return( "[" + arrLetters[ intLetter ] + "]" );
}

Try calling the function on its own a few times, just to see how it behaves.

alert(
RandomString() + "n" + RandomString() + "n" +
RandomString() + "n" + RandomString() + "n" +
RandomString() + "n" + RandomString() + "n" +
RandomString() + "n" + RandomString() + "n"
);

As you can see, it randomly (as random as possible) picks a letter to return. Now, let’s call the replace with the RandomString() method sent as the second argument. We will do this a few times so you can see the randomness in effect.

alert( strText.replace( "th", RandomString ) );
alert( strText.replace( "th", RandomString ) );
alert( strText.replace( "th", RandomString ) );

Notice that we are passing in a POINTER to the function but not actually calling it. RandomString vs. RandomString(). There’s one thing I did not mention yet. Not only can you pass in a function as an argument, but when the replace method is taking place, it passes in the target match as an argument to this function. We could have re-written the function as such:

function RandomString2( strTargetInstance) // This is the target string match instance.
{
var arrLetters = ["A","B","C","D","E","V","W","X","Y","Z"];
var intLetter = (Math.floor( Math.random() * 10 ) % 9);

// Return the random letter string we get from the
// array of letters above. This time, though, we are
// going to include the target string to demonstrate
// that it has been passed in.
return( "[" + strTargetInstance + " : " + arrLetters[ intLetter ] + "]" );
}

Now, we will run it again, just once, so you can see it in action.

alert( strText.replace( "th", RandomString2 ) );

Want to read more on this? do VISIT HERE