Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds

How-To Tutorials - Web Development

1797 Articles
article-image-breaching-wireless-security
Packt
01 Jul 2013
5 min read
Save for later

Breaching Wireless Security

Packt
01 Jul 2013
5 min read
(For more resources related to this topic, see here.) Different types of attacks We will now discuss each one of these attacks briefly. The probing and discovery attacks are accomplished by sending out probes and looking for the wireless networks. We have used several tools for discovery so far, but they have all been passive in how they discover information. A passive probing tool can detect the SSID of a network even when it is cloaked, as we have shown with the Kismet tool. With active probing, we are sending out probes with the SSID in it. This type of probing will not discover a hidden or cloaked SSID. An active probing tool for this is NetStumbler (www.netstumbler.com). With an active probe, the tool will actively send out probes and elicit responses from the access points to gather information. It is very difficult to prevent an attacker from gathering information about our wireless access points; this is because an access point has to be available for connection. We can cloak or hide the SSID. The next step an attacker will carry out is performing the surveillance of the network. This is the technique we used with Kismet, airodump-ng, and ssidsniff. An example of the output of the Kismet tool is shown in the next screenshot: All three of these tools are passive, so they do not probe the network for information. They just capture it from the wireless frequency that is received from the network. Each of these tools can discover the hidden SSID of a network, and again, are passive tools. Once the attacker has discovered the target network, they will move to the surveillance step and attempt to gather more information about the target. For this, we can again use any of the three tools we previously mentioned. The information that an attacker is looking for are as follows: Whether or not the network is protected The encryption level used The signal strength and the GPS coordinates When an attacker is scanning a network, he or she is looking for an "easy" target. This is the motive of most of the attackers; they want an easy way in, and almost always, they target the weakest link. The next step that an attacker will typically pursue is Denial of Service (DoS); unfortunately, this is one area we really cannot do much about. This is because, in the case of a wireless signal, the network can be jammed by using simple and inexpensive tools; so if an attacker wants to perform a DoS attack, there is really not much that we can do to prevent it. So we will not spend any more time on this attack. The next attack method is one that is shared between the "wired" network world and the wireless world. The attack of masquerading, or spoofing as it is sometimes referred to, involves impersonating an authorized client on a network. One of the protection mechanisms we have within our wireless networks is the capability to restrict or filter a client based on their Media Access Control (MAC) address. This address is that of the network card itself; it is how data is delivered on our networks. There are a number of ways to change the MAC address; we have tools, and we can also change it from the command line in Linux. The simplest way to change our MAC address is to use the macchanger tool. An example of how to use this tool to change an address is shown in the next screenshot: In the Windows world, we can do it in another way; but it involves editing the registry, which might be too difficult for some of you. The hardware address is in the registry; you can find it by searching for the term wireless within the registry. An example of this registry entry is shown in the following screenshot: The last category of attacks that we will cover here is the rogue access point. This is an attack that takes advantage of the fact that all wireless networks have a particular level of power that they transmit. What we do for this attack is create an access point with more power than the access point we are masquerading as; this results in a stronger signal being received by the client software. When would anyone take a three-bar signal over a five-bar signal? The answer for that would be: never; that is why the attack is so powerful. An attacker can create an access point as a rogue access point; there is no way for most clients to tell whether the access point is real or not. There really is nothing that you can do to stop this attack effectively. This is why it is a common attack used in areas that have a public hotspot. We do have a recommended mechanism you can use to help mitigate the impact of this type of attack. If you look at the example that is shown in the next screenshot, can you identify which one of the access points with the same name is the correct one? This is an example of what most clients see when they are using Windows. From this list, there is no way of knowing which one of the access points is the real one. Summary Thus in this article we covered, albeit briefly, the steps that an attacker typically uses when preparing for an attack. Resources for Article : Further resources on this subject: Tips and Tricks on BackTrack 4 [Article] BackTrack Forensics [Article] BackTrack 5: Attacking the Client [Article]
Read more
  • 0
  • 0
  • 1254

article-image-installing-and-configuring-drupal-commerce
Packt
28 Jun 2013
8 min read
Save for later

Installing and Configuring Drupal Commerce

Packt
28 Jun 2013
8 min read
(For more resources related to this topic, see here.) Installing Drupal Commerce to an existing Drupal 7 website There are two approaches to installing Drupal Commerce; this recipe covers installing Drupal Commerce on an existing Drupal 7 website. Getting started You will need to download Drupal Commerce from http://drupal.org/project/ commerce. Download the most recent recommended release you see that couples with your Drupal 7 website's core version: You will also require the following modules to allow Drupal Commerce to function: Ctools: http://drupal.org/project/ctools Entity API: http://drupal.org/project/entity Views: http://drupal.org/project/views Rules: http://drupal.org/project/rules Address Field: http://drupal.org/project/addressfield How to do it... Now that you're ready, install Drupal Commerce by performing the following steps: Install the modules that Drupal Commerce depends on, first by copying the preceding module files into your Drupal site's modules directory, sites/all/modules. Install Drupal Commerce's modules next, by copying the files into the sites/all/ modules directory, so that they appear in the sites/all/modules/commerce directory. Enable the newly installed Drupal Commerce module in your Drupal site's administration panel (example.com/admin/modules if you've installed Drupal Commerce at example.com), under the Modules navigation option, by ensuring the checkbox to the left-hand side of the module name is checked. Now that Drupal Commerce is installed, a new menu option will appear in the administration navigation at the top of your screen when you are logged in as a user with administration permissions. You may need to clear the cache to see this. Navigate to Configuration | Development | Performance in the administration panel to do this. How it works... Drupal Commerce depends on a number of other Drupal modules to function, and by installing and enabling these in your website's administration panel you're on your way to getting your Drupal Commerce store off the ground. You can also install the Drupal Commerce modules via Drush (the Drupal Shell) too. For more information on Drush, see http://drupal.org/project/drush. Installing Drupal Commerce with Commerce Kickstart 2 Drupal Commerce requires quite a number of modules, and doing a basic installation can be quite time-consuming, which is where Commerce Kickstart 2 comes in. It packages Drupal 7 core and all of the necessary modules. Using Commerce Kickstart 2 is a good idea if you are building a Drupal Commerce website from scratch, and don't already have Drupal core installed. Getting started Download Drupal Commerce Kickstart 2 from its drupal.org project page at http://drupal.org/project/commerce kickstart. How to do it... Once you have decompressed the Commerce Kickstart 2 files to the location you want to install Drupal Commerce in, perform the following steps: Visit the given location in your web browser. For this example, it is assumed that your website is at example.com, so visit this address in your web browser. You'll see that you are presented with a welcome screen as shown in the following screenshot: Click the Let's Get Started button underneath this, and the installer moves to the next configuration option. Next, your server's requirements are checked to ensure Drupal can run in this environment. In the preceding screenshot you can see some common problems when installing Drupal that prevent installation. In particular, ensure that you create the /sites/ default/files directory in your Drupal installation and ensure it has permissions to allow Drupal to write to it (as this is where your website's images and files are stored). You will also need to copy the /sites/default/default.settings.php file to /sites/default/settings.php before you can start. Make sure this file is writeable by Drupal too (you'll secure it after installation is complete). Once these problems have been resolved, refresh the page and you will be taken to the Set up database screen. Enter the database username, password, and database name you want to use with Drupal, and click on Save and continue: The next step is the Install profile section, which can take some time as Drupal Commerce is installed for you. There's nothing for you to do here; just wait for installation to complete! You can now safely remove write permissions for the settings.php file in the /sites/default directory of your Drupal Commerce installation. The next step is Configure site. Enter the name of your new store and your e-mail address here, and provide a username and password for your Drupal Commerce administrator account. Don't forget to make a note of these as you'll need them to access your website later! Below these options, you can specify the country of your server and the default time zone. These are usually picked up from your server itself, but you may want to change them: Click on the Save and continue button to progress now; the next step is Configure store. Here you can set your Default store country field (if it's different from your server settings) and opt to install Drupal Commerce's demo, which includes sample content and a sample Drupal Commerce theme too: Further down on this screen, you're presented with more options. By checking the Do you want to be able to translate the interface of your store? field, Drupal Commerce provides you with an ability to translate your website for customers of different languages (for this simple store installation, leave this set to No). Finally, you can set the Default store currency field you wish to use, and whether you want Commerce Kickstart to set up a sales tax rule for your store (select which is more appropriate for your store, or leave it set to No sample tax rate for now): Click on Create and finish at the bottom of the screen. If you chose to install the demo store in the previous screen, you will have to wait as it is added for you. There are now options to allow Drupal to check for updates automatically, and to receive e-mails about security updates. Leave these both checked to help you stay on top of keeping your Drupal website secure and up-to-date. Wait as Commerce Kickstart installs everything Drupal Commerce requires to run. That's it! Your Drupal Commerce store is now up and running thanks to Commerce Kickstart 2. How it works... The Commerce Kickstart package includes Drupal 7 core and the Drupal Commerce module. By packaging these together, installation and initial configuration for your Drupal Commerce store is made much easier! Creating your first product Now that you've installed Drupal Commerce, you can start to add products to display to customers and start making money. In this recipe you will learn how to add a basic product to your Drupal Commerce store. Getting started Log in to your Drupal Commerce store's administration panel, and navigate to Products | Add a product: If you haven't, navigate to Site settings | Modules and ensure that the Commerce Kickstart Menu module is enabled for your store. Note the sample products from Drupal Kickstart's installation are displaying there. How to do it... To get started adding a product to your store, click on the Add product button and follow these steps: Click on the Product display. Product displays groups of multiple related product variations together for display on the frontend of your website. Fill in the form that appears, entering a suitable Title, using the Body field for the product's description, as well as filling in the SKU (stock keeping unit; a unique reference for this product) and Price fields. Ensure that the Status field is set to Active. You can also optionally upload an image for the product here: Optionally, you can assign the product to one of the pre-existing categories in the Product catalog tab underneath these fields, as well as a URL for it in the URL path settings tab: Click on the Save product button, and you've now created a basic product in your store. To view the product on the frontend of your store, you can navigate to the category listings if you imported Drupal Commerce's demo data, or else you can return to the Products menu and click on the name of the product in the Title column: You'll now see your product on the frontend of your Drupal Commerce store: How it works... In Drupal Commerce, a product can represent several things, listed as follows: A single product for sale (for example, a one-size-fits-all t-shirt) A variation of a product (for example, a medium-size t-shirt) An item that is not necessarily a purchase as such (for example, it may represent a donation to a charity) An intangible product which the site allows reservations for (for example, an event booking) Product displays (for example, a blue t-shirt) are used to group product variations (for example, a medium-sized blue t-shirt and a large-sized blue t-shirt), and display them on your website to customers. So, depending on the needs of your Drupal Commerce website, products may be displayed on unique pages, or multiple products might be grouped onto one page as a product display.
Read more
  • 0
  • 0
  • 2653

article-image-building-chat-application
Packt
27 Jun 2013
4 min read
Save for later

Building a Chat Application

