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.

Back to Basics: Forms

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:

So today's post begins with a question: what editor is your favourite? Do you have separate editors based on different contexts (eg. Netbeans for Java, Dreamweaver for sites), or do you tend to stick to a single Man Friday to fulfill all your needs? Do you prefer IDEs or simple text editors?

My answer for the above questions:

I love gVIM (graphical VIM). I've set it up to work over SSH in Windows (I work on a different box and merely use my laptop as a convenient interface), hidden all menu bars and installed a colour theme pack of which I'm currently using "Evening". And I've started using VIM for every code related task I do. In defence of my choice, allow me to introduce some of the basic functionality included in VIM and some practical use cases: (Not intended as a tutorial, but a quick glimpse at the great functionality on offer)

  1. Simple Editing
    Typographical errors are the programmer's bane. And if they're not shown as errors (occasionally the case with various Javascript libraries), life becomes hell. Quick correction options in vim:

    • dw, dd, etc. Basically, both for deleting and cutting text. dw deletes till the end of the line. d2w deletes 2 words. dd deletes the current line. Entering %d on the command line (i.e. using : ) deletes the full file. D deletes until the end of the current line. Considering standard equivalents, I'm always astonished by what I can accomplish so quickly in VIM.
      I really tend to use d...d to quickly get rid of large chunks of commented code. Or simply for moving code around very very quickly.
    • r, rw, etc. d was for delete. r is for replace. Need I elaborate?
      I tend to mis-type certain words a lot. Really easy for me to just go over the offending character and type in rx, where x is the new character I want to replace it by.
    • o, i, a, A, etc. Single keypresses for: 0: add a new line after current one and start editing, O: add a new line before the current line and start editing, a: start appending after cursor, i: start inserting before cursor, A: insert stuff at end of the current line.
      A is the forgetful programmer's boon. Really useful for adding ; at the end of lines.
  2. Editing over scp/ftp/etc.
    Vim comes with a special plugin (NetRW) that lets you quickly edit files over your protocol of choice. I regularly use
    :e scp://<username>@<host>/path/
    to get a directory listing of all the files in that path; choose your file and edit away.
  3. Search and replace
    Ever changed a variable at the last minute and had to change it? Easily carry out regular expressions over very simply defined yet complex range of lines using /<pattern>/ or :s/<pattern>/<substitute>/flags. You can even carry out commands on matching portions. One of the most useful features I've used once I got the hang of it.
  4. Ranges
    Vim's flexibility in terms of defining ranges for substitution/deletion/anything you'd care to mention is amazing. One of the features I most constantly use is 'marks' that allow you to mark certain positions to be easily referenced later.
  5. Too many colour themes
    The amount of possible colour themes available is astonishing. And allows a UI freak like me to be completely satisfied with what I'm coding in. And switching quickly when I want to.
  6. Registers
    Registers allow you to cut/copy and store stuff in different named "registers and then paste where and when you want. Anyone who's shuffled through various files can easily comprehend the huge help this is.
  7. Buffers and Tabs
    Tabs are essential to any decent program today. Buffers are tabs without the graphical interface indicating their presence. The best part is while using Vim in linux I tend to use
    gVIM -p *.php
    and other such commands to quickly open all files of  a single type in tabs in a single window. Really makes finding the right file much much easier.
  8. Sessions
    Using :mksession and :source allow you to quickly open all the files you had open the last time you sat down to work. And as you get to choose where the file containing the session is saved, handling sessions becomes really simple and easy.
  9. Abbreviations
    How many times do you find yourself using common stuff like console.log() or error_log() while debugging? Just use the command
    :ab cl console.log
    and every time you type cl( (followed by a space/newline/./(/etc.) it will be automatically expanded. I imagine you can see the possibilities. Interestingly, abbreviations can be saved in sessions so if you don't want to keep an abbr. around for a long time, or have something specific (such as a class name) just use and save it in the session.
  10. Key Mapping
    Map keys to carry out your most often used commands.
  11. An awesome community
    There are thousands of sites out there with pointers on using VIM as well as an excellent Vim tips twiki. Be sure to check out the VIM tips twiki and this presentation on VIM for PHP programmers by Andrei Zmievski to get a much better idea of what VIM is capable of.

Also, for those of you who edit a lot of stuff on the web (using text boxes), install It's all text to edit any text box's contents using your favourite editor (VIM, anyone?). This post was written in gVIM, opened via "It's all text" on the excellent blogging platform provided by Wordpress.

Editors for coding?

I keep changing my desktop to suit my mood and the kind of work I'm doing around that period of time. I just switched today, and made myself a new background too.

Some screenshots:

Empty

Working out

screenshot Cube

Tangent is the 'hack' -- please do not ask me to define 'hack' -- I worked on for the Yahoo! Hack-U competition. The basic idea behind tangent is to basically allow you to fly off on tangents while reading stuff on the web -- from any browser which supports javascript.

Why a bookmarklet?

By aiming at all browsers and minimal installation -- both because I use a dual boot system and understand the pain of installing something on different browsers on different OSs, I was limited to using a Javascript Bookmarklet. There are a lot of great bookmarklets available on the net -- developers/designers shouldn't miss out on Design -- and with the powerful libraries available out there, making a bookmarklet which adds content to the page, alongwith nodes is not a problem at all.

Why the basic idea?

The inspiration for Tangent came from the way I read Trivia while surfing the net; reading up about something interesting and marking up stuff I want to read later by opening that in new tabs. Tangent just makes that easier for me to do.

Using Tangent

Get the bookmarklet here: http://kunal-b.in/Tangent . Select some text in any page, click the bookmarklet, and the rest should be pretty obvious. I'll put up a screencast as soon as I understand how to in Ubuntu.

Tangent

Finally, I've managed to make something I can be (moderately) proud of. I've tried a lot of new stuff in the new site design and I've recieved positive and highly negative reviews -- 3 and 1, respectively. What really matters to me, though -- is that I'm happy with it. What all have I learned from making the theme?

  • I used a home-brewed CSS grid; generated the css using Header-content and managed to get a full, easily customizable grid up and ready quickly. A suggestion for everyone making their own themes -- use a grid for making a blog. By keeping text and columns neatly lined up, you tend to give a basic form; some quiet space to read. It also made it much easier for me to create the alternating layout for posts while keeping the same order of html code for SEO -- just varying the classes was enough.
  • I've payed a lot of attention to typography this time around. I haven't used ems just so I can keep everything simple (as in -- whole number values of pixels) but I probably should have. Maybe I'll write something in PHP to do that for me. This design currently has a line height of 20px, with text of varying sizes. The font used for text and headings is palatino linotype; verdana, etc. are sprinkled throughout the rest of the blog in bits and pieces. I've also tried to maintain a vertical rhythm for the site, and believe that I have been successful -- more or less. Font-variant: smallcaps has been a great help for separating out links and stuff.
  • The CSS colours and typography/positioning elements have been purposely separated so that I can easily and quickly skin it. Perhaps I'll let the user choose his favourite colour theme once I get the php scripts for it up and running.
  • Fully supporting comment threading -- unlike a lot of the current batch of wordpress themes. It took me quite a bit of time to understand what went where -- Otto's blog was a great resource, but ultimately the best help was just going through the actual core files (as I was using a callback function to display comments). Maybe I should write up something about that here.
  • Tiny twitters: I've created a completely distinct -- and hopefully non-obstrusive look -- for the asides/twitters. I'll shortly be further hiding these by compacting consecutive twitters in a single box, but that, again will be sometime in the far future.

The new design

First off: there are many excellent tutorials on the net which will fulfill all you need to learn how to create Web pages. From my experience (and I have learned HTML, etc. just from the net and the occasional book) I must emphasize one point: the most difficult task in learning designing/coding is separating the grain from the chaff. As many excellent tutorials as there are, there are more completely useless tutorials, which promise the moon and end up giving stale cheese.

For those of you just beginning, I would seriously suggest http://www.w3schools.com . Don't be concerned about the staid look of the website. The content is solid gold; you get complete references, accurate information and short and sweet tutorials with loads of examples. Again, for the beginner: try reading/coding HTML - xHTML -> CSS -> Javascript -> PHP & SQL -> AJAX. This is roughly the order I went in (though I learned Javascript before CSS). Stuff I know that you (& I) should cover, but have no idea about where to fit in: XML and Flash. When (and if) I learn more about these, I'll edit this post.

A few tips while coding up websites:

  • From the beginning, ensure cross browser compatability. Whether or not you consider IE6 worthy enough to be included in the list of browsers your site appears perfectly in, depends on your personal opinion. There are those who would argue much more for all round accessibility, and those who consider the 8 years old (malfunctioning) browser obsolete. Personally, I agree with the latter. (Very few websites I design work completely in IE6).
  • Write code as if someone else will grade it. Do your best to keep stuff well commented, neatly tabbed and avoid unsightly hacks put together at the last moment. Remember, unlike coding a program, where (in most cases) the code is a secret you can carry to your grave, clicking "View Source" does allow everyone to see your sloppiness. And it ain't easy to find bugs in messy code either.
  • Keep everything W3 compliant. Always ensure that your websites are xhtml, css valid. Don't forget to put in a !DOCTYPE.
  • Try to use the best Search Engine Optimization practices from the beginning so that you get into a habit of using the proper elements at the right places. I'm afraid I still struggle and accidentally use
    h1

    where I should have put an

    h2

    . (If you don't understand what I'm talking about, you will, later.)

  • Use sprites while handling images. One of the worst impressions I can get of a site is having non-preloaded roll-over images.
  • Look at the source code of sites that you like. Wonder about how certain effects might be created and then check from the source code.
  • Use Firefox and its excellent plugins: Firebug (for looking quickly through a page, editing to find those pesky bugs on the fly and making your life much more comfortable) and Web Developer Toolbar (to do the few things firebug doesn't).
  • At all costs, never use GUI based webpage creators. Hand-code, use libraries, whatever. Don't use something which doesn't even give you a glimpse of the code.

Apart from the above, it's always good to read stuff all over the web. I'll keep putting up links here to interesting websites which give useful information, but it's better if you search for yourself.

Learning Web Designing

There are literally thousands of step-by-step tutorials for theming wordpress out there. So why one more?

Well, we all have our own unique approaches. And I've seen a lot of very bad tutorials out there. Very good ones too, but that's beside the point. This set of tutorials marks the beginning of this site's tech section; apart from that, I'll be focussing solely on Wordpress 2.7, which seems to be lacking in themes right now. (I am extremely suspicious that this may be due to the beta status wordpress is currently in, though I may be wrong.)

One of the projects I aim to do sometime in the near future involves creating a plugin for designing themes without writing a single line of code, but till then, here are some tutorials to help you theme.

Incidentally, I'm making a theme for this site at the same time. So I'll be providing screenshots as and where possible, just to get you started.

Step 1: DO THE DESIGN

Without jumping into the code, sit down and decide the blog design you want to achieve. Add all elements you want, so that nothing is left out; it's not that you won't be able to add anything later, but that it's much easier if you complete the design before you start coding.

Stuff you need to decide:

  1. Will you be creating a special splash page for when someone visits your site?
    • If yes, then what all do you plan to put there? A nice, flashy welcome; or an introduction to your site and all that lies within? Choose and design appropriately.
      Here's what I made for my site:

      Home design

      Home design

  2. The posts are the most important thing in your blog. Pay attention to how you place them; use plenty of whitespace; fit and choose fonts according to your preferences. Would you prefer a grid layout, or just place text any old way? Remember to use standard fonts that everyone has. Suggestion: Keep the posts in a thin column; say 400-600 px wide; makes the posts easier to read.
  3. Widgets: 2 column? 3 column? 1 column? 98, 862 columns? Which widgets do you plan to use; where do you want to put them. Also consider the footer and the header.
  4. Navigation: Blog navigation is generally neglected; consider how your blog is structured. For example, this blog has various main categories which are then subdivided; so I have a menu for each category. Do you really want the pages to be distinct from the categories, or should they blend in with posts? Depends on how you are using them / plan to use them.
  5. Feeds / Social Bookmarking: Blogs are meant to be read. Make sure to emphasize your feed; as well as give links for social bookmarking -- Digg, Stumble upon, etc. etc.
  6. Pictures: How do you want pictures to appear? Should they have an outline, a separate background, or should they be as indistinguishable from the text as possible?
  7. Comments: How do you want comments to appear? Wordpress 2.7 has added a lot of functionality -- including threaded comments which open up many design possibilities -- and complications. Remember to distinguish your comments from others. Leave space for (Gr)Avatars.
  8. Asides: Do you want to add asides to the post? Some text floating around separately? Think about it.
  9. CSS Elements: Remember to style for blockquotes, the different headings h1, h2, h3, etc., links and everything else you would be considering in normal site designing.
  10. Archives: Do you want a different style for monthly listing / listing by author / etc.? Then design for that too.

(As and when I keep completing my theme, I'll keep adding screenshots to illustrate what I mean.)

Well, I finally upgraded today. It's still in Beta mode, but it has the best backend I've ever seen from Wordpress; or blogger for that matter. Have a look at this screenshot:

Wordpress 2.7 Beta 3

Wordpress 2.7 Beta 3

Apart from a superbly remodelled backend with an excellent new look, I now have threaded comments too! I'll say type this out only once. If you're still using Wordpress 2.6, upgrade now! You really don't have any idea about what you're missing out on here!

Wordpress 2.7

Wordpress, while excellent in a lot of respects, is extremely binding in terms of widgets allowed and themes that can be created. Even editing the CSS of a page requires a paid upgrade.

This has led me to believe that the best place to maintain a blog is on your own free web-site without thousands of limitations imposed (for security reasons) by various blog-hosters.

I have decided to update my Google homepage to make it host blogs; I will be designing a completely new website, which, among other things, will also host my blog. Considering the amount of free time I get with a computer at my disposal, my little project will be finished in a trillion centuries or so. Never fear: I will try and complete it though.

I have decided to continuously give reports on my progress on the blog... how I want the site to look; the technical details (which will be separately formatted and can be safely skipped) will also be given if I find them interesting enough.

I shall begin by working on the look and deciding where to host the blog, as access to PHP is a must. This will be followed by designing a web 2.0-ish website and then implementing a comments section for posts, a calendar with posts highlighted, and many more things that the average blogger takes for granted.

This journey promises to be a highly interesting, if not easy, experience for me.

Of course, the inane babble I generally and (thankfully) occasionally type will continue till I am ready to shift.

Adios.

I know that you believe that you understood what you think I said, but I am not sure you realize that what you heard is not what I meant.
- Robert McCloskey

Shifting again…