Back to Basics: Forms

This is my second post in a series of 52 (yes, yes I've delayed a lot but I would prefer later, better posts than useless, on-time posts).

Forms are something that I end up coding on almost every website I make (without using a CMS, that is). Essentially, while making a form I have to:

  • Write HTML code for the forms giving appropriate names and ids.
  • Write PHP code that reads in these names from POST or GET and then filter them.
  • Create appropriate error messages in PHP based on incorrect data provided in forms, and repopulate correctly filled fields in the form for the sanity of users.
  • Write Javascript (or use a plugin from jQuery) to validate the fields inline using the exact same rules and show messages to users before submitting the form.
  • Debug because I missed a character or capitalized something I shouldn't have.
  • And then I realize I missed something, and then repeat.

This is also known as web developer hell. Somewhere near the inner circles.

Ideally, what would I want to do to get a form ready?

Specify what I want at one single place with some convenient format (— did anyone say JSON?)

So essentially, this post covers:

  1. Specifying a (modifiable) JSON format for forms.
  2. Generating HTML using PHP for those forms.
  3. Generating rules in PHP using this format.
  4. Generating javascript for validation using this format.

Building the specification:

Call it a whim or a fancy — I want to use JSON for my specifications. I cannot think of any other more convenient format for specifying data to be used in PHP and Javascript.

Let's take a look at all available form elements:

  1. input tags:
    1. button
    2. checkbox
    3. file
    4. hidden
    5. image
    6. password
    7. radio
    8. reset
    9. text
    10. submit

    I'll only be taking a look at the types highlighted in bold text.

  2. textarea
  3. select
    1. option
    2. optgroup
  4. button

The specification as it is now

[{
    'name' : '[form-name]' //Name and id of the form to be created.
    'class'   : '[ '[class1]', ... ]'
}, ...]

What do I need to specify for the form?

  • The form structure — the JSON spec must follow the structure that the form will take. Specifying a contents array seems to be the best possible solution to that, allowing and defining fieldsets for forms nested inside forms.
    [{
        'name' : '[form-name]',
        'contents' : [
            {
                'name' : '[fieldset-name]',
                'legend' : '[fieldset-legend]',
                'class'   : '[ '[class1]', ... ]'
                'contents' : [ ... ]
            }
        ]
    }, ...]
    
  • So now we get down to the meaty part. Defining elements. Each element is an object with a type, name, label, an array each for attributes and classes, and an array for validation data.
    [{
        'name'    : '[form-name]',
        'caption' : '[form-caption]',
        'class'   : '[ '[class1]', ... ]'
        'contents' : [
            {
                'name'      : '[fieldset-name]',
                'legend'    : '[fieldset-legend]',
                'contents'  : [
                    {
                        'type' : 'input-text',
                        'name' : '[name and id of the object]',
                        'label': '[its label. duh.]',
                        'attr' : [ '[attr-name]' : '[value]' , ... ],
                        'class': [ '[class1]', '[class2]' ],
                        'rules': [ ... ]
                    }
                ]
            }
        ]
    }, ...]
    

To be continued.

Hostel Collapses! More than 50 laptops feared damaged and destroyed!

30/01/2010 The Windy Hostel, Indian Institute of Consultancy, Delhi: At 11.05 a.m. today morning a horrifying accident occurred because of gross negligence by engineers at Windy Hostel, IICd. The hostel had been undergoing renovation for over a year and work had recently started on a new block today. Students were still residing in the 4-story hostel on the top 2 floors while the bottom floors had been vacated.

In order to complete his work on time, the contractor had allegedly told the workers to demolish the lower portion of the building and start renovation work on it, without considering whether the already considerably weakened, 40 year old structure could take the weight. The inevitable occurred, with the top two floors crashing down and burying and damaging many laptops.

In the words of one of the surviving students (who has requested to remain unnamed) "They were destroying the doors beneath our room and the balcony start moving wildly, deflecting as much as 1 cm. We ran to stop them, but the [expletive deleted] workers refused to budge."

The maintenance secretary of the hostel was allegedly gallivanting somewhere in East Delhi during the incident, meeting some foreigner. On being contacted he replied that he had an urgent meeting with someone he could not name -- a fact that has been noted by the investigating authorities who have taken him into custody. We managed to get a statement from the Chief Investigator, Mr. M. Adi "We have not ruled out the involvement of the maintenance secretary, and are also considering the foreign angle", obliquely referring to the recent statement by the President of United States of Pakerica, Mr. Obama Bin Bush.

Being a holiday, most of the students were sitting in their rooms during the accident, apparently trying to block their internet access so as to be able to prepare for their upcoming examinations. A quote by one of the IICians from our archives: "Our professors believe that we can obtain everything we need to learn by surfing the internet -- in fact they maintain a check to see that all students download at least 100MB of data every day to ensure they are spending enough time on the internet. We have learnt a lot but it becomes difficult to adhere to this rule during our minor exams so trying to outsmart our professors and blocking our internet access is a favourite pass-time for IICians during the exam season."

Most of the students were taken by surprise as the building came crashing down on them, and more than 50 laptops have been reported missing and are assumed to still be buried under the rubble, while 10 damaged (2 critically) laptops have been recovered. One or 2 lucky laptops survived on their battery life and were discovered as they were playing heavy rock and could be heard through the concrete. Worried students at IIC have kept a candle light vigil outside the laptop repair shop, with the very best technicians of the top laptop manufacturers including Nosy Baio, Sell and Compact working tirelessly to save the laptops. More technicians are expected to arrive from around the world soon. Excavation work to locate the remaining laptops is also underway.

Many IICians are still in shock, with many roaming around in a daze. A particularly sad case is that of a few students, who, being deprived of access to their laptops and the Facebook live feed appear to have devolved to animals -- with one imitating a bull, another squealing in French like a pig and the  worst affected keeps trying to fly off the top of the hostel and is constantly restrained by his friends. It is currently not clear whether he has delusions about being a bird or being the Man of Steel (both being able to fly).

What has made this accident even more unique is the fact that there have been various reports of the accident being a complete fabrication and fallacy as people have allegedly communicated with the missing residents of the hostel (using their own laptops). In the public interest, we reiterate that the accident has happened and any such rumours must be disregarded as utter nonsense.

There have been suspicions of paranormal activity at the site of the accident because of these apparent messages and the top investigative news channel in India -- IndiaTV -- has sent its best reporter to find out the truth. The initial findings of the reporter will be presented on tomorrow's primetime show at 8 p.m. -- "IIC ke khooni engineer". Insiders (who wish to remain unnamed) have said that such a tragic parting of nerds with their computers can cause their ghosts to linger on till they manage to complete their last wish: to update their status messages. Only then will they be able to pass on to the afterlife. As always, there are many skeptics who have denounced this theory, claiming that the ghosts need to play one last LAN game of AoE.

In a surprise turn of events, famed teen impersonator and actor Aamir K. and ex-IICian and MBA B. Chetan came together in support of the missing laptops. They said that they has put aside all differences to be able to garner even more publicity for their film/book as people had stopped discussing their recent disagreements.

Reliance ZTE/ONDA on Linux

It seems fitting that my first post for project 52 (albeit a bit late) involves connecting to the internets. 'Cause that is generally the first step on all most of the stuff I do on the computer.

I have a HSD Reliance ZTE datacard/modem which I had been unable to run on Linux till tonight. The interesting bit is, I have had this card for around 7 months now -- and it was forcing me to use Windows Vista (the horror, the agony, the pain!).

As a log (in case my computer gets formatted sometime in the future -- a likely, but not hoped for occurrence -- ) as well as a possible guide to others, here are the steps I followed.

Note: I'm using Ubuntu 9.10 with a Reliance NetConnect ZTE AC8710 modem.

  1. Connect to the net using some other, temporary connection
    1. Get usb-modeswitch. Those with access to a repository can simply do
      sudo apt-get install usb-modeswitch
      

      Others can get the latest version from http://www.draisberghof.de/usb_modeswitch/ .

    2. You will also need (do an apt-get as required)
      lsusb, libusb-dev, wvdial, modprobe
      
  2. Connect your modem and run
    lsusb
    

    You should see one of the usb ports having your modem -- it will probably be classified as ONDA and have a vendor/product id specified. Along the lines of

    192d:fff6
    

    The fff6 indicates that it has been detected as a flash drive/cd rom and not as a modem.

  3. Also do a
    dmesg | tail
    

    And observe where the modem has gone -- usbtty0 / 1 / 2/ 3 etc.

  4. Edit the usb-modeswitch configuration to make your computer recognize it as a modem
    sudo vim /etc/usb_modeswitch.conf
    

    Navigate till you find the settings for your vendor id/product id.

    ########################################################
     568 # ZTE AC8710
     569 #
     570 # Two ID variants known; check your default
     571 #
     572 # Contributor: Michael Khurtsiya
     573
     574 ;DefaultVendor=  0x19d2
     575 ;DefaultProduct= 0xfff5
     576
     577 ;TargetVendor=   0x19d2
     578 ;TargetProduct=  0xffff
     579
    <strong> 580 # No. 2
     581
     582 ;DefaultVendor=  0x19d2
     583 ;DefaultProduct= 0xfff6
     584
     585 ;TargetVendor=   0x19d2
     586 ;TargetProduct=  0xfff1
     587
     588 # only for reference
     589 # MessageEndpoint=0x05</strong>
     590 <strong>
     591 ;MessageContent="5553424312345678c00000008000069f030000000000000000000000000000"</strong>
    

    And remove the ';' before the required lines. Save and exit.
    Run it.

    sudo usb_modeswitch
  5. Check whether it's worked -- do another
    lsusb
    

    and see that the product id has changed to fff1 (or whatever your target product was).

  6. Now we need to do a modprobe
    modprobe usbserial vendor=0x19d2 product=0xfff1
    

    Replace vendor and prodcut as you require.

  7. Once that's done, you need to make your wvdial.conf file. To edit the file:
    sudo vim /etc/wvdial.conf
    

    Copy paste the following in it.

    [Dialer Defaults]
     Username = &lt;enter your 10 digit modem number here&gt;
     Password = &lt;enter your 10 digit modem number here&gt;
     Init1 = ATZ
     Init2 = ATQ0 V1 E1 S0=0 &amp;C1 &amp;D2 +FCLASS=0
     Modem Type = Analog Modem
     Phone = #777
     ISDN = 0
     SetVolume = 0
     FlowControl = Hardware (CRTSCTS)
     Modem = /dev/ttyUSB0 &lt;modify based on the results of your dmesg&gt;
     Dial Command = ATDT
     Baud = 460800
     Stupid Mode = 1
  8. Once that's done, you should be good to go. Simply run
    sudo wvdial
    

And you should be connected. Hopefully this helps someone and prevents them from wasting as much time as I did.

Sources:

Boredom. My worst nemesis. My best ally.

I get bored very easily.

Gaping Void, Hugh Macleod

Cartoon by Hugh Macleod

It may be because I have nothing to do; or I've lost interest in what I was doing for some reason -- it being too repetitive, etc.; I have too little to do; what I'm working on doesn't seem to have any apparent purpose; or even if only some senses are occupied and others left alone.

I try to get over this foible of mine by listening to music -- hence the headphones hanging around my neck or on my ear, 24 by 7 by 4 by 12 by ~20. At least, by keeping my ears occupied I can relax, and possibly not get bored. This has also resulted in my having a 70GB music + video collection on my iPod.

But I digress.

I have come to realize that if I did not get bored so easily -- I would have achieved less than half of what I have today. There would be no reason for me to tread on the fine line of just enough work to do; I could have relaxed a bit more -- and perhaps enjoyed a bit less.

On the other hand, I have abandoned certain projects because I found out that they were no-where near as challenging as I'd imagined and hoped for, and were rather achievable -- and no longer interesting; because I no longer believed that the work I was doing served any purpose.

What pushes me -- and also stops me from working -- is my characteristic of getting bored so quickly. Paradoxically, it makes me give up and move ahead at the same time.

And ever since I've had more to do -- or more that I want to do -- I lose my patience with other things even more quickly. I can no longer comfortably watch a film in a cinema hall -- my hands are unoccupied, and depending on the film -- perhaps even my brain.

Doing only one thing at a time is possible only if it is interesting enough to merit my full concentration. Hence the rabid multi-tasking -- reading a book with lunch while listening to music or maybe watching television. Coding while watching a film or having a conversation. Social Networking while reading a comic. etc. etc.

What about you?

Another passage, after a long long time

So I haven't been blogging lately -- to be honest; I had hoped to let this blog die a natural death and so on and move to different (PHP5 supporting) hosting but I was inspired a bit back and am taking baby steps on this blog.

The plans to move this blog are still underway, just a bit blocked by certain other stuff I'm doing right now. How many of these posts survive the transition is a point I have not yet decided. A few certainly; all -- definitely lot.

Back to the point -- from The Ground Beneath Her Feet / Salman Rushdie

These things are bad for you: sex, high-rise buildings, chocolate, lack of exercise, dictatorship, racism! No, au contraire! Celibacy damages the brain, high rise buildings bring us closer to God, tests show that a bar of chocolate a day significantly improves children's academic performance, exercise kills, tyranny is just a part of our culture so I'll thank you to keep your culture-imperialist ideas of my fucking fiefdom, and as for racism, let's not get all preachy about this, it's better out in the open than under some  grubby carpet. That extremist is a moderate! That universal right is culturally specific! this circumcised woman is culturally happy! That Aboriginal whistlecockery is culturally barbaric! This image has been faked! Free the press! Ban nosy journalists! The novel is dead! Honor is dead! God is dead! Aargh, they're all alive, and they're coming after us! That star is rising! No, she's falling! We dined at nine! We dined at eight! You were on time! No, you were late! East is West! Up is Down! Yes is No! In is Out! Lies are Truth! Hate is Love! Two and two makes five! And everything is for the best, in this best of all possible worlds.

Xenocide

Food. Warmth.

These were the thoughts that scurried through his brain. Over and over.

Times were harsh. Friends and family were disappearing; and no one knew where they went. Those sent on foraging missions disappeared, and some were found -- dead -- after an extremely long time.

It had been generations since the world had been warm. He had been born in hardship; suffering was all that he knew. No one alive knew what it had been like before. But they all agreed on one thing: life had been much better then. It was much worse now.

It wasn't like they hadn't tried. There had been attempts to go to better places; but none had been successful as far as they knew. There had only been one survivor from their expeditions -- and he had arrived half-mad, half-dead and died quickly afterwards. The only things he spoke of was some poison air, a great white light and giants.

Giants! Hah. There were always rumours, but none had been proven. All they saw was simply a result of nature... Giants. Stuff of dreams and nonsense. All of them dismissed all claims.

But there were always those awful rumours, always whispered. Of the mountains moving, killing them, hitting them. Covering them with their poisonous breath... But that was all they were -- rumours.

He was suddenly woken from his reverie by his brother. It was happening again! The gate to salvation -- to heaven was opening! And he had been chosen to investigate! He was afraid, true, but it was for the good of the colony.

He quickly, nervously, scurried through the gate.

Where I stepped on it, and ended another pain-in-the-neck ant's life.

Plans.

  1. A complete redesign of this blog, from the ground up.
  2. Editing and trimming posts I like, and deleting those I don't.
  3. Handling tweets better.
  4. Creating a personal framework of Javascript MVC to interact with CodeIgniter.
  5. An adobe AIR Application for making and saving notes.
  6. A fb extension for said application.
  7. A web based feed reader.
  8. Tutorials for most of the stuff above on this blog.

The best laid schemes o' mice an' men
Gang aft agley.

-Robert Burns

How to study like an IITian

Looking through the hits on my blog from Search, I noticed a few based on "how to study like an IITian". Frankly speaking -- I'm sure there are a lot of misconceptions floating around out there about how IITians study (further spread by the infamous 5 pointers) -- so in the interests of improving the level of information on the internet and in public interest, allow me to elaborate.

The Golden Rule, The First Commandment and the Code by which every IITian must live by is never do anything before the last minute. If the presentation is due at 13.00, completing it before 12.30 is blasphemy and before 12.00 means that the concerned IITian has been abducted by aliens and replaced by a doppleganger. Lab reports -- even those involving 30 pages of writing, 10 pages of calculations and 20 graphs each with atleast 50 points (all of which must be drawn exclusively by hand) must never be started before the night before it is due. You get my drift, I assume.

Those who actually buy books are an endangered species -- fast dying out. Books are arranged by jugaad, through seniors, not returning books to the insti library, from the hostel library, photocopies, not buying at all. And so on.

Class Notes are an alien concept conceived by the same alien dopplegangers I mentioned earlier. And are photocopied and distributed throughout. Repeatedly.

Reading room is a euphemism for something else involving socializing, ornithology, etc. Ex(hibition) Hall is often mentioned with an extra s appended on the right word. The only way to actually accomplish anything is  to sit facing the wall, with a pair of headphones. And maybe blinkers.

Another phenomenon often observed is that group study is extremely popular. I always doubt the efficacy of this method, though people I know are extremely successful in following this method. Including my room-mate and batch-mates. I have failed miserably in earning marks through group study.

And of course -- time devoted to study. If we did devote as much time to studies as the 5(!?) pointers did, we would've been 9 pointers. Without the (excessive) blessings of the Gods and daily devotion periods. Self study is something you fit in between extra-currics, video games, sleep (4 hours or so) and classes. If you do.

Hope that helps. Yours as always.

--Me.

Interning @ Yahoo!

A bit of background first: I joined Yahoo!  Bangalore in May for a 10 weeks summer vacation internship. And my first industry experience.

So: what did I work on? Stuff that involved extensive use of a keyboard, monitor (2 in fact) and a touchpad (occasionally even a mouse). Apart from that, I'm not sure what I'm allowed to speak about, so to avoid any unnecessary complications, I'll leave it at that.

Let's start at the beginning, shall we. Day zero: Go and see the Y! building from outside. Getting into the business park was a bit difficult, so didn't try venturing into the building itself. Day one: Arrive at 8.30 in the morning, wondering what I'll be doing. Completely dressed up in formals, of course. I mean, which company doesn't expect shirts, trousers and black shoes? A lot of them, apparently. Including Y!.

9.30: My introduction to Y! . A 2 hour presentation followed by an intro to my team. I am completely amazed by the office -- themes for each floor; Cafe Coffee Day machines on every corner; neat and clean cubicles. Even better than what I'd expected after having seen the Adobe office in Delhi during India's first WordCamp.  My computer wasn't quite ready yet, so I was given a quick introduction to search engines, the structure, etc. by my Team Leader and Manager. Which, in itself, was pretty cool. My computer was set up by the end of the day, but getting it to run was a pretty big problem without support.

Finally, near the end of the day -- it was working. I quickly set up/was helped in setting up my email, Cube No., etc etc. And customizing my desktop. So I was set to reading about a lot of stuff maintained by Y!, which I would be working on. And this kind of went on for the first week -- orientation, reading up a lot of stuff, presentations and clarifications by my team leader; and I click my way through to Friday, setting up a dev environment (customizing Vim, etc.) and so on.

Come Friday, and my team's changed. Which was a bit strange -- but there wasn't anything I could have managed to do wrong by then, so I wasn't that worried. And I probably shouldn't have been, from what I've seen of Y!. ( Y! is so much easier to type than any pronouns, or the company name.)

Week 2: I'm introduced to my new Manager and Team Leader -- my computer's still the same till now. And then I start reading up on new stuff that I'll be using/working on. Re-run 1st week, with a different context. Oh, and I also move to a laptop; as the desktop hasn't been removed yet, I start using both the Desktop's huge monitor and my laptop's average one together. The downside to a laptop -- I'm stuck with Windows; the up-side? I can carry it to conferences and all. And finally, near the end of the week, I'm told about what I'll be working on. Something or the other.

Week 3 onwards is kind of a blur -- I walk into office anywhere between 8 and 11, stay till anywhere between 1 and 3 (am), learn a lot -- both related to computers and pool -- annoy my team leader with strange questions related to the environment I'm working in. And have fun. Weekends are spent crawling around malls looking for books (Landmark being my favourite), having iced coffee at Gloria Jeans Coffee -- and wondering about the requirement of weekends in general for certain kinds of jobs. Occasionally I would be bored enough to walk into office, get some work done, play some pool. Also joined the gym during this time, and kept a goatee. And a moustache.

Somewhere around the middle, I gave my first presentation. I even spent half the night photoshopping 2 flickr images to make a nice image for my debugging tool. It was during this time that I started walking into office at around 10 and leaving anywhere between 1 and 3 am.

I distinctly remember the first night I spent at office. I had initially planned to leave at 11, as I needed some help from someone across timezones. By the time I was ready to catch a cab, it was pouring heavily; and the solitary cab that had managed to reach the office was already overcrowded -- I turned, went to the Cafe, bought a Red Bull (my first) and marched back to my cube. And worked till 3 am. Followed by 2 hours of pool with some other insomniacs (and people who had come back from home 'cause of power cuts). And then some more work till 7 am. After which I caught an auto home.

I spent 1 or 2 more nights at office after that day. There always used to be a few people around. The longest I stayed at office was some 30 hours or so -- during the hack day. I brought along a change of clothes, a towel and other toiletries -- stayed up throughout the night, worked on my hack (http://kunal-b.in/Tangent2) and had more concentrated doses of caffeine than I had probably ever had before. I'm sad to say that my hack bombed and didn't even reach the top 40, but it was an interesting experience.

Life went on, office, various malls et al. Landmark, novels and comics being my primary source of entertainment.

Perhaps too soon, I reached the end of my intern. I gave my final presentation -- which was well received (or I hope it was) -- and spent a week adding a bit more stuff to the final part of my project and handing over whatever I had done to a FTE Y!. And then, back.

After such a long, stream of consciousness typish post, a short summary: Went to Y!, set up camp in office, had fun, did some work, made quite a few friends, played pool and came back to college (but didn't want to).

Passage: Carl Sagan, Cosmos

A book is made from a tree. It is an assemblage of flat, flexible parts (still called "leaves") imprinted with dark pigmented squiggles. One glance at it and you hear the voice of another person -- perhaps someone dead for thousands of years. Across the millenia, the author is speaking clearly and silently inside your head directly to you. Writing is perhaps the greatest of human inventions, binding together people, citizens of distant epochs who never knew one another. Books break the shackles of time, proof that humans can do magic.