Packt
27 Jun 2013
4 min read
(For more resources related to this topic, see here.) The following is a screenshot of our chat application: Creating a project To begin developing our chat application, we need to create an Opa project using the following Opa command: opa create chat This command will create an empty Opa project. Also, it will generate the required directories and files automatically with the structure as shown in the following screenshot: Let's have a brief look at what these source code files do: controller.opa: This file serves as the entry point of the chat application; we start the web server in controller.opa view.opa: This file serves as an user interface model.opa: This is the model of the chat application; it defines the message, network, and the chat room style.css: This is an external stylesheet file Makefile: This file is used to build an application As we do not need database support in the chat application, we can remove --import-package stdlib.database.mongo from the FLAG option in Makefile. Type make and make run to run the empty application. Launching the web server Let's begin with controller.opa, the entry point of our chat application where we launch the web server. We have already discussed the function Server.start in the Server module section. In our chat application, we will use a handlers group to handle users requests. Server.start(Server.http, [ {resources: @static_resource_directory("resources")}, {register: [{css:["/resources/css/style.css"]}]}, {title:"Opa Chat", page: View.page } ]) So, what exactly are the arguments that we are passing to the Server.start function? The line {resources: @static_resource_direcotry("resources")} registers a resource handler and will serve resource files in the resources directory. Next, the line {register: [{css:["/resources/css/style.css"]}]} registers an external CSS file—style.css. This permits us to use styles in the style.css application scope. Finally, the line {title:"Opa Chat", page: View.page} registers a single page handler that will dispatch all other requests to the function View.page. The server uses the default configuration Server.http and will run on port 8080. Designing user interface When the application starts, all the requests (except requests for resources) will be distributed to the function View.page, which displays the chat page on the browser. Let's take a look at the view part; we define a module named View in view.opa. import stdlib.themes.bootstrap.css module View { function page(){ user = Random.string(8) <div id=#title class="navbar navbar-inverse navbar-fixed-top"> <div class=navbar-inner> <div id=#logo /> </div> </div> <div id=#conversation class=container-fluid onready={function(_){Model.join(updatemsg)}} /> <div id=#footer class="navbar navbar-fixed-bottom"> <div class=input-append> <input type=text id=#entry class=input-xxlarge onnewline={broadcast(user)}/> <button class="btn btn-primary" onclick={broadcast(user)}>Post</button> </div> </div> } ... } The module View contains functions to display the page on the browser. In the first line, import stdlib.themes.bootstrap.css, we import Bootstrap styles. This permits us to use Bootstrap markup in our code, such as navbar, navbar-fixtop, and btn-primary. We also registered an external style.css file so we can use styles in style.css such as conversation and footer. As we can see, this code in the function page follows almost the same syntax as HTML. As discussed in earlier, we can use HTML freely in the Opa code, the HTML values having a predefined type xhtml in Opa. Summary In this article, we started by creating and a project and launching the web server. Resources for Article : Further resources on this subject: MySQL 5.1 Plugin: HTML Storage Engine—Reads and Writes [Article] Using jQuery and jQueryUI Widget Factory plugins with RequireJS [Article] Oracle Web RowSet - Part1 [Article]
Read more
  • 0
  • 0
  • 2362
Visually different images

article-image-choosing-your-shipping-method
Packt
19 Jun 2013
9 min read
Save for later

Choosing your shipping method

Packt
19 Jun 2013
9 min read
(For more resources related to this topic, see here.) Getting ready To view and edit our shipping methods we must first navigate to System | Configuration | Shipping Methods. Remember, our Current Configuration Scope field is important as shipping methods can be set on a per website scope basis. There are many shipping methods available by default, but the main generic methods are Flat Rate, Table Rates, and Free Shipping. By default, Magento comes with the Flat Rate method enabled. We are going to start off by disabling this shipping method. Be careful when disabling shipping methods; if we leave our Magento installation without any active shipping methods then no orders can be placed—the customer would be presented with this error in the checkout: Sorry, no quotes are available for this order at this time. Likewise through the administration panel manual orders will also receive the error. How to do it... To disable our Flat Rate method we need to navigate to its configuration options in System | Configuration | Shipping Methods | Flat Rate and choose Enabled as No, and click on Save. The following screenshot highlights our current configuration scope and disabled Flat Rate method: Next we need to configure our Table Rates method, so we need to now click on the Table Rates tab and set Enabled to Yes , within Title enter National Delivery and within Method Name enter Shipping. Finally, for the Condition option select Weight vs. Destination (all the other information can be left as default as it will not affect our pricing for this scenario). To upload our spreadsheet for our new Table Rates method we need to first change our scope (shipping rates imported via a .csv file are always entered at a website view level). To do this we need to select Main Website (this wording can differ depending on System | Manage Stores Settings) from our Current Configuration Scope field. The following screenshot shows the change in input fields when our configuration scope has changed: Click on the Export CSV button and we should start downloading a blank .csv file (or if there are rates already, it will give us our active rates). Next we will populate our spreadsheet with the following information (shown in the screenshot) so that we can ship to anywhere in the USA: After finishing our spreadsheet we can now import it, so (with our Current Configuration Scope field set to our Website view) click on the Choose File/Browse button and upload it. Once the browser has uploaded the file we can click on Save. Next we are going to configure our Free Shipping method to run alongside our Table Rates method, so to start with we need to switch back to our Default Config scope and then click on the Free Shipping tab Within this tab we will set Enabled to Yes and Minimum Order Amount to 50. We can leave the other options as default. How it works... The following is a brief explanation of each of our main shipping methods. Flat Rate The Flat Rate method allows us to specify a fixed shipping charge to be applied either per item or per order. The Flat Rate method also allows us to specify a handling fee—a percentage or fixed amount surcharge of the flat rate fee. With this method we can also specify which countries we wish to make this shipping method applicable for (dependent solely on the customers' shipping address details). Unlike the Table Rates method, you cannot specify multiple flat rates for any given region of a country nor can you specify flat rates individually per country. Table Rates The Table Rates method uses a spreadsheet of data to increase the flexibility of our shipping charges by allowing us to apply different prices to our orders depending on the criteria we specify in the spreadsheet. Along with the liberty to specify which countries this method is applicable for and giving us the option to apply a handling fee, the Table Rates method also allows us to choose from a variety of shopping cart conditions. The choice that we select from these conditions affects the data that we can import via the spreadsheet. Inside this spreadsheet we can specify hundreds of rows of countries along with their specific states or Zip/Postal Codes. Each row has a condition such as weight (and above) and also a specific price. If a shopping cart matches the criteria entered on any of the rows, the shipping price will be taken from that row and set to the cart. In our example we have used Weight vs. Destination; there are two other alternative conditions which come with a default Magento installation that could be used to calculate the shipping: Price vs. Destination: This Table Rates condition takes into account the Order Subtotal (and above) amount in whichever currency is currently set for the store # of Items vs. Destination: This Table Rates condition calculates the shipping cost based on the # of Items (and above) within the customer's basket Free Shipping The Free Shipping method is one of the simplest and most commonly used of all the methods that come with a default Magento installation. One of the best ways to increase the conversion rate through your Magento store is to offer your customers Free Shipping. Magento allows you to do this by using its Free Shipping method. Selecting the countries that this method is applicable for and inputting a minimum order amount as the criteria will enable this method in the checkout for any matching shopping cart. Unfortunately, you cannot specify regions of a country within this method (although you can still offer a free shipping solution through table rates and promotional rules). Our configuration As mentioned previously, the Table Rates method provides us with three types of conditions. In our example we created a table rate spreadsheet that relies on the weight information of our products to work out the shipping price. Magento's default Free Shipping method is one of the most popular and useful shipping methods and its most important configuration option is Minimum Order Amount. Setting this value to 50 will tell Magento that any shopping cart with a subtotal greater than $50 should provide the Free Shipping method for the customer to use; we can see this demonstrated in the following screenshot: The enabled option is a standard feature among nearly all shipping method extensions. Whenever we wish to enable or disable a shipping method, all we need to do is set it to Yes for enabled and No to disable it. Once we have configured our Table Rates extension, Magento will use the values inputted by our customer and try to match them against our imported data. In our case if a customer has ordered a product weighing 2.5 kg and they live anywhere in the USA, they will be presented with our $6.99 price. However, a drawback of our example is if they live outside of the USA, our shipping method will not be available. The .csv file for our Weight vs. Destination spreadsheet is slightly different to the spreadsheet used for the other Table Rates conditions. It is therefore important to make sure that if we change our condition, we export a fresh spreadsheet with the correct column information. One very important point to note when editing our shipping spreadsheets is the format of the file—programs such as Microsoft Excel sometimes save in an incompatible format. It is recommended to use the free, downloadable Open Office suite to edit any of Magento's spreadsheets as they save the file in a compatible format. We can download Open Office here: www.openoffice.org If there is no alternative but to use Microsoft Excel then we must ensure we save as CSV for Windows or alternatively CSV (Comma Delimited). A few key points when editing the Table Rates spreadsheet: The * (Asterisk) is a wildcard—similar to saying ANY Weight (and above) is really a FROM weight and will set the price UNTIL the next row value that is higher than itself (for the matching Country, Region/State, and Zip/ Postal Code)—the downside of this is that you cannot set a maximum weight limit The Country column takes three-letter codes—ISO 3166-1 alpha-3 codes The Zip/Postal Code column takes either a full USA ZIP code or a full postal code The Region/State column takes all two-letter state codes from the USA or any other codes that are available in the drop-down select menus for regions on the checkout pages of Magento One final note is that we can run as many shipping methods as we like at the same time—just like we did with our Free Shipping method and our Table Rates method. There's more... For more information on setting up the many shipping methods that are available within Magento please see the following link: http://innoexts.com/magento-shipping-methods We can also enable and disable shipping methods on a per website view basis, so for example we could disable a shipping method for our French store. Disabling Free Shipping for French website If we wanted to disable our Free Shipping method for just our French store, we could change our Current Configuration Scope field to our French website view and then perform the following steps: Navigate to System | Configuration | Shipping Methods and click on the Free Shipping tab. Uncheck Use Default next to the Enabled option and set Enabled to No, and then click on Save Config. We can see that Magento normally defaults all of our settings to the Default Config scope; by unchecking the Use Default checkbox we can edit our method for our chosen store view. Summary This article explored the differences between the Flat Rate, Table Rates, and Free Shipping methods, as well as taught us how to disable a shipping method and configure your Table Rates. Resources for Article : Further resources on this subject: Magento Performance Optimization [Article] Magento: Exploring Themes [Article] Getting Started with Magento Development [Article]
Read more
  • 0
  • 0
  • 1788

article-image-responsive-design-media-queries
Packt
19 Jun 2013
6 min read
Save for later

Responsive Design with Media Queries

Packt
19 Jun 2013
6 min read
(For more resources related to this topic, see here.) Web design for a multimedia web world As noted in the introduction to this article, recent times have seen an explosion in the variety of media through which people interact with websites, particularly the way smart phones and tablets are defining the browsing experience more and more. Moreover, as noted, a web page design that is appropriate may be necessary for a wide-screen experience but is often inappropriate, overly cluttered, or just plain dysfunctional on a tiny screen. The solution is Media Queries—a new element of CSS stylesheets introduced with CSS3. But before we examine new media features in CSS3, it will be helpful to understand the basic evolutionary path that led to the development of CSS3 Media Queries. That background will be useful both in getting our heads around the concepts involved and because in the crazy Wild West state of browsing environments these days (with emerging and yet-unresolved standards conflicts), designing for the widest range of media requires combining new CSS3 Media Queries with older CSS Media detection tools. We'll see how this plays out in real life near the end of this article, when we examine particular challenges of creating Media Queries that can detect, for example, an Apple iPhone. How Media Queries work Let's look at an example. If you open the Boston Globe (newspaper) site (http://www.bostonglobe.com/) in a browser window the width of a laptop, you'll see a three-column page layout (go ahead, I'll wait while you check; or just take a look at the following example). The three-column layout works well in laptops. But in a smaller viewport, the design adjusts to present content in two columns, as shown in the following screenshot: The two-column layout is the same HTML page as the three-column layout. And the content of both pages (text, images, media, and so on) is the same. The crew at the Globe do not have to build a separate home page for tablets or smartphones. But a media query has linked a different CSS file that displays in narrower viewports. A short history of Media Queries Stepping back in time a bit, the current (pre-CSS3) version of CSS could already detect media, and enable different stylesheets depending on the media. Moreover, Dreamweaver CS6 (also CS5.5, CS5, and previous versions) provided very nice, intuitive support for these features. The way this works in Dreamweaver is that when you click the Attach Style Sheet icon at the bottom of the CSS Styles panel (with a web page open in Dreamweaver's Document window), the Attach External Style Sheet dialog appears. The Media popup in the dialog allows you to attach a stylesheet specifically designed for print, aural (to be read out loud by the reader software), Braille, handheld devices, and other "traditional" output options, as well as newer CSS3-based options. The handheld option, shown in the following screenshot, was available before CSS3: So, to summarize the evolutionary path, detecting media and providing a custom style for that media is not new to HTML5 and its companion CSS3, and there is support for those features in Dreamweaver CS6. Detecting and synchronizing styles with defined media has been available in Dreamweaver. However, what is relatively new is the ability to detect and supply defined stylesheets for specific screen sizes. And that new feature opens the door to new levels of customized page design for specific media. HTML5, CSS3, and Media Queries With HTML5 and CSS3, Media Queries have been expanded. We can now define all kinds of criteria for selecting a stylesheet to apply to a viewing environment, including orientation (whether or not a mobile phone, tablet, and so on, is held in the portrait [up-down] or landscape [sideways] view), whether the device displays color, the shape of the viewing area, and—of most value—the width and height of the viewing area. All these options present a multitude of possibilities for creating custom stylesheets for different viewing environments. In fact they open up a ridiculously large array of possibilities. But for most designers, simply creating three appropriate stylesheets, one for laptop/desktop viewing, one for mobile phones, and one for tablets, is sufficient. In order to define criteria for which stylesheet will display in an environment, HTML5 and CSS3 allow us to use if-then statements. So, for example, if we are assigning a stylesheet to tablets, we might specify that if the width of the viewing area is greater than that of a cell phone, but smaller than that of a laptop screen, we want the tablet stylesheet to be applied. Styling for mobile devices and tablets While a full exploration of the aesthetic dimensions of creating styles for different media is beyond the scope of our mission in this book, it is worth noting a few basic "dos and don'ts" vis-à-vis styling for mobile devices. I'll be back with more detailed advice on mobile styling later in this article, but in a word, the challenge is: simplify. In general, this means applying many or all of the following adjustments to your pages: Smaller margins Larger (more readable) type Much less complex backgrounds; no image backgrounds No sidebars or floated content (content around which other content wraps) Often, no containers that define page width Design advice online: If you search for "css for mobile devices" online, you'll find thousands of articles with different perspectives and advice on designing web pages that can be easily accessed with handheld devices. Media Queries versus jQuery Mobile and apps Before moving to the technical dimension of building pages with responsive design using Media Queries, let me briefly compare and contrast media queries to the two other options available for displaying content differently for fullscreen and mobile devices. One option is an app. Apps (short for applications) are full-blown computer programs created in a high-level programming language. Dreamweaver CS6 includes new tools to connect with and generate apps through the online PhoneGap resources. The second option is a jQuery Mobile site. jQuery Mobile sites are based on JavaScript. But, as we'll see later in this book, you don't need to know JavaScript to build jQuery Mobile sites. The main difference between jQuery Mobile sites and Media Query sites with mobile-friendly designs is that jQuery Mobile sites require different content while Media Query sites simply repackage the same content with different stylesheets. Which approach should you use, Media Queries or JavaScript? That is a judgment call. What I can advise here is that Media Queries provides the easiest way to create and maintain a mobile version of your site.
Read more
  • 0
  • 0
  • 1234

article-image-fundamental-razor-syntaxes
Packt
18 Jun 2013
2 min read
Save for later

Fundamental Razor syntaxes

Packt
18 Jun 2013
2 min read
(For more resources related to this topic, see here.) Getting ready In this view page you can try all the Razor syntaxes given in this section. How to do it... Here, let's start learning the fundamene written using three different approaches: inline, code block, and mixed. Inline code expressions Inline code expressions are always written in a single line, as follows: I always enjoy @DateTime.Now.DayOfWeek with my family. At runtime, the inline code expression, which is @DateTime.Now.DayOfWeek, will be converted into a day, such as Sunday. This can be seen in the following screenshot: Let's look at one more example, which will pass the controller's ViewBag and ViewData messages on the view. The rendered output will be as follows: Code block expression Code block expression is actually a set of multiple code lines that start and end with @{}. The use of opening (@{) and closing (}) characters is mandatory, even for single line of C# or VB code; as shown in the following screenshot: This will render the following output: Mixed code expression Mixed code expression is a set of multiple inline code expressions in a code block where we switch between C# and HTML. The magical key here is @:, which allows writing HTML in a code block, as follows: This will render the following output: So, this is all about how we write the code on Razor view page. Summary This article thus you learned about inline code expressions, code block expressions, and mixed code expressions. Resources for Article : Further resources on this subject: Deploying HTML5 Applications with GNOME [Article] Making the World Wide Web an Easier Place to Talk About [Article] The Best Way to Create Round Cornered Boxes with CSS [Article]
Read more
  • 0
  • 0
  • 1747
Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €14.99/month. Cancel anytime
article-image-using-jquery-and-jqueryui-widget-factory-plugins-requirejs
Packt
18 Jun 2013
5 min read
Save for later

Using jQuery and jQueryUI Widget Factory plugins with RequireJS

Packt
18 Jun 2013
5 min read
(For more resources related to this topic, see here.) How to do it... We must declare the jquery alias name within our Require.js configuration file. require.config({// 3rd party script alias namespaths: {// Core Libraries// --------------// jQuery"jquery": "libs/jquery",// Plugins// -------"somePlugin": "libs/plugins/somePlugin"}}); If a jQuery plugin does not register itself as AMD compatible, we must also create a Require.js shim configuration to make sure Require.js loads jQuery before the jQuery plugin. shim: {// Twitter Bootstrap plugins depend on jQuery"bootstrap": ["jquery"]} We will now be able to dynamically load a jQuery plugin with the require() method. // Dynamically loads a jQuery plugin using the require() methodrequire(["somePlugin"], function() {// The callback function is executed after the pluginis loaded}); We will also be able to list a jQuery plugin as a dependency to another module. // Sample file// -----------// The define method is passed a dependency array and a callbackfunctiondefine(["jquery", "somePlugin"], function ($) {// Wraps all logic inside of a jQuery.ready event$(function() {});}); When using a jQueryUI Widget Factory plugin, we create Require.js path names for both the jQueryUI Widget Factory and the jQueryUI Widget Factory plugin: "jqueryui": "libs/jqueryui","selectBoxIt": "libs/plugins/selectBoxIt" Next, create a shim configuration property: // The jQueryUI Widget Factory depends on jQuery"jqueryui": ["jquery"],// The selectBoxIt plugin depends on both jQuery and the jQueryUIWidget Factory"selectBoxIt": ["jqueryui"] We will now be able to dynamically load the jQueryUI Widget Factory plugin with the require() method: // Dynamically loads the jQueryUI Widget Factory plugin, selectBoxIt,using the Require() methodrequire(["selectBoxIt"], function() {// The callback function is executed after selectBoxIt.js(and all of its dependencies) have been loaded}); We will also be able to list the jQueryUI Widget Factory plugin as a dependency to another module: // Sample file// -----------// The define method is passed a dependency array and a callbackfunctiondefine(["jquery", "selectBoxIt"], function ($) {// Wraps all logic inside of a jQuery.ready event$(function() {});}); How it works... Luckily for us, jQuery adheres to the AMD specification and registers itself as a named AMD module. If you are confused about how/why they are doing that, let's take a look at the jQuery source: // Expose jQuery as an AMD moduleif ( typeof define === "function" && define.amd && define.amd.jQuery ){define( "jquery", [], function () { return jQuery; } );} jQuery first checks to make sure there is a global define() function available on the page. Next, jQuery checks if the define function has an amd property, which all AMD loaders that adhere to the AMD API should have. Remember that in JavaScript, functions are first class objects, and can contain properties. Finally, jQuery checks to see if the amd property contains a jQuery property, which should only be there for AMD loaders that understand the issues with loading multiple versions of jQuery in a page that all might call the define() function. Essentially, jQuery is checking that an AMD script loader is on the page, and then registering itself as a named AMD module (jquery). Since jQuery exports itself as the named AMD module, jquery, you must use this exact name when setting the path configuration to your own version of jQuery, or Require.js will throw an error. If a jQuery plugin registers itself as an anonymous AMD module and jQuery is also listed with the proper lowercased jquery alias name within your Require.js configuration file, using the plugin with the require() and define() methods will work as you expect. Unfortunately, most jQuery plugins are not AMD compatible, and do not wrap themselves in an optional define() method and list jquery as a dependency. To get around this issue, we can use the Require.js shim object configuration like we have seen before to tell Require. js that a file depends on jQuery. The shim configuration is a great solution for jQuery plugins that do not register themselves as AMD modules. Unfortunately, unlike jQuery, the jQueryUI does not currently register itself as a named AMD module, which means that plugin authors that use the jQueryUI Widget Factory cannot provide AMD compatibility. Since the jQueryUI Widget Factory is not AMD compatible, we must use a workaround involving the paths and shim configuration objects to properly define the plugin as an AMD module. There's more... You will most likely always register your own files as anonymous AMD modules, but jQuery is a special case. Registering itself as a named AMD module allows other third-party libraries that depend on jQuery, such as jQuery plugins, to become AMD compatible by calling the define() method themselves and using the community agreed upon module name, jquery, to list jQuery as a dependency. Summary This article demonstrates how to use jQuery and jQueryUI Widget Factory plugins with Require.js. Resources for Article : Further resources on this subject: So, what is KineticJS? [Article] HTML5 Presentations - creating our initial presentation [Article] Tips & Tricks for Ext JS 3.x [Article]
Read more
  • 0
  • 0
  • 2334

article-image-so-what-play
Packt
14 Jun 2013
11 min read
Save for later

So, what is Play?

Packt
14 Jun 2013
11 min read
(For more resources related to this topic, see here.) Quick start – Creating your first Play application Now that we have a working Play installation in place, we will see how easy it is to create and run a new application with just a few keystrokes. Besides walking through the structure of our Play application, we will also look at what we can do with the command-line interface of Play and how fast modifications of our application are made visible. Finally, we will take a look at the setup of integrated development environments ( IDEs ). Step 1 – Creating a new Play application So, let's create our first Play application. In fact, we create two applications, because Play comes with the APIs for Java and Scala, the sample accompanying us in this book is implemented twice, each in one separate language. Please note that it is generally possible to use both languages in one project. Following the DRY principle, we will show code only once if it is the same for the Java and the Scala application. In such cases we will use the play-starter-scala project. First, we create the Java application. Open a command line and change to a directory where you want to place the project contents. Run the play script with the new command followed by the application name (which is used as the directory name for our project): $ play new play-starter-java We are asked to provide two additional information: The application name, for display purposes. Just press the Enter key here to use the same name we passed to the play script. You can change the name later by editing the appName variable in play-starter-java/project/Build.scala. The template we want to use for the application. Here we choose 2 for Java. Repeat these steps for our Scala application, but now choose 1 for the Scala template. Please note the difference in the application name: $ play new play-starter-scala The following screenshot shows the output of the play new command: On our way through the next sections, we will build an ongoing example step-by-step. We will see Java and Scala code side-by-side, so create both projects if you want to find out more about the difference between Java and Scala based Play applications. Structure of a Play application Physically, a Play application consists of a series of folders containing source code, configuration files, and web page resources. The play new command creates the standardized directory structure for these files: /path/to/play-starter-scala└app source code| └controllers http request processors| └views templates for html files└conf configuration files└project sbt project definition└public folder containing static assets| └images images| └javascripts javascript files| └stylesheets css style sheets└test source code of test cases During development, Play generates several other directories, which can be ignored, especially when using a version control system: /path/to/play-starter-scala└dist releases in .zip format└logs log files└project THIS FOLDER IS NEEDED| └project but this...| └target ...and this can be ignored└target generated sources and binaries There are more folders that can be found in a Play application depending on the IDE we use. In particular, a Play project has optional folders on more involved topics we do not discuss in this book. Please refer to the Play documentation for more details. The app/ folder The app/ folder contains the source code of our application. According to the MVC architectural pattern, we have three separate components in the form of the following directories: app/models/: This directory is not generated by default, but it is very likely present in a Play application. It contains the business logic of the application, for example, querying or calculating data. app/views/: In this directory we find the view templates. Play's view templates are basically HTML files with dynamic parts. app/controllers/: This controllers contain the application specific logic, for example, processing HTTP requests and error handling. The default directory (or package) names, models, views, and controllers, can be changed if needed. The conf/ directory The conf/ directory is the place where the application's configuration files are placed. There are two main configuration files: application.conf: This file contains standard configuration parameters routes – This file defines the HTTP interface of the application The application.conf file is the best place to add more configuration options if needed for our application. Configuration files for third-party libraries should also be put in the conf/ directory or an appropriate sub-directory of conf/. The project/ folder Play builds applications with the Simple Build Tool ( SBT ). The project/ folder contains the SBT build definitions: Build.scala: This is the application's build script executed by SBT build.properties: This definition contains properties such as the SBT version plugins.sbt: This definition contains the SBT plugins used by the project The public/ folder Static web resources are placed in the public/ folder. Play offers standard sub-directories for images, CSS stylesheets, and JavaScript files. Use these directories to keep your Play applications consistent. Create additional sub-directories of public/ for third-party libraries for a clear resource management and to avoid file name clashes. The test/ folder Finally, the test/ folder contains unit tests or functional tests. This code is not distributed with a release of our application. Step 2 – Using the Play console Play provides a command-line interface (CLI), the so-called Play console. It is based on the SBT and provides several commands to manage our application's development cycle. Starting our application To enter the Play console, open a shell, change to the root directory of one of our Play projects, and run the play script. $ cd /path/to/play-starter-scala$ play On the Play console, type run to run our application in development (DEV) mode. [play-starter-scala] $ run Use ~run instead of run to enable automatic compilation of file changes. This gives us an additional performance boost when accessing our application during development and it is recommended by the author. All console commands can be called directly on the command line by running play <command>. Multiple arguments have to be denoted in quotation marks, for example, play "~run 9001" A web server is started by Play, which will listen for HTTP requests on localhost:9000 by default. Now open a web browser and go to this location. The page displayed by the web browser is the default implementation of a new Play application. To return to our shell, type the keys Ctrl + D to stop the web server and get back to the Play console. Play console commands Besides run , we typically use the following console commands during development: clean: This command deletes cached files, generated sources, and compiled classes compile: This command compiles the current application test: This command executes unit tests and functional tests We get a list of available commands by typing help play in the Play development console. A release of an application is started with the start command in production (PROD) mode. In contrast to the DEV mode no internal state is displayed in the case of an error. There are also commands of the play script, available only on the command line: clean-all: This command deletes all generated directories, including the logs. debug: This command runs the Play console in debug mode, listening on the JPDA port 9999. Setting the environment variable JDPA_PORT changes the port. stop: This command stops an application that is running in production mode. Closing the console We exit the Play console and get back to the command line with the exit command or by simply typing the key Ctrl + D . Step 3 – Modifying our application We now come to the part that we love the most as impatient developers: the rapid development turnaround cycles. In the following sections, we will make some changes to the given code of our new application visible. Fast turnaround – change your code and hit reload! First we have to ensure that our applications are running. In the root of each of our Java and Scala projects, we start the Play console. We start our Play applications in parallel on two different ports to compare them side-by-side with the commands ~run and ~run 9001. We go to the browser and load both locations, localhost:9000 and I Then we open the default controller app/controllers/Application.java and app/controllers/Application.scala respectively, which we created at application creation, in a text editor of our choice, and change the message to be displayed in the Java code: public class Application extends Controller {public static Result index() {return ok(index.render("Look ma! No restart!"));}} and then in the Scala code: object Application extends Controller {def index = Action {Ok(views.html.index("Look ma! No restart!"))}} Finally, we reload our web pages and immediately see the changes: That's it. We don't have to restart our server or re-deploy our application. The code changes take effect by simply reloading the page. Step 4 – Setting up your preferred IDE Play takes care of automatically compiling modifications we make to our source code. That is why we don't need a full-blown IDE to develop Play applications. We can use a simple text editor instead. However, using an IDE has many advantages, such as code completion, refactoring assistance, and debugging capabilities. Also it is very easy to navigate through the code. Therefore, Play has built-in project generation support for two of the most popular IDEs: IntelliJ IDEA and Eclipse . IntelliJ IDEA The free edition, IntelliJ IDEA Community , can be used to develop Play projects. However, the commercial release, IntelliJ IDEA Ultimate , includes Play 2.0 support for Java and Scala. Currently, it offers the most sophisticated features compared to other IDEs.More information can be found here: http://www.jetbrains.com/idea and also here: http://confluence.jetbrains.com/display/IntelliJIDEA/Play+Framework+2.0 We generate the required IntelliJ IDEA project files by typing the idea command on the Play console or by running it on the command line: $ play idea We can also download the available source JAR files by running idea with-source=true on the console or on the command line: $ play "idea with-source=true" After that, the project can be imported into IntelliJ IDEA. Make sure you have the IDE plugins Scala, SBT , and Play 2 (if available) installed. The project files have to be regenerated by running play idea every time the classpath changes, for example, when adding or changing project dependencies. IntelliJ IDEA will recognize the changes and reloads the project automatically. The generated files should not be checked into a version control system, as they are specific to the current environment. Eclipse Eclipse is also supported by Play. The Eclipse Classic edition is fine, which can be downloaded here: http://www.eclipse.org/downloads. It is recommended to install the Scala IDE plugin, which comes up with great features for Scala developers and can be downloaded here: http://scala-ide.org. You need to download Version 2.1.0 (milestone) or higher to get Scala 2.10 support for Play 2.1. A Play 2 plugin exists also for Eclipse, but it is in a very early stage. It will be available in a future release of the Scala IDE. More information can be found here: https://github.com/scala-ide/scala-ide-play2/wiki The best way to edit Play templates with Eclipse currently is by associating HTML files with the Scala Script Editor. You get this editor by installing the Scala Worksheet plugin, which is bundled with the Scala IDE. We generate the required Eclipse project files by typing the eclipse command on the Play console or by running it on the command line: $ play eclipse Analogous to the previous code, we can also download available source JAR files by running eclipse with-source=true on the console or on the command line: $ play "eclipse with-source=true" Also, don't check in generated project files for a version control system or regenerate project files if dependencies change. Eclipse (Juno) is recognizing the changed project files automatically. Other IDEs Other IDEs are not supported by Play out of the box. There are a couple of plugins, which can be configured manually. For more information on this topic, please consult the Play documentation. Summary We saw how easy it is to create and run a new application with just a few keystrokes. Besides walking through the structure of our Play application, we also looked at what we can do with the command-line interface of Play and how fast modifications of our application are made visible. Finally, we looked at the setup of integrated development environments ( IDEs ). Resources for Article : Further resources on this subject: Play! Framework 2 – Dealing with Content [Article] Play Framework: Data Validation Using Controllers [Article] Play Framework: Binding and Validating Objects and Rendering JSON Output [Article]
Read more
  • 0
  • 0
  • 1709

article-image-so-what-kineticjs
Packt
14 Jun 2013
3 min read
Save for later

So, what is KineticJS?

Packt
14 Jun 2013
3 min read
(For more resources related to this topic, see here.) With KineticJS you can draw shapes on the stage and manipulate them using the following elements: Move Rotate Animate Even if your application has thousands of figures, the animation will run smoothly and with a high enough FPS. The items are organized into layers, of which you can have as many as you want. Shapes can also be organized into groups. KineticJS allows unlimited nesting of shapes and groups. Scenes, layers, groups, and figures are virtual nodes, similar to DOM nodes in HTML. Any node can be styled or transformed. There are several predefined shapes, such as rectangles, circles, images, text, lines, polygons, stars, and so on. You can also create custom drawing functions in order to create custom shapes. For each object you can assign different event handlers (touch or mouse). You can also apply filter or animation to the shapes. Of course, you can implement all the necessary HTML5 Canvas functionality without KineticJS, but you have to spend a lot more time, and not necessarily get the same level of performance. The creators of KineticJS put all their love and faith into a brighter future of HTML5 interactivity. The main advantage of the library is high performance, which is achieved by creating two canvas renderers – a scene renderer and a hit graph renderer. One renderer is what you see, and the second is a special hidden canvas that's used for high-performance event detection. A huge advantage of KineticJS is that it is an extension to HTML5 Canvas, and thus is perfectly suited for developing applications for mobile platforms. High performance can hide all the flaws of the canvas in iOS, Android, and other platforms. It is a known fact that the iOS platform does not support Adobe Flash. In this case, KineticJS is a good Flash alternative for iOS devices. You can wrap up your KineticJS application with Cordova/PhoneGap and use it as an offline application, or publish to the App store. In short, the following are the main advantages of KineticJS: Speed Scalability Extensibility Flexibility Familiarity with API (for developers with the knowledge of HTML, CSS, JS, and jQuery) If you are an active innovator and indomitable web developer, this library is for you. Summary In this article, we walked through the basics and main advantages KineticJS. Resources for Article : Further resources on this subject: HTML5 Presentations - creating our initial presentation [Article] Removing Unnecessary jQuery Loads [Article] Using JavaScript Effects with Joomla! [Article]
Read more
  • 0
  • 0
  • 2864

article-image-getting-started-leaflet
Packt
14 Jun 2013
9 min read
Save for later

Getting started with Leaflet

Packt
14 Jun 2013
9 min read
(For more resources related to this topic, see here.) Getting ready First, we need to get an Internet browser, if we don't have one already installed. Leaflet is tested with modern desktop browsers: Chrome, Firefox, Safari 5+, Opera 11.11+, and Internet Explorer 7-10. Internet Explorer 6 support is stated as not perfect but accessible. We can pick one of them, or all of them if we want to be thorough. Then, we need an editor. Editors come in many shapes and flavors: free or not free, with or without syntax highlighting, or remote file editing. A quick search on the Internet will provide thousands of capable editors. Notepad++ (http://notepad-plus-plus.org/) for Windows, Komodo Edit (http://www.activestate.com/komodo-edit) for Mac OS, or Vim (http://www.vim.org/) for Linux are among them. We can download Leaflet's latest stable release (v0.5.1 at the time of writing) and extract the content of the ZIP file somewhere appropriate. The ZIP file contains the sources as well as a prebuilt version of the library that can be found in the dist directory. Optionally, we can build from the sources included in the ZIP file; see this article's Building Leaflet from source section. Finally, let's create a new project directory on our hard drive and copy the dist folder from the extracted Leaflet package to it, ensuring we rename it to leaflet. How to do it... Note that the following code will constitute our code base throughout the rest of the article. Create a blank HTML file called index.html in the root of our project directory. Add the code given here and use the browser installed previously to execute it: <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="leaflet/ leaflet.css" /> <!--[if lte IE 8]> <link rel="stylesheet" type="text/css" href=" leaflet/ leaflet.ie.css" /> <![endif]--> <script src = "leaflet/leaflet.js"></script> <style> html, body, #map { height: 100%; } body { padding: 0; margin: 0; } </style> <title>Getting Started with Leaflet</title> </head> <body> <div id="map"></div> <script type="text/javascript"> var map = L.map('map', { center: [52.48626, -1.89042], zoom: 14 }); L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/ {x}/{y}.png', { attribution: '© OpenStreetMap contributors' }).addTo(map); </script> </body> </html> The following screenshot is of the first map we have created: How it works... The index.html file we created is a standardized file that all Internet browsers can read and display the contents. Our file is based on the HTML doctype standard produced by the World Wide Web Consortium (W3C), which is only one of many that can be used as seen at http://www.w3.org/QA/2002/04/valid-dtd-list.html. Our index file specifies the doctype on the first line of code as required by the W3C, using the <!DOCTYPE HTML> markup. We added a link to Leaflet's main CSS file in the head section of our code: <link rel="stylesheet" type="text/css" href="leaflet/leaflet.css" /> We also added a conditional statement to link an Internet Explorer 8 or lower only stylesheet when these browsers interpret the HTML code: <!--[if lte IE 8]> <link rel="stylesheet" type="text/css" href="leaflet/leaflet.ie.css" /> <![endif]--> This stylesheet mainly addresses Internet Explorer specific issues with borders and margins. Leaflet's JavaScript file is then referred to using a script tag: <script src = "leaflet/leaflet.js"></script> We are using the compressed JavaScript file that is appropriate for production but very inefficient for debugging. In the compressed version, every white space character has been removed, as shown in the following bullet list, which is a straight copy-paste from the source of both files for the function onMouseClick: compressed: _onMouseClick:function(t){!this._loaded||this.dragging&& this.dragging.moved()||(this.fire("preclick"),this._ fireMouseEvent(t))}, uncompressed: _onMouseClick: function (e) { if (!this._loaded || (this.dragging && this.dragging.moved())) { return; } this.fire('preclick'); this._fireMouseEvent(e); }, To make things easier, we can replace leaflet.js with leaflet-src.js—an uncompressed version of the library. We also added styles to our document to make the map fit nicely in our browser window: html, body, #map { height: 100%; } body { padding: 0; margin: 0; } The <div> tag with the id attribute map in the document's body is the container of our map. It must be given a height otherwise the map won't be displayed: <div id="map" style="height: 100%;" ></div> Finally, we added a script section enclosing the map's initialization code, instantiating a Map object using the L.map(…) constructor and a TileLayer object using the L.tileLayer(…) constructor. The script section must be placed after the map container declaration otherwise Leaflet will be referencing an element that does not yet exist when the page loads. When instantiating a Map object, we pass the id of the container of our map and an array of Map options: var map = L.map('map', { center: [52.48626, -1.89042], zoom: 14 }); There are a number of Map options affecting the state, the interactions, the navigation, and the controls of the map. See the documentation to explore those in detail at http://leafletjs.com/reference.html#map-options. Next, we instantiated a TileLayer object using the L.tileLayer(…) constructor and added to the map using the TileLayer.addTo(…) method: L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }).addTo(map); Here, the first parameter is the URL template of our tile provider—that is OpenStreetMap— and the second a noncompulsory array of TileLayer options including the recommended attribution text for our map tile's source. The TileLayer options are also numerous. Refer to the documentation for the exhaustive list at http://leafletjs.com/reference.html#tilelayer-options. There's more... Let's have a look at some of the Map options, as well as how to build Leaflet from source or use different tile providers. More on Map options We have encountered a few Map options in the code for this recipe, namely center and zoom. We could have instantiated our OpenStreetMap TileLayer object before our Map object and passed it as a Map option using the layers option. We also could have specified a minimum and maximum zoom or bounds to our map, using minZoom and maxZoom (integers) and maxBounds, respectively. The latter must be an instance of LatLngBounds: var bounds = L.latLngBounds([ L.latLng([52.312, -2.186]), L.latLng([52.663, -1.594]) ]); We also came across the TileLayer URL template that will be used to fetch the tile images, replacing { s} by a subdomain and { x}, {y}, and {z} by the tiles coordinate and zoom. The subdomains can be configured by setting the subdomains property of a TileLayer object instance. Finally, the attribution property was set to display the owner of the copyright of the data and/or a description. Building Leaflet from source A Leaflet release comes with the source code that we can build using Node.js. This will be a necessity if we want to fix annoying bugs or add awesome new features. The source code itself can be found in the src directory of the extracted release ZIP file. Feel free to explore and look at how things get done within a Leaflet. First things first, go to http://nodejs.org and get the install file for your platform. It will install Node.js along with npm, a command line utility that will download and install Node Packaged Modules and resolve their dependencies for us. Following is the list of modules we are going to install: Jake: A JavaScript build program similar to make JSHint: It will detect potential problems and errors in JavaScript code UglifyJS: A mangler and compressor library for JavaScript Hopefully, we won't need to delve into the specifics of these tools to build Leaflet from source. So let's open a command line interpreter— cmd.exe on Windows, or a terminal on Mac OSX or Linux—and navigate to the Leaflet's src directory using the cd command, then use npm to install Jake, JSHint and UglifyJS: cd leaflet/src npm install –g jake npm install jshint npm install uglify-js We can now run Jake in Leaflet's directory: jake What about tile providers? We could have chosen a different tile provider as OpenStreetMap is free of charge but has its limitations in regard of a production environment. A number of web services provide tiles but might come at a price depending on your usage: CloudMade, MapQuest. These three providers serve tiles use the OpenStreetMap tile scheme described at http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames. Remember the way we added the OpenStreetMap layer to the map? L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }).addTo(map); Remember the way we added the OpenStreetMap layer to the map? Cloudmade: L.tileLayer(' http://{s}.tile.cloudmade.com/API-key/997/256/{z}/ {x}/{y}.png', { attribution: ' Map data © <a href="http://openstreetmap. org">OpenStreetMap</a> contributors, <a href="http:// creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>' }).addTo(map); MapQuest: L.tileLayer('http://{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}. png', { attribution: ' Tiles Courtesy of <a href="http://www.mapquest. com/" target="_blank">MapQuest</a> <img src = "http://developer.mapquest.com/content/osm/mq_logo.png">', subdomains: ['otile1', 'otile2', 'otile3', 'otile4'] }).addTo(map); You will learn more about the Layer URL template and subdomains option in the documentation at http://leafletjs.com/reference.html#tilelayer. Leaflet also supports Web Map Service (WMS) tile layers—read more about it at http://leafletjs.com/reference.html#tilelayer-wms—and GeoJSON layers in the documentation at http://leafletjs.com/reference.html#geojson. Summary In this article we have learned how to create map using Leaflet and created our first map. We learned about different map options and also how to build a leaflet from source. Resources for Article : Further resources on this subject: Using JavaScript Effects with Joomla! [Article] Getting Started with OpenStreetMap [Article] Quick start [Article]
Read more
  • 0
  • 0
  • 7538
article-image-creating-your-own-theme
Packt
13 Jun 2013
5 min read
Save for later

Creating Your Own Theme

Packt
13 Jun 2013
5 min read
(For more resources related to this topic, see here.) Starting with a new layout Before we start creating a concrete5 theme we need a layout. In this article, we're going to use a simple layout without any pictures to keep the code as short as possible—it's about concrete5, not about HTML and CSS. If you don't have the time for an exercise, you can use your own layout. With good knowledge about the basic technologies of concrete5, you should be able to amend the instructions in this article to match your own layout. If you don't feel very comfortable working with PHP you should probably use the printed HTML code in this article. Here's a screenshot of what our site is going to look like once we've finished our theme: While this layout isn't very pretty, it has an easy structure; navigation on top and a big content area where we can insert any kind of block we want. In case you're using your own layout, try to use one with a simple structure; navigation on top or on the left with one big place for the content, and try to avoid Flash. The HTML code Let's have a look at the HTML code: <!DOCTYPE html><html lang="en"><head><title>concrete5 Theme</title><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><style type="text/css" media="screen">@import "main.css";</style></head><body><div id="wrapper"><div id="page"><div id="header_line_top"></div><div id="header"><ul class="nav-dropdown"><li><a href="#">Home</a></li><li><a href="#">Test</a></li><li><a href="#">About</a></li></ul></div><div id="header_line_bottom"></div><div id="content"><p>Paragraph 1</p><p>Paragraph 2</p><p>Paragraph 3</p></div><div id="footer_line_top"></div><div id="footer"></div><div id="footer_line_bottom"></div></div></div></body></html> There are three highlighted lines in the preceding code: The CSS import: This is to keep the layout instructions separated from the HTML elements; we've got all the CSS rules in a different file named main.css. This is also how almost all concrete5 themes are built. The header block contains the navigation. As we're going to apply some styles to it, make sure it has its own ID. Using an ID also improves the performance when using CSS and JavaScript to access an element, as an ID is unique. The same applies to the content block. Make sure it has a unique ID. Most web technologies we use nowadays are standardized in one way or another. Currently, the most important organization is W3C. They also offer tools to validate your code. Checking your code is never a bad idea. Navigate to http://validator.w3.org/ and enter the address of the website you want to check or in this case, as your website isn't accessible by the public, click on Validate by Direct Input and paste the HTML code to see if there are any mistakes. While it should be fairly easy to produce valid HTML code, things are a bit tricky with CSS. Due to some old browser bugs, you're often forced to use invalid CSS rules. There's often a way to rebuild the layout to avoid some invalid rules but often this isn't the case—you won't be doomed if something isn't 100 percent valid but you're on the safer side if it is. CSS rules As mentioned earlier, all CSS rules are placed in a file named main.css. Let's have a look at all CSS rules you have to put in our CSS file: /* global HTML tag rules */html, body, div, pre, form, fieldset, input, h1, h2, h3, h4, h5, h6,p, textarea, ul, ol, li, dl, dt, dd, blockquote, th, td {margin: 0;padding: 0;}p {margin: 5px 0px 15px 0px;}html {height: 100%;}body {background-color: #989898;height: 100%;}/* layout rules */#wrapper {margin: 0 auto;width: 980px;text-align: left;padding-top: 35px;}#page {background: #FFFFFF;float: left;width: 960px;padding: 5px;-moz-box-shadow: 0 0 15px black;-webkit-box-shadow: 0 0 15px black;box-shadow: 0 0 15pxblack;border-radius: 10px;}/* header */#header {background: #262626;border-radius: 10px 10px 0px 0px;height: 75px;}#header_line_top {background: #262626;height: 0px;}#header_line_bottom {background: #e64116;height: 3px;}/* content */#content {min-height: 300px;padding: 30px;color: #1E1E1E;font-family: verdana, helvetica, arial;font-size: 13px;line-height: 22px;}/* footer */#footer {background: #262626;height: 75px;border-radius: 0px 0px 10px 10px;}#footer_line_top {background: #e64116;height: 3px;}#footer_line_bottom {background: #262626;height: 0px;}/* header navigation */#header ul{margin: 0px;padding: 20px;}#header ul li {float: left;list-style-type: none;}#header ul li a {margin-right: 20px;display: block;padding: 6px 15px 6px 15px;color: #ccc;text-decoration: none;font-family: verdana, helvetica, arial;}#header ul li a:hover {color: white;}
Read more
  • 0
  • 0
  • 3645

article-image-magento-fundamentals-developers
Packt
11 Jun 2013
13 min read
Save for later

Magento Fundamentals for Developers

Packt
11 Jun 2013
13 min read
(For more resources related to this topic, see here.) Zend Framework – the base of Magento As you probably know, Magento is the most powerful e-commerce platform in the market; what you might not know about Magento is that it is also an object-oriented (OO) PHP framework developed on top of Zend Framework. Zend's official site describes the framework as: Zend Framework 2 is an open source framework for developing web applications and services using PHP 5.3+. Zend Framework 2 uses 100% object-oriented code and utilises most of the new features of PHP 5.3, namely namespaces, late static binding, lambda functions and closures. The component structure of Zend Framework 2 is unique; each component is designed with few dependencies on other components. ZF2 follows the SOLID object oriented design principle. This loosely coupled architecture allows developers to use whichever components they want. We call this a "use-at-will" design. But what is Zend Framework exactly? Zend Framework is an OO framework developed on PHP that implements the Model-View-Controller (MVC) paradigm. When Varien, now Magento Inc., started developing Magento it decided to do it on top of Zend because of the following components: Zend_Cache Zend_Acl Zend_DB Zend_Pdf Zend_Currency Zend_Date Zend_Soap Zend_Http In total, Magento uses around 15 different Zend components. The Varien library directly extends several of the Zend components mentioned previously, for example Varien_Cache_Core extends from Zend_Cache_Core. Using Zend Framework, Magento was built with the following principles in mind: Maintainability: It occurs using code pools to keep the core code separate from local customizations and third-party modules Upgradability: Magento modularity allows extensions and third-party modules to be updated independently from the rest of the system Flexibility: Allows seamless customization and simplifies the development of new features Although having used Zend Framework or even understanding it are not the requirements for developing with Magento, having at least a basic understanding of the Zend components, usage, and interaction can be invaluable information when we start digging deeper into the core of Magento. You can learn more about Zend Framework at http://framework.zend.com/ Magento folder structure Magento folder structure is slightly different from other MVC applications; let's take a look at the directory tree, and each directory and its functions: app: This folder is the core of Magento and is subdivided into three importing directories: code: This contains all our application code divided into three code pools such as core, community, and local design: This contains all the templates and layouts for our application locale: This contains all the translation and e-mail template files used for the store js: This contains all the JavaScript libraries that are used in Magento media: This contains all the images and media files for our products and CMS pages as well as the product image cache lib: This contains all the third-party libraries used in Magento such as Zend and PEAR, as well as the custom libraries developed by Magento, which reside under the Varien and Mage directories skin: This contains all CSS code, images, and JavaScript files used by the corresponding theme var: This contains our temporary data such as cache files, index lock files, sessions, import/export files, and in the case of the Enterprise edition the full page cache folders Magento is a modular system. This means that the application, including the core, is divided into smaller modules. For this reason, the folder structure plays a key role in the organization of each module core; a typical Magento module folder structure would look something like the following figure: Let's review each folder in more detail: Block: This folder contains blocks in Magento that form an additional layer of logic between the controllers and views controllers: controllers folders are formed by actions that process web server requests Controller: The classes in this folder are meant to be abstract classes and extended by the controller class under the the controllers folder etc: Here we can find the module-specific configuration in the form of XML files such as config.xml and system.xml Helper: This folder contains auxiliary classes that encapsulate a common-module functionality and make it available to a class of the same module and to other modules' classes as well Model: This folder contains models that support the controllers in the module for interacting with data sql: This folder contains the installation and upgrade files for each specific module As we will see later on in this article, Magento makes heavy use of factory names and factory methods. This is why the folder structure is so important. Modular architecture Rather than being a large application, Magento is built by smaller modules, each adding specific functionality to Magento. One of the advantages of this approach is the ability to enable and disable specific module functionality with ease, as well as add new functionality by adding new modules. Autoloader Magento is a huge framework, composed of close to 30,000 files. Requiring every single file when the application starts would make it incredibly slow and heavy. For this reason, Magento makes use of an autoloader class to find the required files each time a factory method is called. So, what exactly is an autoloader? PHP5 includes a function called __autoload().When instantiating a class, the __autoload() function is automatically called; inside this function, custom logic is defined to parse the class name and the required file. Let's take a closer look at the Magento bootstrap code located at app/Mage.php: …Mage::register('original_include_path', get_include_path());if (defined('COMPILER_INCLUDE_PATH')) {$appPath = COMPILER_INCLUDE_PATH;set_include_path($appPath . PS .Mage::registry('original_include_path'));include_once "Mage_Core_functions.php";include_once "Varien_Autoload.php";} else {/*** Set include path*/$paths[] = BP . DS . 'app' . DS . 'code' . DS . 'local';$paths[] = BP . DS . 'app' . DS . 'code' . DS . 'community';$paths[] = BP . DS . 'app' . DS . 'code' . DS . 'core';$paths[] = BP . DS . 'lib';$appPath = implode(PS, $paths);set_include_path($appPath . PS .Mage::registry('original_include_path'));include_once "Mage/Core/functions.php";include_once "Varien/Autoload.php";}Varien_Autoload::register(); The bootstrap file takes care of defining the include paths and initializing the Varien autoloader, which will in turn define its own autoload function as the default function to call. Let's take a look under the hood and see what the Varien autoload function is doing: /*** Load class source code** @param string $class*/public function autoload($class){if ($this->_collectClasses) {$this->_arrLoadedClasses[self::$_scope][] = $class;}if ($this->_isIncludePathDefined) {$classFile = COMPILER_INCLUDE_PATH .DIRECTORY_SEPARATOR . $class;} else {$classFile = str_replace(' ', DIRECTORY_SEPARATOR,ucwords(str_replace('_', ' ', $class)));}$classFile.= '.php';//echo $classFile;die();return include $classFile;} The autoload class takes a single parameter called $class, which is an alias provided by the factory method. This alias is processed to generate a matching class name that is then included. As we mentioned before, Magento's directory structure is important due to the fact that Magento derives its class names from the directory structure. This convention is the core principle behind factory methods that we will be reviewing later on in this article. Code pools As we mentioned before, inside our app/code folder we have our application code divided into three different directories known as code pools. They are as follows: core: This is where the Magento core modules that provide the base functionality reside. The golden rule among Magento developers is that you should never, by any circumstance, modify any files under the core code pool. community: This is the location where third-party modules are placed. They are either provided by third parties or installed through Magento Connect. local: This is where all the modules and code developed specifically for this instance of Magento reside. The code pools identify where the module came from and on which order they should be loaded. If we take another look at the Mage.php bootstrap file, we can see the order on which code pools are loaded: $paths[] = BP . DS . 'app' . DS . 'code' . DS . 'local';$paths[] = BP . DS . 'app' . DS . 'code' . DS . 'community';$paths[] = BP . DS . 'app' . DS . 'code' . DS . 'core';$paths[] = BP . DS . 'lib'; This means that for each class request, Magento will look in local, then community, then core, and finally inside the lib folder. This also leads to an interesting behavior that can easily be used for overriding core and community classes, by just copying the directory structure and matching the class name. Needless to say that this is a terrible practice, but it is still useful to know about just in case you someday have to take care of a project that exploits this behavior. Routing and request flow Before going into more detail about the different components that form a part of Magento, it is important that we understand how these components interact together and how Magento processes requests coming from the web server. As with any other PHP application, we have a single file as an entry point for every request; in the case of Magento this file is index.php, which is in charge of loading the Mage.php bootstrap class and starting the request cycle. It then goes through the following steps: The web server receives the request and Magento is instantiated by calling the bootstrap file, Mage.php. The frontend controller is instantiated and initialized; during this controller initialization Magento searches for the web routes and instantiates them. Magento then iterates through each of the routers and calls the match. The match method is responsible for processing the URL and generating the corresponding controller and action. Magento then instantiates the matching controller and takes the corresponding action. Routers are especially important in this process. The Router objects are used by the frontend controller to match a requested URL (route) to a module controller and action. By default, Magento comes with the following routers: Mage_Core_Controller_Varien_Router_Admin Mage_Core_Controller_Varien_Router_Standard Mage_Core_Controller_Varien_Router_Default The action controller will then load and render the layout, which in turn will load the corresponding blocks, models, and templates. Let's analyze how Magento will handle a request to a category page; we will use http:// localhost/catalog/category/view/id/10 as an example. Magento URIs are comprised of three parts – /FrontName/ControllerName/ActionName. This means that for our example URL, the breakdown would be as follows: FrontName: catalog ControllerName: category ActionName: view If I take a look at the Magento router class, I can see the Mage_Core_Controller_ Varien_Router_Standard match function: public function match(Zend_Controller_Request_Http $request){…$path = trim($request->getPathInfo(), '/');if ($path) {$p = explode('/', $path);} else {$p = explode('/', $this->_getDefaultPath());}…} From the preceding code, we can see that the first thing the router tries to do is to parse the URI into an array. Based on our example URL, the corresponding array would be something like the following code snippet: $p = Array([0] => catalog[1] => category[2] => view) The next part of the function will first try to check if the request has the module name specified; if not, then it tries to determine the module name based on the first element of our array. And if a module name can't be provided, then the function will return false. Let's take a look at that part of the code: // get module nameif ($request->getModuleName()) {$module = $request->getModuleName();} else {if (!empty($p[0])) {$module = $p[0];} else {$module = $this->getFront()->getDefault('module');$request->setAlias(Mage_Core_Model_Url_Rewrite::REWRITE_REQUEST_PATH_ALIAS, '');}}if (!$module) {if (Mage::app()->getStore()->isAdmin()) {$module = 'admin';} else {return false;}} Next, the match function will iterate through each of the available modules and try to match the controller and action, using the following code: …foreach ($modules as $realModule) {$request->setRouteName($this->getRouteByFrontName($module));// get controller nameif ($request->getControllerName()) {$controller = $request->getControllerName();} else {if (!empty($p[1])) {$controller = $p[1];} else {$controller =$front->getDefault('controller');$request->setAlias(Mage_Core_Model_Url_Rewrite::REWRITE_REQUEST_PATH_ALIAS,ltrim($request->getOriginalPathInfo(), '/'));}}// get action nameif (empty($action)) {if ($request->getActionName()) {$action = $request->getActionName();} else {$action = !empty($p[2]) ? $p[2] :$front->getDefault('action');}}//checking if this place should be secure$this->_checkShouldBeSecure($request,'/'.$module.'/'.$controller.'/'.$action);$controllerClassName = $this->_validateControllerClassName($realModule, $controller);if (!$controllerClassName) {continue;}// instantiate controller class$controllerInstance = Mage::getControllerInstance($controllerClassName,$request, $front->getResponse());if (!$controllerInstance->hasAction($action)) {continue;}$found = true;break;}... Now that looks like an awful lot of code, so let's break it down even further. The first part of the loop will check if the request has a controller name; if it is not set, it will check our parameter array's ($p) second value and try to determine the controller name, and then it will try to do the same for the action name. If we got this far in the loop, we should have a module name, a controller name, and an action name, which Magento will now use to try and get a matching controller class name by calling the following function: $controllerClassName = $this->_validateControllerClassName($realModule, $controller); This function will not only generate a matching class name but it will also validate its existence; in our example case this function should return Mage_Catalog_ CategoryController. Since we now have a valid class name, we can proceed to instantiate our controller object; if you were paying attention up to this point, you have probably noticed that we haven't done anything with our action yet, and that's precisely the next step in our loop. Our new instantiated controller comes with a very handy function called hasAction(); in essence, what this function does is to call a PHP function called is_callable(), which will check if our current controller has a public function matching the action name; in our case this will be viewAction(). The reason behind this elaborate matching process and the use of a foreach loop is that it is possible for several modules to use the same FrontName. Now, http://localhost/catalog/category/view/id/10 is not a very user-friendly URL; fortunately, Magento has its own URL rewrite system that allows us to use http: //localhost/books.html. Let's dig a little deeper into the URL rewrite system and see how Magento gets the controller and action names from our URL alias. Inside our Varien/Front.php controller dispatch function, Magento will call: Mage::getModel('core/url_rewrite')->rewrite(); Before actually looking into the inner workings of the rewrite function, let's take a look at the structure of the core/url_rewrite model: Array (["url_rewrite_id"] => "10"["store_id"] => "1"["category_id"] => "10"["product_id"] => NULL["id_path"] => "category/10"["request_path"] => "books.html"["target_path"] => "catalog/category/view/id/10"["is_system"] => "1"["options"] => NULL["description"] => NULL) As we can see, the rewrite module is comprised of several properties, but only two of them are of particular interest to use – request_path and target_path. Simply put, the job of the rewrite module is to modify the request object path information with the matching values of target_path.
Read more
  • 0
  • 0
  • 1755

article-image-building-multipage-forms-intermediate
Packt
11 Jun 2013
5 min read
Save for later

Building multipage forms (Intermediate)

Packt
11 Jun 2013
5 min read
(For more resources related to this topic, see here.) Getting ready We'll separate our existing user registration form already created to multipage forms. The sections will be for personal information, address details, and contact information. How to do it... All code related to the form is written in a file named _form under protected/views/user. We are dividing the input fields into three sections, so create three separate files in the same folder with the names _page1, _page2, and _page3. Separate the code's respective files. Some sample lines are as follows: <?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'user-form', 'enableAjaxValidation'=>false, 'stateful'=>true, )); ?> <div class="row"> <?php echo $form->labelEx($model,'first_name'); ?> <?php echo $form->textField($model,'first_name', array( 'size'=>50, 'maxlength'=>50 )); ?> <?php echo $form->error($model,'first_name'); ?> </div> ..... ..... <div class="row buttons"> <?php echo CHtml::submitButton('Next', array( 'name'=>'page2' )); ?> </div> <?php $this->endWidget(); ?> .... <div class="row buttons"> <?php echo CHtml::submitButton('back', array( 'name'=>'page1' )); ?> <?php echo CHtml::submitButton('Next', array( 'name'=>'page3' )); ?> </div> <div class="row buttons"> <?php echo CHtml::submitButton('Back', array( 'name'=>'page2' )); ?> <?php echo CHtml::submitButton('submit', array( 'name'=>'submit' )); ?> </div> Now, in the User controller, change the code for actionCreate as follows: public function actionCreate() { if(isset($_POST['page1'])) { $model = new User('page1'); $this->checkPageState($model, $_POST['User']); $view = '_page1'; } elseif(isset($_POST['page2'])) { $model = new User('page1'); $this->checkPageState($model, $_POST['User']); if($model->validate()) { $view = '_page2'; $model->scenario = 'page2'; } else { $view = '_page1'; } } .... $this->render($view, array('model'=>$model)); } And add a function, checkPageState(), as follows: private function checkPageState(&$model, $data) { $model->attributes = $this->getPageState('page', array()); $model->attributes = $data; $this->setPageState('page', $model->attributes); } Lastly, create scenarios in the model User to validate each page of the form separately. Add three arrays specifying all the required fields per page, as follows: return array( array('first_name, last_name, gender, dob', 'required', 'on'=>'page1' ), array('address_1, city, state, country', 'required', 'on'=>'page2' ), array('phone_number_1, email_1', 'required', 'on'=>'page3' ), How it works... We have separated all our input fields into three forms. Each page contains an entire standalone form that accepts the input from the user, validates it from the server, and stores the data till we finally submit this form. The parameter stateful passed to the CactiveForm widget specifies the form needed to maintain the state across the pages. To do this, Yii creates a hidden field in each form with the name YII_PAGE_STATE, as shown in the following screenshot: All the data submitted on the first page is stored in this hidden field and passed to the server with the second page. To read the data from this field we have used the method getPageState(), and to write we have used setPageState(). We have added a private method checkPageState() to the User controller, which reads the page state, if any, and assigns it to $model->attributes, then assigns data from the current form using $model->attributes = $_POST['User'], and finally overwrites the page state with freshly combined data. When we click on Next on _page1, we set the POST variable page2, which in turn executes the second block in the if-else ladder in actionCreate. In this article, we create an instance of the model User with scenario set to _page1 (as we need to validate the data received from _page1). With a call to checkPageState(), we check the current page state and add any new data from _page1 to the page state. Then we check if the data filled is valid using $model->validate() . If the model passes the validation we set, apply view to _page2 and set $model->scenario to _page2, to mark the required fields on _page2. If the validation fails, we set the view to _page1 with the validation errors set in the model. At the end of the action, we render the selected view with the current state of the model. If any validation errors are set, they are listed on the same page; else, the next page will be rendered. The same steps are repeated for _page2 as well. When the submit button is clicked on on _page3, we retrieve the previous data from the page state using getPageState(). Here we are not using checkPageState() as now we do not need to store any data to the page state. We simply assign the data from _page3 to the model, and if the model validates we save all the data to the database with $model->save(). After saving, we are redirected to actionView(), where data from all three forms is listed as shown in the following screenshot: Summary In this article, we saw the importance of dividing big single forms into mulitpage forms. The article provided an insight into the making of multipage forms. Resources for Article : Further resources on this subject: Play! Framework 2 – Dealing with Content [Article] Play Framework: Introduction to Writing Modules [Article] Generating Content in WordPress Top Plugins—A Sequel [Article]
Read more
  • 0
  • 0
  • 3254
article-image-article-nesting-extend-placeholders-and-mixins
Packt
05 Jun 2013
9 min read
Save for later

Nesting, Extend, Placeholders, and Mixins

Packt
05 Jun 2013
9 min read
(For more resources related to this topic, see here.) Styling a site with Sass and Compass Personally, while abstract examples are fine, I find it difficult to fully understand concepts until I put them into practice. With that in mind, at this point I'm going to amend the markup in our project's index.html file, so we have some markup to flex our growing Sass and Compass muscles on. We're going to build up a basic home page for this book. Hopefully, the basic layout and structure will be common enough to be of help. If you want to see how things turn out, you can point your browser at http://sassandcompass.com, as that's what we'll be building. The markup for the home page is fairly simple. It consists of a header with links, navigation made up of list items, images, and content and a footer area. Pasting the home page markup here will span a few pages (and be extremely dull to read. Don't get too hung up on the specifics of the markup. Let me be clear. The actual code, selectors used, and the finished webpage that we'll create are not important. The Sass and Compass techniques and tools we use to create them are. You can download the code from the book's page at http://packtpub.com and also from http://sassandcompass.com You can download the code from the book's page at http:// packtpub.com and also from http://sassandcompass.com At this point, here's how the page looks in the browser: Image Wow, what a looker! Thankfully, with Sass and Compass we're going to knock this into shape in no time at all. Notice that in the source code there are semantically named classes in the markup. Some people dislike this practice, but I have found that it makes it easier to create more modular and maintainable code. A full discussion on the reasoning behind using classes against styling elements themselves is a little beyond the scope of this book. However, a good book on this topic is SMACSS by Jonathan Snook (http:// smacss.com). It's not essential to adhere slavishly to the conventions he describes, but it's a great start in thinking about how to structure and write style sheets in general. First, let's open the _normalize.scss partial file and amend the default styles for links (changing the default text-underline to a dotted bottom border) and remove the padding and margin for the ul tags. Now I think about this, before we get knee-deep in code, a little more organization is called for. Separating the layout from visuals Before getting into nesting, @extend, placeholders, and mixins, it makes sense to create some partial files for organizing the styles. Rather than create a partial Sass file for each structural area (the header, footer, and navigation), and lump all the visual styles relevant inside, we can structure the code in a slightly more abstract manner. There is no right or wrong way to split up Sass files. However, it's worth looking at mature and respected projects such as Twitter Bootstrap (https://github.com/twitter/ bootstrap) and Foundation from Zurb (https://github.com/zurb/foundation) to see how they organize their code. We'll create a partial file called _base.scss that will contain some base styles: code Then a partial file called _layout.scss. That will only contain rules pertaining to visual layout and positioning of the main page areas (the previously mentioned header, footer, aside, section, and navigation). Here are the initial styles being added into the _layout.scss partial file: code There is nothing particular to Sass there, it's all standard CSS. Debug help in the browser Thanks to the popularity of Sass there are now experimental features in browsers to make debugging Sass even easier. When inspecting an element with developer tools, the source file and line number is provided, making it easier to find the offending selector. For Chrome, here's a step-by-step explanation: http://benfra.in/1z1 Alternatively, if using Firefox, check out the FireSass extension: https://addons.mozilla.org/en-us/firefox/addon/ firesass-for-firebug/ Let's create another partial file called _modules.scss. This will contain all the modular pieces of code. This means, should we need to move the .testimonial section (which should be a modular section) in the source code, it's not necessary to move it from one partial file to another (which would be the case if the partial files were named according to their existing layout). The _module.scss file will probably end up being the largest file in the Sass project, as it will contain all the aesthetics for the items on the page. However, the hope is that these modular pieces of code will be flexible enough to look good, regardless of the structural constraints defined in the _layout.scss partial file. If working on a very large project, it may be worth splitting the modules into sub-folders. Just create a sub-folder and import the file. For example, if there was a partial called _callouts.scss in a sub-folder called modules, it could be imported using the following code: code Here is the contents of the amended styles.scss file: code A quick look at the HTML in the browser shows the basic layout styles applied: Image With that done, let's look at how Sass's ability to nest styles can help us make modules of code. What nesting is and how it facilitates modules of code Nesting provides the ability to nest styles within one another. This provides a handy way to write mini blocks of modular code. Nesting syntax With a normal CSS style declaration, there is a selector, then an opening curly brace, and then any number of property and value pairs, followed by a closing curly brace. For example: code Where Sass differs is that before the closing curly brace, you can nest another rule within. What do I mean by that? Consider this example: code In the previous code, a color has been set for the link tag using a variable. Then the hover and focus state have been nested within the main anchor style with a different color set. Furthermore, styles for the visited and active state have been nested with an alternate color defined. To reference a variable, simply write the dollar sign ( $) and then the name of the variable, for example, $variable. When compiled, this produces the following CSS: code Notice that Sass is also smart enough to know that the hex value #7FFF00 is actually the color called chartreuse, and when it has generated the CSS it has converted it to the CSS color name. How can this be used practically? Let's look at the markup for the list of navigation links on the home page. Each currently looks like this: code I've omitted the additional list items and closing tags in the previous code for the sake of brevity. From a structure point of view, each list item contains an anchor link with a <b> tag and a <span> tag within. Here's the initial Sass nested styles that have been added into the _modules.scss partial to control that section: code Notice that the rules are being nested inside the class .chapter-summary. That's because it then limits the scope of the nested styles to only apply to elements within a list item with a class of .chapter-summary. However, remember that if the styles can be re-used elsewhere, it isn't necessarily the best practice to nest them, as they may become too specific. The nesting of the selectors in this manner partially mirrors the structure of the HTML, so it's easy to see that the styles nested within only apply to those that are similarly structured in the markup. We're starting with the outermost element that needs to be styled (the <li class=”chapter-summary”>) and then nesting the first element within that. In this instance, it's the anchor tag. Then further styles have been nested for the hover and visited states along with the <b> and <span> tags. I tend to add focus and active states at the end of a project, but that's a personal thing. If you're likely to forget them, by all means add them at the same time you add hover. Here's the generated CSS from that block: code The nested styles are generated with a degree of specificity that limits their scope; they will only apply to elements within a <li class=”chapter-summary”>. It's possible to nest all manner of styles within one another. Classes, IDs, pseudo classes; Sass doesn't much care. For example, let's suppose the <li> elements need to have a dotted border, except for the last one. Let's take advantage of the last-child CSS pseudo class in combination with nesting and add this section: code The parent selector Notice that any pseudo selector that needs to be nested in Sass is prefixed with the ampersand symbol (&), then a colon (:). The ampersand symbol has a special meaning when nesting. It always references the parent selector. It's perfect for defining pseudo classes as it effectively says 'the parent plus this pseudo element'. However, there are other ways it can work too, for example, nesting a few related selectors and expressing different relationships between them: code This actually results in the following CSS: code We have effectively reversed the selectors while nesting by using the & parent selector. Chaining selectors It's also possible to create chained selectors using the parent selector. Consider this: code That will compile to this: code That will only select an element that has both HTML classes, namely selector-one and selector-two. The parent selector is perfect for pseudo selectors and at odd times its necessary to chain selectors, but beyond that I couldn't find much practical use for it, until I saw this set of slides by Sass guru Brandon Mathis http://speakerdeck.com/u/imathis/p/sass-compass-the-future-of-stylesheets-now. In this, he illustrates how to use the parent selector for nesting a Modernizr relevant rule.
Read more
  • 0
  • 0
  • 1574

article-image-wijmo-widgets
Packt
31 May 2013
9 min read
Save for later

Wijmo Widgets

Packt
31 May 2013
9 min read
(For more resources related to this topic, see here.) Column bar chart (Simple) A column bar chart widget is slightly different from the regular bar chart widget we previously created. Remember we also had a look at some of the useful and common options used by most Wijmo developers. The last one we listed was the horizontal option of type Boolean. The default value of the horizontal option is true. This implies that the bar chart will be rendered in a horizontal layout by default. Getting ready For the creation of our first column bar chart, we shall proceed by setting the horizontal option to false, using the same code used for the previous bar chart we had created. Here's our new complete code: <html><head><!--jQuery References--><script src = "http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.1.min.js" type="text/javascript"></script><script src = "http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.17/jqueryui.min.js" type="text/javascript"></script><!--Wijmo Widgets JavaScript--><script src = "http://cdn.wijmo.com/jquery.wijmo-open.all.2.0.0.min.js"type="text/javascript"></script><script src = "http://cdn.wijmo.com/jquery.wijmo-complete.all.2.0.0.min.js" type="text/javascript"></script><!--Theme--><link href = "http://cdn.wijmo.com/themes/rocket/jquery-wijmo.css"rel="stylesheet" type="text/css" title="rocket-jqueryui" /><!--Wijmo Widgets CSS--><link href = "http://cdn.wijmo.com/jquery.wijmo-complete.all.2.0.0.min.css" rel="stylesheet" type="text/css" /></head><body><div id="wijbarchart" class="ui-widget ui-widget-content ui-cornerall"style="width: 400px;height: 300px"></div><script id="scriptInit" type="text/javascript">$(document).ready(function () {//activating the wijbarchart function on #wijbarchart$("#wijbarchart").wijbarchart({horizontal: false,//makes it verticalaxis: { //set up the x and y axesy: {text: "Total Automation Sales",},x: {text: "",labels: {style: {rotation: -45}}}},hint: { //hint text when hovering over chartcontent: function () {return this.data.label + 'n ' + this.y + '';}},header: {//chart titletext: "US Toyota Automobile Statistics (DummyData)"},//data for chart representing each columnseriesList: [{label: "US",legendEntry: true,data: { x: ['Toyota Camry', 'Toyota Corolla','Toyota Sienna'], y: [12.35, 21.50, 30.56] }}],seriesStyles: [{fill: "40-#BD0070-#718680", stroke: "#1261C0",opacity: 0.7}],seriesHoverStyles: [{ "stroke-width": "1.5", opacity:1}]});});</script></body></html> Notice from the preceding code, which we will hereon refer to as the main code, that we set the horizontal option to false. Now, when we run the main code, we should see a column bar chart widget as follows: That's how simple switching from a regular bar chart to a column bar chart is. The choice between either of the two bar charts is usually dependent on user preference. How to do it... We reference the Wijmo dependencies as follows: After the page loads, we set the horizontal property to false. The x and y properties are set, and y is rotated at -45 degrees, which rotates the labels for Toyota Camry, Toyota Corolla, and Toyota Sienna. We set the hint property, which is displayed on hovering over the chart. We set the header property, which is displayed atop the grid. For the seriesList property, we have a data subproperty that holds data for x and y. These values are mapped one-to-one in such a way that x['Toyota Camry'] gets y[0] or y[12.35]. For the seriesStyles property, we set the gradient color as "40-#BD0070- #718680" and set the opacity value as 0.7. Bubble chart (Intermediate) A bubble chart is a chart whose data points are replaced with bubbles of various shapes and scattered across the chart. It is like a scatter chart. The Wijmo widget representing a bubble chart is referred to as a wijbubblechart object. Getting ready The data points or bubbles each have three non-dependent values, x, y, and y1 as follows: The value x defines the Cartesian position along the x axis The value y defines the Cartesian position along the y axis The value y1 defines the bubble size at each point Having understood a bubble chart and the three values that define the positions of the bubble, we can now happily proceed with an implementation. Let us create a wijbubblechart object of the percentage of college graduates in six major cities around the world. This is dummy data and doesn't reflect the actual relationship between college graduates and the health of the corresponding economy. However, this dummy data is based on the assumption that a city with more graduates per thousand will have a smarter economy. Also, this depends on the overall population of that city. Enter the following code into your favorite code editor: <html><head><!--jQuery References--><script src = "http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.1.min.js" type="text/javascript"></script><script src = "http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.17/jqueryui.min.js" type="text/javascript"></script><!--Wijmo Widgets JavaScript--><script src = "http://cdn.wijmo.com/jquery.wijmo-open.all.2.0.0.min.js"type="text/javascript"></script><script src = "http://cdn.wijmo.com/jquery.wijmo-complete.all.2.0.0.min.js" type="text/javascript"></script><!--Theme--><link href = "http://cdn.wijmo.com/themes/rocket/jquery-wijmo.css"rel="stylesheet" type="text/css" title="rocket-jqueryui" /><!--Wijmo Widgets CSS--><link href = "http://cdn.wijmo.com/jquery.wijmo-complete.all.2.0.0.min.css" rel="stylesheet" type="text/css" /><script type = "text/javascript">$(document).ready(function () {$("#myWijbubblechart").wijbubblechart({showChartLabels: false,axis: {y: {text: "Smart Economy Rating"},x: {text: "College Graduates(Per Thousand)"}},hint: {content: function () {return this.data.label;}},header: {text: "College Graduates Vs. Health of the Economy- 2012"},seriesList: [{label: "Beijing",legendEntry: true,data: { y: [85], x: [150], y1: [1340] },markers: {type: "tri"}}, {label: "New Delhi",legendEntry: true,data: { y: [80], x: [167], y1: [1150] },markers: {type: "diamond"}}, {label: "Los Angeles",legendEntry: true,data: { y: [92], x: [400], y1: [309] },markers: {type: "circle"}}, {label: "Tokyo",legendEntry: true,data: { y: [94], x: [250], y1: [126] },markers: {type: "invertedTri"}}, {label: "London",legendEntry: true,data: { y: [82], x: [200], y1: [140] },markers: {type: "cross"}}, {label: "Lagos",legendEntry: true,data: { y: [48], x: [374], y1: [72] },markers: {type: "box"}}]});});</script></head><body><div id="myWijbubblechart" class="ui-widget ui-widget-content uicorner-all" style="width: 500px;height: 300px"></div></body></html> If the preceding code is copied correctly and run in a browser, we should have a Wijmo bubble chart similar to the following screenshot: How to do it... To see how the wijbubblechart object works, we can simply examine one of the objects in the seriesList property, like this one: {label: "Beijing",legendEntry: true,data: { y: [85], x: [150], y1: [1340] },markers: {type: "tri"}}, Remember that we already defined x, y, and y1 as the values of a point on the x axis, a point on the y axis, and the size of the bubble respectively. So in this case, for Beijing the value for y is set to 85, and the size of the bubble, y1, is 1340. The legendEntry property is set to true so we can see Beijing in the legend area by the right of the chart. We can see the various bubbles in different shapes and a legend that tells what city each bubble represents. The type property of the markers object is responsible for setting the shape of the bubble. markers: {type: "tri"} There's more... One more common aspect of the wijbubblechart object is the possibility of changing its appearance, for example, applying gradient colors, using some options, and so on. To achieve this we simply have to include a seriesStyles property as follows: <script type="text/javascript">$(document).ready(function () {//instantiating wijbubblechart on #myWijbubblechart$("#myWijbubblechart").wijbubblechart({showChartLabels: false,//setup the x and y axis labelsaxis: {y: {text: "Smart Economy Rating"},x: {text: "College Graduates(Per Thousand)"}},//Display hint text on chart hoverhint: {content: function () {return this.data.label;}},//title of chartheader: {text: "College Graduates Vs. Health of the Economy- 2012"},//chart color fill stylesseriesStyles: [{fill: "180-#8F8F8F-#C462AC", stroke: "#8F8F8F"}, {fill: "45-#C462AC-#2371B0", stroke: "#C462AC"}, {fill: "90-#4A067D-#0B7D19", stroke: "#4A067D"}, {fill: "270-#2371B0-#6AABA7", stroke: "#2371B0"}, {fill: "45-#0C85F0-#852E85", stroke: "#0C85F0"}, {fill: "180-#6AABA7-#AB6A9C", stroke: "#6AABA7"}],//data values for each bubbleseriesList: [{label: "Beijing",legendEntry: true,data: { y: [85], x: [150], y1: [1340] },markers: {type: "tri"}}, {label: "New Delhi",legendEntry: true,data: { y: [80], x: [167], y1: [1150] },markers: {type: "diamond"}}, {label: "Los Angeles",legendEntry: true,data: { y: [92], x: [400], y1: [309] },markers: {type: "circle"}}, {label: "Tokyo",legendEntry: true,data: { y: [94], x: [250], y1: [126] },markers: {type: "invertedTri"}}, {label: "London",legendEntry: true,data: { y: [82], x: [200], y1: [140] },markers: {type: "cross"}}, {label: "Lagos",legendEntry: true,data: { y: [48], x: [374], y1: [72] },markers: {type: "box"}}]});});</script> The script tags should be embedded within the HTML tags for a successful run. If we successfully run the preceding code, we should have a bubble chart that looks like this: See also You can visit http://wijmo.com/wiki/index. php/Bubblechart for more details about Wijmo bubble charts and more advanced options available for customizing your charts. Summary In this Article, we have discussed the Column Bar Chart and Bubble Chart wijmos. Column bar chart (Simple) explains how to convert a regular Wijmo bar chart to a column bar chart widget. Bubble chart (Intermediate) shows how to create and customize a bubble chart widget Resources for Article : Further resources on this subject: Getting Started with jQuery [Article] Exclusive Offer On jQuery Books: Winner Of 2010 Open-Source JavaScript Libraries [Article] New Effects Added by jQuery UI [Article]
Read more
  • 0
  • 0
  • 1279