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-interacting-data-sharepoint-server
Packt
02 Aug 2010
10 min read
Save for later

Interacting with Data on the SharePoint Server

Packt
02 Aug 2010
10 min read
Managing data in a Silverlight RIA included in a SharePoint solution So far, we have been able to create, deploy, and debug a Silverlight RIA that read data from a list in the SharePoint server. It is also possible to insert, update, and remove items from these lists. In fact, the typical LOB (Line-Of-Business) RIA performs CRUD (Create, Read, Update, and Delete) operations. Therefore, we can create a Silverlight RIA to perform some of the CRUD operations with the existing list of tasks, by using more features provided by the SharePoint 2010 Silverlight Client OM. We could improve our existing Silverlight RIA that displays data from the existing list in a grid. However, we are going to create a new Silverlight RIA and then, we will improve both applications to work together to offer a complex LOB solution. We will analyze diverse alternatives to simplify the deployment process and show how to debug a Silverlight RIA that queries data from a SharePoint server. Working with the SharePoint 2010 Silverlight Client Object Model to insert items Now, we are going to create a new solution in Visual Studio. It will include two new projects: A Silverlight application project, SLTasksCRUD An empty SharePoint 2010 project with a module, SPTasksCRUD Follow these steps to create the new Silverlight RIA that allows a user to insert a new item into the list in the SharePoint server: This example requires the ProjectsList2010 list created in SharePoint Start Visual Studio as a system administrator user. Select File New | Project...| or press Ctrl+Shift+N. Select Other Project Types Visual Studio Solutions under Installed Templates in the New Project dialog box. Then, select Blank Solution and enter TasksCRUD as the project's name and click OK. Visual Studio will create a blank solution with no projects. Right-click on the solution's name in Solution Explorer and select Add New Project from the context menu that appears. Select Visual C# Silverlight under Installed Templates in the New Project dialog box. Then, select Silverlight Application, enter SLTasksCRUD as the project's name and click OK. Deactivate the Host the Silverlight application in a new Web site checkbox in the New Silverlight Application dialog box and select Silverlight 4 in Silverlight Version. Then, click OK. Visual Studio will add the new Silverlight application project to the existing solution. Follow the necessary steps to add the following two references to access the new SharePoint 2010 Silverlight Client OM: Microsoft.SharePoint.Client.Silverlight.dll Microsoft.SharePoint.Client.Silverlight.Runtime.dll Open App.xaml.cs and add the following using statement: using Microsoft.SharePoint.Client; Add the following code in the StartUp event handler to initialize the Microsoft.SharePoint.Client.ApplicationContext with the same initialization parameters and the synchronization context for the current thread (the UI thread). private void Application_Startup(object sender, StartupEventArgs e){ this.RootVisual = new MainPage(); // Initialize the ApplicationContext ApplicationContext.Init(e.InitParams, System.Threading.SynchronizationContext.Current);} Open MainPage.xaml, define a new width and height for the Grid, 800 and 600, add the following controls, and align them as shown in the following screenshot: Six Label controls aligned at the left with the following values for their Content properties. They are Title, Priority, Status, % Complete, Start Date and Due Date. One Label control, located at the bottom, lblStatus. One TextBox control, txtTitle. One ComboBox control, cboPriority. One ComboBox control, cboStatus. One Slider control, sldPercentComplete. Set LargeChange to 10, Maximum to 100, and Minimum to 0. This slider will allow the user to set the percentage of the total work that has been completed. One DatePicker control, dtStartDate. One DatePicker control, dtDueDate. One Button control, butInsert. Set its Title property to Insert Select the Grid, LayoutRoot. Click on the Categorized button to arrange the properties by category. Then, click on Brushes Background| and a color palette with many buttons located at the top and the bottom will appear. Click on the Gradient Brush button, located at the top and then on the Vertical Gradient one, located at the bottom. Define both the start and the stop colors. The rectangle that defines the background Grid will display a nice linear gradient, as shown in the previous screenshot. Open MainPage.xaml.cs and add the following using statements to include the Microsoft.SharePoint.Client namespace: using Microsoft.SharePoint.Client;using SP = Microsoft.SharePoint.Client;Add the following two private variablesprivate SP.ClientContext _context;private SP.List _projects; Add the following method to fill the drop-down lists that will display the different options for the priority and the status: private void FillComboBoxes(){ cboPriority.Items.Add("(1) High"); cboPriority.Items.Add("(2) Normal"); cboPriority.Items.Add("(3) Low"); cboStatus.Items.Add("Not Started"); cboStatus.Items.Add("In Progress"); cboStatus.Items.Add("Completed"); cboStatus.Items.Add("Deferred"); cboStatus.Items.Add("Waiting on someone else");} It is possible to retrieve the possible choices for both the Priority and Status fields.In this case, we add the possible values in this method and then we will learn how to retrieve the choices through queries to the SharePoint server. Add the following line to the page MainPage constructor: public MainPage(){ InitializeComponent(); FillComboBoxes();} Now, it is necessary to add code to execute the following tasks: Connect to the SharePoint server and load the current user that logged on the server, ConnectAndAddItemToList method. Add a new item to the ProjectsList2010 list, considering the values entered by the user in the controls, AddItemToList method. private void ConnectAndAddItemToList(){ // Runs in the UI Thread lblStatus.Content = "Started"; _context = new SP.ClientContext(SP.ApplicationContext.Current.Url); _context.Load(_context.Web); // Load the current user _context.Load(_context.Web.CurrentUser); _context.ExecuteQueryAsync(OnConnectSucceeded, null);}private void AddItemToList(){ // Runs in the UI Thread lblStatus.Content = "Web Connected. Adding new item to List..."; _projects = _context.Web.Lists.GetByTitle("ProjectsList2010"); ListItem listItem = _projects.AddItem(new ListItemCreationInformation()); listItem["Title"] = txtTitle.Text; listItem["StartDate"] = Convert.ToString(dtStartDate.SelectedDate); listItem["DueDate"] = Convert.ToString(dtDueDate.SelectedDate); listItem["Status"] = "Not Started"; var fieldUserValue = new FieldUserValue(); // Assign the current user to the Id fieldUserValue.LookupId = _context.Web.CurrentUser.Id; listItem["AssignedTo"] = fieldUserValue; listItem["Priority"] = "(2) Normal"; listItem["PercentComplete"] = Convert.ToString(Math.Round(sldPercentComplete.Value, 0)/100); listItem.Update(); // Just load the list Title proprty _context.Load(_projects, list => list.Title); _context.ExecuteQueryAsync(OnAddItemToListSucceeded, OnAddItemToListFailed);} All the previously added methods are going to run in the UI thread. The following methods, which are going to be fired as asynchronous callbacks, schedule the execution of other methods to continue with the necessary program flow in the UI thread: When the connection to the SharePoint server, requested by the ConnectAndAddItemToList method, is successful, the OnConnectSucceeded method schedules the execution of the AddItemToList method in the UI thread. If the ConnectAndAddItemToList method fails, the OnConnectFailed method schedules the execution of the ShowErrorInformation method in the UI thread, sending the ClientRequestFailedEventArgs args instance as a parameter to the delegate. When the insert operation performed on the list available in the SharePoint server, requested by the AddItemToList method, is successful, the OnAddItemToListSucceeded method schedules the execution of the ShowInsertResult method in the UI thread. If the AddItemToList method fails, the OnAddItemToList method schedules the execution of the ShowErrorInformation method in the UI thread, sending the ClientRequestFailedEventArgs args instance as a parameter to the delegate. private void ShowErrorInformation(ClientRequestFailedEventArgsargs){ System.Windows.Browser.HtmlPage.Window.Alert( "Request failed. " + args.Message + "n" + args.StackTrace + "n" + args.ErrorDetails + "n" + args.ErrorValue);}private void ShowInsertResult(){ lblStatus.Content = "New item added to " + _projects.Title;}private void OnConnectSucceeded(Object sender, SP.ClientRequestSucceededEventArgs args){ // This callback isn't called on the UI thread Dispatcher.BeginInvoke(AddItemToList);}private void OnConnectFailed(object sender,ClientRequestFailedEventArgs args){ // This callback isn't called on the UI thread // Invoke a delegate and send the args instance as a parameter Dispatcher.BeginInvoke(() => ShowErrorInformation(args));}private void OnAddItemToListSucceeded(Object sender, SP.ClientRequestSucceededEventArgs args){ // This callback isn't called on the UI thread //Dispatcher.BeginInvoke(GetListData); Dispatcher.BeginInvoke(ShowInsertResult);}private void OnAddItemToListFailed(object sender,ClientRequestFailedEventArgs args){ // This callback isn't called on the UI thread // Invoke a delegate and send the args instance as a parameter Dispatcher.BeginInvoke(() => ShowErrorInformation(args));} Add the following line to the Click event for the butInsert Button. This way, when the user clicks on this button, the application will connect to the SharePoint server and will insert the new item. private void butInsert_Click(object sender, RoutedEventArgs e){ ConnectAndAddItemToList();} Now, follow these steps to create a new SharePoint module and link it to the previously created Silverlight RIA, SLTasksCRUD. Stay in Visual Studio as a system administrator user. Right-click on the solution's name in Solution Explorer and select Add | New Project… from the context menu that appears. Select Visual C# SharePoint | 2010| under Installed Templates in the New Project dialog box. Then, select Empty SharePoint Project, enter SPTasksCRUD as the project's name, and click OK. The SharePoint Customization Wizard dialog box will appear. Enter the URL for the SharePoint server and site in What local site do you want to use for debugging? Click on Deploy as a sandboxed solution. Then, click on Finish and the new SPTasksCRUD empty SharePoint 2010 project will be added to the solution. Add a new item to the project, that is a SharePoint 2010 module, Module1. Expand the new SharePoint 2010 module, Module1, in the Solution Explorer and delete the Sample.txt file. Now, right-click on Module1 and select Properties in the context menu that appears. In the Properties palette, click the ellipsis (...) button for the Project Output References property. The Project Output References dialog box will appear. Click on Add, below the Members list. The empty SharePoint 2010 project's name, SPTasksCRUD, will appear as a new member. Go to its properties, shown in the list, located at the right. Select the Silverlight application project's name, SLTasksCRUD, in the Project Name drop-down list. Select ElementFile in the Deployment Type drop-down list. The following value will appear in Deployment Location: {SharePointRoot}TemplateFeatures{FeatureName}Module1, as shown in the next screenshot: Click OK and the SharePoint project now includes the Silverlight application project, SLTasksCRUD. Now, right-click on the SharePoint 2010 project, SPTasksCRUD, and select Properties in the context menu that appears. Click on the SharePoint tab in the properties panel and different options for the SharePoint deployment configuration will be shown. Activate the Enable Silverlight debugging (instead of Script debugging) checkbox. Remember that this option will allow us to debug code in the Silverlight application that adds items to the list in the SharePoint server. Right-click on the solution's name in Solution Explorer and select Properties from the context menu that appears. Select Startup Project in the list on the left, activate Single startup project, and choose the SharePoint project's name in the drop-down list below it, SPTasksCRUD. Then, click OK. Build and deploy the solution. Now that the WSP package has been deployed to the SharePoint site, follow the necessary steps to create a new web page, add the Silverlight Web Part, and include the Silverlight RIA in it. Remember that in this case, it is not necessary to upload the .xap file because it was already deployed with the WSP package.
Read more
  • 0
  • 0
  • 1295

article-image-building-job-board-website-using-jobpress
Packt
30 Jul 2010
9 min read
Save for later

Building a Job Board Website using JobPress

Packt
30 Jul 2010
9 min read
(For more resources on WordPress, see here.) With so many types of jobs out there, the possibilities for niche job boards are almost endless. Drawing in traffic shouldn't prove to be too difficult either because, after being populated with niche-specific job listings, your job board will be filled with a wide variety of targeted keywords. Once these job seekers arrive at your niche job board they should transition into repeat traffic since they will be able to easily peruse job listings that are appropriate to the skills that they posses. That will remove much of the hassle that job seekers suffer as they seek employment. FoxNews and Smashing Magazine are two users of the JobPress theme who have zeroed in on a niche for their job boards. FoxNews only covers positions available within their own company while Smashing Magazine provides job listings primarily targeted toward those seeking design and programming-related jobs. So, as you can see, opting to focus on a niche will put you and your job board in good company.         The previous screenshots of the FoxNews and Smashing Magazine job boards will give you some idea of just what you can do with this theme. As you can see, JobPress can be integrated into the design of an existing website so that the two blend together nicely. In this article, you will learn how to: Build a dedicated job board website Make the JobPress sidebar widget-ready Run JobPress alongside an existing web site Once this project is complete, you will have succeeded in creating a site that's similar to the one shown in the following screenshot: Introducing JobPress JobPress, which can be found at http://www.dailywp.com/jobpress-wordpresstheme/, took the inspiration for its features from several of the job boards already in existence on the Internet. As you would expect, the theme offers those building a job board site the ability to edit and customize various features using a theme-related settings screen. This one screen houses all of the settings specific to this theme, so the customization of JobPress and its features can be completed in record time. If you're looking to earn a profit from your job board, then you have two options. You can either include advertisements in their various forms or you can charge a fee in order to post a job listing. If you would like to go with the latter option, then you can simply enter your PayPal information into the appropriate settings area and JobPress and PayPal will take care of the rest. JobPress also includes a feature whereby payment is verified between PayPal and JobPress, so that you can always be sure that the job listings that appear on your website have, in fact, been paid for. JobPress makes the job hunt easier for your visitors by allowing them to use the FREELANCE, FULL TIME, and PART TIME tags to sort listings. These sort options are available on both the front page and within categories to make locating a suitable job as easy as possible. If job seekers want to search for a specific job, instead of browsing, then they can do that too by using the search box provided by JobPress. JobPress also includes a feature that will alert job seekers when a listing has been online for more than 30 days. That way they will be able to see which listings are fresh and which ones are likely to have already been filled by another applicant. Running a job board isn't just about pleasing the job seekers who come to your site looking for listings. It's also about catering to the desires of those who will be placing ads. After all, without them your job board won't contain any job listings which means that there will be nothing there to draw in visitors. The developer behind JobPress took that into consideration when designing this theme by making the job listing submission process virtually hassle-free. Setting up and configuring JobPress After uploading and activating the JobPress theme, a new JobPress Settings link will appear. From this screen, all of your JobPress settings can be configured. So, to begin customizing JobPress to your liking, click on JobPress Settings. The Publishing & Payment Settings area is the first section that you will need to concentrate on during this configuration process. The Auto Publish? setting allows you to publish job listings automatically or manually. This setting is currently set to On, but you may switch it to Off if you prefer to have more control over the ads that appear on your website. The Paid Submission? setting is currently enabled. If you would like to charge a fee for placing a job listing, then this setting shouldn't be changed. Otherwise, change it to Disable to offer job listing placements for free. If you've decided to offer job listing placements for free, then proceed to the Custom Information settings area. If, you've instead opted to charge for the placement of job listings, then you will need to configure the remaining settings found in the Publishing & Payment Settings area. First, enter the email address associated with your PayPal account into the PayPal Mail textbox. In the Submission Price textbox, enter the amount that you would like to charge for standard ad placements. The last setting in this area is the Currency drop-down menu. Here you need to choose the currency associated with your area of the world. The Custom Information section of this settings screen is next and Renew Jobs is the first option that you will see. This feature is currently set to Enabled which means that job posters will be able to renew their listings if they would like to do so. This setting can be left at its default or you can, instead, set it to Disable if you would rather not provide a renewal option. It's best, however, for ease of use, if this setting remains enabled. The Apply Online option is also set to Enabled and it's probably best if this is left as is so that your job board offers the highest level of convenience to job seekers. With this setting in place visitors to your job board will be able to apply online for the jobs that they're interested in. The Sociable setting is also currently enabled, which is ideal since this will provide your visitors with a way to share a job listing that they see on your site with someone who might be interested in applying. Featured Job is next and, like all of the proceeding settings, it's also enabled. If you want to provide job posters with the option of upgrading from a standard listing to one that's featured, then this setting should remain enabled. If, however, you would rather not offer featured job listings on your website, then change this setting to Disable. If you opted to leave this setting enabled, then enter the price that you plan to charge for featured job listings into the Submission Featured Job Price textbox. Now, in the Items Per Page textbox, enter the number of job listings that you would like to appear on a single page. In the Success Message text area you will find a pre-written message that's displayed on the confirmation page when a job listing is submitted. It's best if you rewrite this message to correct grammar issues and to add any additional information that you would like to provide. Success Mail is next and this setting contains a few different options that must be addressed. First, you must choose whether you would like to leave this feature set to Enabled or, instead, set it to Disable. If you would like to use this feature, then you will first need to heed the advice included below the drop-down menu which advises you to contact your web host before enabling this setting. When you contact your web host you will need to ask them to if the mail() function is activated because the Success Mail feature won't work if that function isn't enabled. If the mail() function isn't enabled, then you should next ask your web host to activate it on your account. If they're unable to do so, then you will have no choice other than to set Success Mail to Disable. If you would like to use this feature, then you will first need to heed the advice included below the drop-down menu which advises you to contact your web host before enabling this setting. When you contact your web host you will need to ask them to if the mail() function is activated because the Success Mail feature won't work if that function isn't enabled. If the mail() function isn't enabled, then you should next ask your web host to activate it on your account. If they're unable to do so, then you will have no choice other than to set Success Mail to Disable. If it was possible for your web host to enable the mail() function, and you set Success Mail to Enabled, you must next deal with the Subject textbox. The default text provided in this textbox is certainly sufficient, but you might want to add the name of your job board to the subject line. That way recipients will be able to easily identify that the message that they're receiving isn't spam. The message within the Content text area is fine as is, but you may certainly rewrite it if you like. If you do decide to create your own message, then be sure to include the tags provided by JobPress for usage in this area so that this unique information can be populated before the message is sent. The From textbox that follows should be left at its default. Now, click Save to finalize your changes. Companies submitting job listings to your site will have the ability to include their company logo along with their submission. This feature won't function properly, unless you change the permissions on the upload folder, which can be found inside the wp-content directory. So, navigate to the upload folder and then CHMOD it to 777.
Read more
  • 0
  • 0
  • 1610

article-image-activating-buddypress-default-theme-and-setting-and-configuring-buddypress
Packt
30 Jul 2010
4 min read
Save for later

Activating the BuddyPress Default Theme and Setting up and Configuring BuddyPress

Packt
30 Jul 2010
4 min read
(For more resources on WordPress, see here.) After installing and activating BuddyPress, an alert will appear at the top of your screen to tell you that the functionality offered by BuddyPress isn't available on your website just yet. For these features to be made available to your members, you will need to install a BuddyPress-compatible theme.   Activating this theme is a two step process. First, navigate to Appearance | Themes and then click Activate for the BuddyPress Default theme. Next, click on SuperAdmin | Themes. Tick the radio button labeled Yes for the BuddyPress Default theme and then click Apply Changes. Now the BuddyPress Default theme will be in use on your site and available for usage by your users. Setting up and configuring BuddyPress After activating the plugin, you might have noticed that a new BuddyPress menu appeared. Click on BuddyPress | General Settings to access the BuddyPress Settings screen. BuddyPress Settings There are only two settings on this screen that you need to concern yourself with; the rest can be left at their defaults settings. The first option that you need to alter is located at the top of the screen and is labeled Base profile group name. As you can see, this is currently set to Base. This text appears in a couple of places. First, when your users go to My Account | Profile | Edit Profile, they will see Editing 'Base' Profile Group.   The second place that this text can be found is on the BuddyPress Profile Field Setup screen where it's used as the name of the default field group.   In both instances, something less enigmatic would be beneficial. Think of a descriptive label that would be useful in both situations and then enter it into the Base profile group name textbox.   You will find the other setting that you need to configure located at the bottom of your screen, so scroll down until you see the Default User Avatar. In this area, select the type of avatar that you would like to display for users without a custom avatar and then click Save Settings. Component Setup Now, click on BuddyPress | Component Setup to be taken to the BuddyPress Component Setup screen. By default, all of the components found on this screen are enabled. How you choose to configure the majority of these settings will depend upon your preferences and the features that you would like to make available on your website. It should be noted, however, that both the bbPress Forums and Groups components should remain enabled if you plan on integrating bbPress into your community portal. Also, the Extended Profiles component should be left set to Enabled, so that your members can have more detailed profiles attached to their accounts. Profile Field Setup Skip the Forums Setup screen for now, and instead click on Profile Field Setup. On this screen, there are three actions that you can take. You can add additional field groups, add new fields, and then choose the location for each of these fields within their group. At present, your installation of BuddyPress has one default field placed within one default field group which now bears the name that it was given when you changed it from Base on the BuddyPress Settings screen. Any fields located in this default field group will appear on the signup screen under the heading of Profile Details.   This field group also appears on the screen that your users see when they go to edit their profile.   Any additional field groups that you add will only be visible to users when they wish to edit their profile. As things stand, your users will have a profile that consists of nothing more than their name. Since that doesn't make for much of a profile you need to add some additional field groups and fields. With the addition of these new groups and fields, it will be possible for your members to build a robust profile page.
Read more
  • 0
  • 0
  • 1596
Visually different images

article-image-making-better-form-using-javascript
Packt
29 Jul 2010
12 min read
Save for later

Making a Better Form using JavaScript

Packt
29 Jul 2010
12 min read
(For more resources on Joomla!, see here.) But enough chat for now, work is awaiting us! Send the form using jQuery AJAX This is not going to be as hard as it may first seem, thanks to the powerful jQuery features. What steps do we need to take to achieve AJAX form sending? First, open our default_tmpl.phpfile. Here we are going to add an ID to our button, and change it a bit, from this: <input type="submit" name="send" value="Send" class="sc_button"/> to this: <input type="button" name="send" value="Send" class="sc_button"id="send_button"/> Apart from adding the ID, we change its type from submit to button. And with this our form is prepared. We need a new file, a js one this time, to keep things organized. So we are going to create a js folder, and place a littlecontact.js file in it, and we will have the following path: modules/mod_littlecontact/js/littlecontact.js As always, we will also include this file in the mod_littlecontact.xml file, like this: <filename>js/littlecontact.js</filename> Before adding our code to the littlecontact.js file, we are going to add it to the header section of our site. We will do this in the mod_littlecontact.php file, as follows: require_once(dirname(__FILE__).DS.'helper.php');$document =& JFactory::getDocument();$document->addScript(JURI::root(true).'modules'.DS.' mod_littlecontact'.DS.'js'.DS.'littlecontact.js');JHTML::stylesheet('styles.css','modules/mod_littlecontact/css/'); I've highlighted the changes we need to make; first we get an instance to the global document object. Then we use the addScript method to add our script file to the header section.   We use JURI::root(true) to create a correct path. So now in our header, if we check the source code, we will see:   <script type="text/javascript" src="/modules/mod_littlecontact/js/littlecontact.js"></script> If instead of using JURI::root(true), we would have used JURI::root() our source code would look like the following: <script type="text/javascript" src="http://wayofthewebninja.com/ modules/mod_littlecontact/js/littlecontact.js"></script> You can find more information about the JURI::root method at: http://docs.joomla.org/JURI/root We are now ready to start working on our littlecontact.js file: jQuery(document).ready(function($){ $('#send_button').click(function() { $.post("index.php", $("#sc_form").serialize()); });}); It is a little piece of code, let's take a look at it. First we use the ready function, so all of our code is executed when the DOM is ready: jQuery(document).ready(function($){ Then we add the click method to the #send_button button. This method will have a function inside with some more code. This time we are using the post method: $.post("index.php", $("#sc_form").serialize()); The post method will send a request to a page, defined in the first parameter, using the HTTP post request method. In the second parameter we can find the data we are sending to the page. We could pass an array with some data, but instead we are using the serialize method on our form, with ID sc_form. The serialize method will read our form, and prepare a string for sending the data. And that's all; our form will be sent, without our visitors even noticing. Go ahead and try it! Also, you could take a look to the following two pages: http://api.jquery.com/jQuery.post/ http://api.jquery.com/serialize/ Here you can find some good information about these two functions. After you have taken a look at these pages, come back here, and we will continue. Well, sending the form without page reloading is OK, we will save our visitors some time. But we need our visitors to notice that something is happening and most important, that the message has been sent. We will now work on these two things. First of all we are going to place a message, so our readers will know that the form is being sent. This is going to be quite easy too. First we are going to add some markup to our default_tmpl.php, as follows: <?phpdefined('_JEXEC') or die('Direct Access to this location is not allowed.');?><div id="littlecontact"> . . . <div id="sending_message" class="hidden_div"> <br/><br/><br/> <h1>Your message is being sent, <br/>wait a bit.</h1> </div> <div id="message_sent" class="hidden_div"> <br/><br/><br/> <h1>Your message has been sent. <br/>Thanks for contacting us.</h1> <br/><br/><br/> <a href="index.php" class="message_link" id="message_back">Back to the form</a> </div></div> We have added two DIVs here: sending_message and message_sent. These two will help us show some messages to our visitors. With the messages prepared, we need some CSS styles, and we will define these in our module's styles.css file: #littlecontact{ position: relative;}#sending_message, #message_sent{ height: 235px; width: 284px; position: absolute; z-index: 100; background-color: #5B5751; top: 0; text-align: center;}.hidden_div{ visibility: hidden; display: none;}.show_div{ visibility: visible; display: block;}a.message_link:link, a.message_link:visited{ color: #ffffff; text-decoration: none;}a.message_link:hover{ text-decoration: underline;} Don't worry about writing all this code; you can find it in the code bundle, so copy it from there. Going back to the code, these are just simple CSS styles, and some of the most important ones are the hidden_div and show_div classes. These will be used to show or hide the messages. Ready to go to the JavaScript code? We will now return to our littlecontact.js file and modify it a bit: jQuery(document).ready(function($){ $('#send_button').click(function() { $.post("index.php", $("#sc_form").serialize(), show_ok()); $("#sending_message").removeClass("hidden_div"); }); $("#message_back").click(function(e){ e.preventDefault(); $("#message_sent").addClass("hidden_div"); $("#sending_message").addClass("hidden_div"); }); function show_ok(){ $("#sending_message").addClass("hidden_div"); $("#message_sent").removeClass("hidden_div"); $("input:text").val(''); $("textarea").val(''); }}); Seems a lot? Don't worry, we will take a step-by-step look at it. If we look at our previously added click function, we can see a new line, as follows: $("#sending_message").removeClass("hidden_div"); This will search for our sending_message DIV, and remove the hidden_div class. This way the DIV will be visible, and we will see a screen similar to the following screenshot: A nice message tells our visitors that the e-mail is being sent just at the moment. But we don't do only that. If we take a closer look at our previous post method, we will see some changes, as follows: $.post("index.php", $("#sc_form").serialize(), show_ok()); A new third parameter! This is a callback function, which will be executed when the request succeeds and our e-mail has been sent. But what is inside this show_ok function? Its contents are as follows: function show_ok(){ $("#sending_message").addClass("hidden_div"); $("#message_sent").removeClass("hidden_div"); $("input:text").val(''); $("textarea").val(''); } First we add the hidden_div class to the sending_message, so this sending message is not seen any more. But instead we remove the hidden_div class of our message_sent DIV, so our visitors will see this new message: But we are also emptying our inputs, text inputs, and textarea fields: $("input:text").val(''); $("textarea").val(''); So when visitors return to the form they are presented with a fresh one, just in case they have forgotten something and want to send a new e-mail. Hey who knows! Our last step is to enable a back link, so that the readers can return to the form: $("#message_back").click(function(e){ e.preventDefault(); $("#message_sent").addClass("hidden_div"); $("#sending_message").addClass("hidden_div"); }); First we target the link using its ID, and then we bind a click function to it. The next step is to prevent the default event for the link. This is why the link won't behave as a link, and won't try to load a page. This is why we are not going to load or reload a page, instead we will continue with our code, hiding both DIVs, so the form is visible again. That's it! It has not been that hard, has it? Now, it would be a great moment to take a look at the code bundle, see the code, read it, and try it by yourself. Or alternatively, keep reading a bit more if you want! Tips and tricks Look at the site http://www.ajaxload.info/. There you will be able to generate some loader GIF images. These will act as the typical clock mouse, telling the users that something is happening. Maybe you would like to use that instead of only using text. Give it a try! Validating form fields using jQuery—why validate? Ah! validating forms, so entertaining. It's just the kind of task everyone always wants to do. Well, maybe a bit less than others. But it's something that needs to be done. Why? Just to ensure that we are receiving the proper data, or even that we are receiving data. Ideally we would use JavaScript validation on the client side, and PHP validation on the server side. Server-side validation is essential, so a user turning off JavaScript still gets his/her contents validated. JavaScript validation will save us the effort of having to send all the data to the server, and then come back with the errors. We are going to use a bit of JavaScript to try to validate our form. This process is going to be quite simple too, as our form is very small. We will be doing all of our work in our littlecontact.js file. Remember our $('#send_button').click function? It looked like this: $('#send_button').click(function() { $.post("index.php", $("#sc_form").serialize(), show_ok()); $("#sending_message").removeClass("hidden_div"); }); Now with some modifications, it will be more or less as follows: $('#send_button').click(function() { //First we do some validation, //just to know that we have some data alerts = ''; if($("input[name=your_name]").val() == ''){ alerts += "we need your namen"; } if($("textarea[name=your_question]").val().length < 5){ alerts += "We need a message of at least 5 characters lengthn"; } if(alerts != ''){ alert(alerts); }else{ $.post("index.php", $("#sc_form").serialize(), show_ok()); $("#sending_message").removeClass("hidden_div"); } }); First, we define a new variable, to put all the messages in: alerts = ''; Then we check our form fields (first the input text): if($("input[name=your_name]").val() == '') As you can see, with jQuery we can select the input with a name equal to your_name and check if its value is empty. The textarea check is very similar: if($("textarea[name=your_question]").val().length < 5 But we are also checking if the length of the value is greater than five. After each one of these validations, if failed, we add a message to the alerts variable. Later, we will check if that variable is not empty. If it's not empty, it would mean that some of the checks have failed, and then we show the alerts to our visitors: alert(alerts); This will raise a typical alert message, much like the following screenshot: Informative, but not really nice. But thinking about it, we already have the jQuery UI library available, thanks to our SC jQuery Joomla! plugin. Why not use that plugin to show a better message? Let's do it. First we need to make some changes in the default_tmpl.php file: <div id="alerts" title="Errors found in the form" style="display: none;"></div> We have added a new DIV, with an ID equal to alerts, and with an informative title. Now that our markup is ready, some changes are also necessary in our littlecontact.js JavaScript file. For example, we are going to change our alert messages from the following: alerts += "- We need your namen";...alerts += "- We need a message of at least 5 characters lengthn"; To the following: alerts += "- We need your name<br/>";...alerts += "- We need a message of at least 5 chapters length<br/>"; Why are we doing this? It is because we will show HTML in our dialog, instead of just text. How are we going to show the dialog? Quite easily, by changing the following line: alert(alerts); To this: $("#alerts").html(alerts).dialog(); What are we doing here? First, we select our newly created DIV, with ID alerts, and then we use the html method, passing the variable alerts as its parameter. This will fill our DIV with the content of the alerts variable. Nested in it we will find the dialog method. This is a jQuery UI method that will create a dialog box, as we can see in the following screenshot: Better than our previous alert message, isn't it? Also notice that this dialog is matching the style of all our jQuery UI elements, like the login dialog and the tabs module. If we were to change the style in the SC jQuery Joomla! plugin, the style of the dialog will also change. If you want to know more about the jQuery UI dialog method, check the following page: http://jqueryui.com/demos/dialog/ Summary In this article we saw how to make a better form using JavaScript, send the form using jQuery AJAX, validate form fields using jQuery, and learn why it is important to validate. Well that's it for now. This is just a small example; now don't you think it would be great to give it a try? Further resources on this subject: Removing Unnecessary jQuery Loads [article] The Basics of Joomla! Module Creation and Creating a "Send us a question" Module [article]
Read more
  • 0
  • 0
  • 1551

article-image-basics-joomla-module-creation-and-creating-send-us-question-module
Packt
29 Jul 2010
9 min read
Save for later

The Basics of Joomla! Module Creation and Creating a "Send us a question" Module

Packt
29 Jul 2010
9 min read
(For more resources on Joomla!, see here.) Building a basic Joomla! module is not that difficult. In fact it's quite easy. Just stay with me, and we will divide the task into some easy-to-follow steps. First of all, we need to create a folder for our module, for example, mod_littlecontact. This folder is where we will place all the files necessary for our module. For example, one of the files we are going to need is the mod_littlecontact.php file, which is named exactly the same as the folder, but with a .php extension. Let's see what we need to put in it: <?phpdefined('_JEXEC') or die('Direct Access to this location is notallowed.');?><h1>Just a simple contact form!</h1> We will look at just the basics. First, defined('_JEXEC') checks whether the file has been included by Joomla! instead of being called directly. If it has been included by Joomla!, the _JEXEC constant would have been defined. With this PHP file created we need to create another file, an XML one this time. We will call it mod_littlecontact.xml; notice that, again, the name is the same as the folder one. Just create the file, and after that we will place the following contents in it: <?xml version="1.0" encoding="utf-8"?><install type="module" version="1.5.0"> <name>Little Contact Form</name> <author>Jose Argudo Blanco</author> <creationDate>2010</creationDate> <copyright>All rights reserved by Jose Argudo Blanco.</copyright> <license>GPL 2.0</license> <authorEmail>[email protected]</authorEmail> <authorUrl>www.joseargudo.com</authorUrl> <version>1.0.0</version> <description>A simple contact form</description> <files> <filename module="mod_littlecontact"> mod_littlecontact.php</filename> </files></install> Most of the contents of this XML file are quite easy to follow and very self-explanatory. In the files section, we have included all the files necessary for our module. Notice that we do not include the XML file itself. With these two files created, we can give a try to this simple module. Copying this folder into our Joomla! modules folder won't work, as Joomla! requires us to install the extension through the Extensions | Install/Uninstall menu. So, what do we need to do? Just compress these two files into a ZIP file by using any tool of your liking. At the end we will need to have a mod_littlecontact.zip file with the following two files inside: mod_littlecontact.php mod_littlecontact.xml Installing our module is done exactly as with any other modules. Go to the administrator screen of our site, then go to the Extensions | Install/Uninstall menu, search and select the file, and then click on Upload File & Install button. If all goes OK, and it really should, we will be able to find our module listed in Extensions | Module Manager, as seen in the following screenshot: We can click in the module name, just as we would do with any of the others. If we enter the administration panel of the module we will see a screen very much like the other modules, as Joomla! standardizes this screen. Just take a look at the Details zone, which will look like the next screenshot: He re we can select the parameters we want, and enable the module. This time we will place it in the module_7 position of our template. Also note that the description is the one that we place in the module XML file: <description>A simple contact form</description> After we have enabled the module, we will be able to see it in the frontend, in the module position we have selected: There's not too much for now, but it's working! Now we will enhance it and convert it into a contact form. Note that now that we have installed our module, a new folder will have been created into our Joomla! installation. We can find this folder in the modules folder, it will be called mod_littlecontact. So now we have this structure on our Joomla! Site: modules/ mod_littlecontact/ mod_littlecontact.php mod_littlecontact.xml As the module is already installed, we can modify these files, and we will be able to see the changes without needing to reinstall it. We have just accomplished our first step; the basics are there, and now we can concentrate on making our modifications. Creating a "Send us a question" module One of the first things we are going to create is an empty index.html file; this will be used so that no one can take a look at the folder structure for the module. For example, imagine that our site is installed in http://wayofthewebninja.com. If we go to http://wayofthewebninja.com/modules/mod_littlecontact/ we will see something like the next image: If we try to click on mod_littlecontact.php, we will see the following phrase: Direct Access to this location is not allowed. That's because the code we added to our file is as follows: <?phpdefined('_JEXEC') or die('Direct Access to this location is notallowed.');?> Of course, we don't want people to be able to see which files we are using for our module. For this place, we used the empty index.html file mentioned in the modules/mod_littlecontact folder. This way, if anyone tries to go to http://wayofthewebninja.com/modules/mod_ littlecontact/, they will see only an empty screen. Good, now note that when we add any file, we need to reflect it on the mod_littlecontact.xml file in the files section: <files> <filename module="mod_littlecontact">mod_littlecontact.php</filename> <filename>index.html</filename></files> This way, when we pack the file for install, the installation process will take this file into account, otherwise it will be left out. Once we have done this, we are going to create another file, a CSS one this time, so we can put our styles in it. For this we are going to first create a new folder, also called css. It will be placed in modules/mod_littlecontact/. Inside that folder we will create a file called styles.css; this file also needs to be declared in the XML: <filename>css/styles.css</filename> In this modules/mod_littlecontact/css/styles.css file we are going to place the following code: #littlecontact h1{ font-size: 18px; border-bottom: 1px solid #ffffff;} But then, if we are to apply these styles, we need to load this CSS file. How are we going to do this? Open the modules/mod_littlecontact/mod_littlecontact.php file and modify it as follows: <?phpdefined('_JEXEC') or die('Direct Access to this location is notallowed.');JHTML::stylesheet('styles.css','modules/mod_littlecontact/css/');?><div id="littlecontact"> <h1>Just a simple contact form!</h1></div> There's not much change here; we have enveloped our previous content in a DIV, with the littlecontact ID, so that we can target our styles. This is the easy part, but there's also an important one, shown as follows: JHTML::stylesheet('styles.css','modules/mod_littlecontact/css/'); We are using the JHTML::stylesheet method to create a link, in our header section, to our CSS file. In fact, if we check the source code on our frontend, we will see: <link rel="stylesheet" href="/modules/mod_littlecontact/css/styles.css" type="text/css" /> This way our stylesheet will be loaded, and our module will look like the next screenshot: As we can see, our styles have been applied. The JHTML::stylesheet method is quite easy to use, the first parameter being the file and the second one being the path to the file. Now we are going to prepare our simple form. Again we will modify our mod_littlecontact.php file, and now it will look more like the following: <?phpdefined('_JEXEC') or die('Direct Access to this location is notallowed.');JHTML::stylesheet('styles.css','modules/mod_littlecontact/css/');?><div id="littlecontact"> <h1>Just a simple contact form!</h1> <form action="index.php" method="post" id="sc_form"> <label>Your name:</label><br/> <input type="text" name="your_name" value="" size="40" class="sc_input"/><br/><br/> <label>Your question:</label><br/> <textarea name="your_question" class="sc_input" rows="5" cols="30"></textarea><br/><br/> <input type="submit" name="send" value="Send" class="sc_button" /> </form></div> This is a common HTML form. We need some styling here, just to make it look good. Let's make the following minimal changes to our styles.css file: #littlecontact h1{ font-size: 18px; border-bottom: 1px solid #ffffff; margin-bottom: 15px;}.sc_input{ border: 1px solid #3A362F;}.sc_button{ background-color: #3A362F; border: 0; color: #ffffff; padding: 5px;} Most styles are new, and modifications to previous h1 styling have been marked. With this minimal change our module looks a bit better. You can see it in the following screenshot:
Read more
  • 0
  • 0
  • 2911

article-image-content-rules-syndication-and-advanced-features-plone-3-intranet
Packt
27 Jul 2010
8 min read
Save for later

Content Rules, Syndication, and Advanced Features of Plone 3 Intranet

Packt
27 Jul 2010
8 min read
(For more resources on Plone, see here.) Content rules Plone features a usability layer around Zope's event system, allowing plain users to create rules tied to the most used event handlers. These rules are composed of tasks that get triggered when an event is raised in our site. Content rules are defined site-wide in the Content rules configlet, and they are available for use in any folderish object in our site. Once the rule is created, it can be locally assigned to any folder object in the site. Rules play a very important role in intranets. We can use them as a mechanism for notification, and they also help in adding dynamism to our intranet. One of the most demanded features in an intranet is the ability to be aware when content is added, changed, or even deleted. The notification of this change to the users can be achieved via content rules assigned strategically, or by user demand in any folder or intranet application, such as forums or in a blog. We can use content types to help us model some of our corporate processes or daily tasks. Move or copy objects to other folders (done by users), just in case some of our processes require this kind of an action. We can find other interesting uses of content rules in our intranet, such as executing an action when a state transition is triggered. All these actions can be carried out programmatically, but the power of content rules lie in that they can be executed thorough the Plone UI and by any experienced user. We can access the manage rules form via the Rules tab in any folder. If we don't have any rules created, the form will address us to create them in the content rules configlet. This control panel configlet will aid us to create and manage content rules of our site: The form is divided into two parts. The first is dedicated to global settings applied to all rules. In this version, there is only one setting in this category to enable and disable the rules in the whole site. If deselected, the whole rule system is disabled and no rules will be executed in the site. The other part of the form is reserved for the rule management interface. Here we can find the already created rules, manage them, and create new ones. We can display them by type using the selector on the right. Adding a new rule Click on the Add content rule button. It will open a new form with the following fields: Title: Title of the rule. Description: Summary of the rule. Triggering event: Starts the execution of the rule. Enabled: Whether or not this rule is enabled. Stop executing rules: Defines if the engine should continue the execution of other rules. It is useful if we assign several rules to a container and the execution of a particular rule excludes any other rule execution. By default, these are the available events: Object added to this container Object modified Object removed from this container Workflow state changed After creating one rule at least, the configlet will let us manage the existing rules, allowing us to perform the standard edit, delete, enable, and disable actions. But this is only the first step. We've created the rule and assigned an event to it. Now it's time to configure the task, which the rule will perform. There are two items to configure—conditions and actions. We can add as many conditions as we want to, and modify the order in which they can be applied. We can add the following types of conditions: Content type: Apply the rule only if an object of this type has triggered the event File extension: Execute the action only if a file content type that has this extension has triggered the event Workflow state: Apply only if a content type in the workflow state specified has triggered the event User's group: Execute only if a user member of a specific group triggers the event User's role: Same as User's group, but by a user having a specific role in that context The actions that a rule can execute are limited but they cover the most useful use cases: Logger: Output a message to the message system log Notify user: Notify the user via a status message Copy to folder: The object that triggers the event is copied to the specified folder Move to folder: The object that triggers the event is moved to the specified folder Delete object: The object that triggers the event is deleted Transition workflow state: An attempt to change workflow of the object that triggers the event via the specified transition Send e-mail: Send e-mail to a specific user By default, only managers can define and apply new content rules, but we can allow more user roles to access their creation. Assigning rules to folderish objects Once the rule is created, we can assign them to any of Plone's folderish content types. Just go to any folderish object and click on the Rules tab. Just use the drop-down box Assign rule here to choose from the available rules and click on Add. We can review what rules are assigned in this container and manage them as well. We can enable, disable, and choose whether to apply them to subfolders or only to current folders, and of course, unassign them. Making any content type rule aware All folderish default content types of Plone are content rule aware. However, not all third-party content types are content rule aware. This is because either they are old or simply do not enable this feature in the content type declaration. In the case of third-party content types, which are not content rule aware, we can enable their awareness by following these instructions: Add an object of the desired content type anywhere in our site, if we haven't created it yet. Find it in the ZMI and access the Interfaces tab. Once there, find the interface plone.contentrules. engine.interfaces.IRuleAssignable in the Available marker interfaces fieldset. Select it and click on the Add button. By doing so, we are assigning an additional marker interface to that content type, which will enable (mark) this instance of the content type (that is, make it aware of the content rule). From this moment onwards, the selected object will have available the Rules tab, and in consequence, we can assign rules to it. Syndication Plone has always paid special attention to syndication, making its folderish content types syndicable. Collections export their contents automatically in a view that all collections have—RSS view. But we can also enable syndication for single folders on our site. Using RSS feeds in our intranet is the recommended approach for keeping our users posted about the changes in syndicated folders, if they are collections or plain folders. Enabling folder syndication For enabling syndication for a particular folder, we need to access the view, synPropertiesForm, from the folder we want to be syndicable. For example, if we want to access this view in the ITStaff folder, we should browse the URL: http://localhost:8080/intranet/ITStaff/synPropertiesForm This view is hidden by default, although we can make it visible in order to allow users to enable folder syndication by themselves. We can make it visible by accessing the portal_actions tool in the ZMI. Go to the object action category and choose syndication. Then just make this action visible by enabling the Visible attribute and choose who will be able to access this view by selecting the item permissions in the Permissions selection box. Once in the synPropertiesForm form, we should click on the Enable syndication button. Then another form is shown to allow us to configure how the publication of the feed will be performed. Following are the syndication details available: Update period: How often the feed will be updated Update frequency: How many times the update will occur inside the period specified in the previous field Update base: When the update will take place Maximum items: How many items the feed will show Accessing a secure RSS feed Syndication was conceived to access information from public resources. Inside an intranet, it will be very common that the folder we want to enable for syndication will be not published, and in consequence, the feed associated will be private. The problem is that there are few feed readers that support feed authentication and even using them. We will have to enable HTTP authentication in our site's PAS configuration, which is not recommended. So we propose two workarounds. We can use a feed enabled browser to browse our intranet and our feeds as well. With this approach, if we are logged in, then we will have access to authenticated feeds. Firefox and Internet Explorer already have this feature. The second approach is to have a special workflow state for the syndicated folders inside our site for being accessible without authentication as anonymous users. Obviously this workaround will make the folder content visible to anonymous users, and it's not an option when privacy of the contained information is a must.
Read more
  • 0
  • 0
  • 1122
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-building-our-own-plone-3-theme-add-product
Packt
27 Jul 2010
6 min read
Save for later

Building our own Plone 3 Theme Add-on Product

Packt
27 Jul 2010
6 min read
(For more resources on Plone, see here.) We can build our own theme add-on product from scratch. It can be done easily with PasteScript. Just type this on our command line from the root of our buildout: $ cd src$ paster create -t plone3_theme plonetheme.myintranet Answer all the questions with the default option except for: Skin Name: A human facing name for the theme, added to portal_skins, for example, MyIntranetTheme. Skin Base: Name of the theme from which this is copied. By default, it is Plone Default. Answer the default option here. Empty Styles?: If true, it will override default public stylesheets with empty ones. Answer False. Include documentation?: If true, the generated theme will include auto- explanatory documentation, desirable for beginners. The resultant theme add-on product will be generated in the src buildout folder. This add-on is completely usable right now, but it's innocuous. Once installed, it will replace the original Plone default theme with the one in this package. Installing the product Just proceed as any other add-on product. However, since we are developing the product, we should specify it in our buildout by filling the develop directive in the buildout section and the eggs directive in the instance section in our buildout.cfg file: [buildout]...develop = src/plonetheme.myintranet...[instance]...eggs = plonetheme.myintranet Go to the package folder, src/plonetheme.myintranet/plonetheme/myintranet, and edit the configure.zcml file. As we don't want to define an i18n folder, delete the following line if it exists: <i18n:registerTranslations directory="locales" /> And then, rerun buildout.cfg: $ ./bin/buildout$ ./bin/instance fg Now, go to the Add-on Products control panel configlet and install it. If we browse our site, we will notice that nothing has changed, because we've chosen to inherit the default theme in our new one. But, now the theme defined in our theme add-on product is in use in our site. Check it out in portal_skins: Notice three things in the previous screenshot: the Default skin is our recently created skin and three additional Plone skin layers have been added to the top of the layer's precedence order list. These three layers will contain the resources we may need for our new theme. These layers represent three folders inside our package structure; to be more precise, those inside skins folder: Name of the layer/folder Description plonetheme_myintranet_custom_images It will contain our theme images. plonetheme_myintranet_custom_templates It will contain our theme custom templates. plonetheme_myintranet_styles It will contain our theme styles. In fact, this layer organization is merely for convenience, as all the layers can contain any type of resources. Customizing Plone skin layer resources As our theme product is positioning the new layers on the top of the precedence order, the elements we place in these folders will override those in layers with less precedence. Just place our custom resource in any of the layers defined by our product and name it as the original one. Our custom resource will override the default one. We can also place other resources we may use, such as our custom templates, images, and styles as well. Enabling CSS debug mode By default, the changes made to our product will not be available until we restart our instance. For the changes to take effect immediately, we should enable CSS debug mode in CSS resource registry. We will find this setting at the top of the portal_css ZMI view. In debug/development mode, stylesheets are not merged to composites, and caching and compression of CSS is disabled. The registry also sends HTTP headers to prevent browsers from caching the stylesheets. It's recommended to enable this mode during CSS-related development. Remember to turn it off again when we finish CSS modifications, as debug mode affects site performance. Customizing the site logo Plone renders the site logo combining two kinds of resources—the viewlet plone. logo provides the HTML structure needed and a Plone skin layer image. Let's say we want to change the site logo and add an additional logo of our company containing a link to the corporate web besides it. We need to customize the original logo with the logo of our intranet and add the required HTML structure to add the new company logo besides the original one. We will need to customize the original logo and the plone.logo viewlet. Later, we will need to add our company logo as a new Plone skin layer image. Customizing the logo image and adding a new one We should override the original logo image with our customized one. In order to accomplish this, we should rename the image we've chosen to use as our site logo with the same name as the original one. The original logo image is called logo.jpg and it is located in the plone_images skin layer. We override it by simply placing our customized image inside skins/plonetheme_myintranet_custom_images and naming it exactly the same as the original one. Place the image for the second logo here too, and name it as company-logo.png. Customizing the plone.logo viewlet Customizing a viewlet is a little trickier than overriding skin layer resources. We will need to tell Zope that we want to override the original viewlet declaration by creating an overrides.zcml file in the plonetheme/myintranet folder of our custom add-on product, and add the attribute that tells Zope where to find the new template associated to this viewlet: <configure i18n_domain="plonetheme.myintranet"> <!-- The new logo viewlet declaration --> <browser:viewlet name="plone.logo" manager="plone.app.layout.viewlets.interfaces.IPortalHeader" class="plone.app.layout.viewlets.common.LogoViewlet" template="browser/newlogo.pt" permission="zope2.View" /></configure> Then place this Zope page template called newlogo.pt in the browser folder of our add-on product: <a id="portal-logo-company" tal_attributes="href string:http://www.mycompany.com/"> <img src="company-logo.png" alt="Company.com logo" title="Company.com logo"/></a><a metal:define-macro="portal_logo" id="portal-logo" accesskey="1" tal_attributes="href view/navigation_root_url" i18n_domain="plone"> <img src="logo.jpg" alt="" tal_replace="structure view/logo_tag" /></a> We leave the original logo template at the end of the file and add a new link tag with the structure for the new logo and the reference to the new Plone skin layer image (company-logo.png). Restart our instance to see the changes applied. This is needed because we have overridden a viewlet defining an additional ZCML file.
Read more
  • 0
  • 0
  • 1530

article-image-integrating-silverlight-4-sharepoint-2010
Packt
27 Jul 2010
7 min read
Save for later

Integrating Silverlight 4 with SharePoint 2010

Packt
27 Jul 2010
7 min read
Understanding the benefits of integrating Silverlight with SharePoint The following list shows many benefits of integrating Silverlight with SharePoint 2010: Rich UX: Silverlight RIAs can offer a rich user experience. You can take full advantage of the rich visual capabilities offered by Silverlight and include them in a SharePoint site. The rich and interactive content offers an incredible new world of possibilities in SharePoint. For example, you can offer an interactive balanced scorecard with animated graphs, rich navigation capabilities, and context menus. Code runs on the client: You can take advantage of the power of the client computers accessing the SharePoint server. You can use threading and asynchronous calls to offer responsive user interfaces and to take advantage of modern multi-core microprocessors found in client computers. You can offer great response times without the need to wait for the server to load another page. You can take advantage of rich controls, animations, and exciting multimedia effects. The processing removes load from the server and enables you to use both the server and the client in your solutions. Additionally, Silverlight 4 is cross-browser capable and we can take advantage of the improved Out of Browser features to create applications that interact with the SharePoint 2010 server but run in the Windows desktop, out of the web browser. Efficient applications: As you can work with the power offered by the client, you can process data without the need to make requests to the server all the time. This way, you can create load-balanced solutions. Access to the Client OM (Client Object Model): When you have to access data and services offered by the SharePoint 2010 server, you don't need to create your own complex infrastructure. There is no need to add additional layers. You can take advantage of the new Client Object Model, also known as Client OM. As you can work with asynchronous calls to the Client OM, you can still offer great responsive applications when consuming services from the server. Users can interact with SharePoint data without requiring server calls as they would from traditional pages. Lots of the processing can be pushed down to the client. This way, as previously explained, you can remove load from the SharePoint server and create load-balanced solutions. Leverage your existing Silverlight knowledge, components, and applications: You can build new capabilities quickly from existing Silverlight components and applications, integrating them with SharePoint 2010.   Creating a SharePoint solution   Now, when we design a new SharePoint 2010 solution, we will be able to consider Silverlight RIAs as new components for the global solution. We have to consider the aforementioned benefits of integrating Silverlight with SharePoint and decide which parts would be convenient to create as Silverlight RIAs. This way, we can focus on preparing the SharePoint 2010 infrastructure and then we can access data and services offered by the server through Silverlight RIAs. For example, you can view the images found in an assets library defined in SharePoint through a Silverlight application. Once you start integrating Silverlight with SharePoint, you will find a new exciting way of enhancing SharePoint solutions. Preparing the development environment We want to take full advantage of modern technologies. First of all, we must install the latest tools and begin working on configurations. Later, we will be able to use our existing knowledge to create different kinds of RIAs for SharePoint 2010, using Silverlight 4—the newest kid-on-the-block from Microsoft. Silverlight 4 is backward-compatible with its previous version, Silverlight 3. Therefore, when an example uses a feature found only in Silverlight 4, you will find a note explaining this situation. Most of the examples work for both Silverlight versions. However, we will also take advantage of some of the new features found in Silverlight 4. The only requirements underpinning the development and integration of RIAs into SharePoint 2010 sites are understanding the basics of the C# programming language, ASP.NET, XAML code, and the Visual Studio IDE. We will cover any other requirements in our journey through the creation of many different kinds of RIAs to run in a SharePoint 2010 site. First, we must download and install various Silverlight development tools. We need Visual C# 2010 Professional, Premium, or Ultimate installed, in order to successfully complete the installations explained in the following section. Visual C# 2010 allows us to choose the desired Silverlight version (for example, version 3 or version 4). The following part will show Visual Studio 2010 Ultimate screenshots. If you use other versions, some elements that appear in the screenshots could be different but the steps are all valid for the aforementioned versions. Setting up the development environment Follow these steps to prepare the development environment: Download the following files: Application's name Download link File name Description Silverlight 4 Tools for Visual Studio 2010 http://www.microsoft.com/downloads/details.aspx?FamilyID=eff8a0da-0a4d-48e8-8366-6ddf2ecad801&displaylang=en Silverlight4_Tools.exe We must install Silverlight 4 Tools in order to create Silverlight 4 applications in the Visual Studio 2010 IDE, using XAML and C#. It will co-exist with previous Silverlight SDKs (Software Development Kits). This new version of Silverlight Tools also includes the WCF RIA Services package. Silverlight 4 Offline Documentation (in CHM format) http://www.microsoft.com/downloads/details.aspx?familyid=B6127B9B-968C-46C2-8CB6-D228E017AD74&displaylang=en Silverlight_Documentation.EXE We must download and run this file to decompress its content because, because we will need access to Silverlight 4 official documentation in due course. Expression Blend for .NET 4 http://www.microsoft.com/downloads/details.aspx?FamilyID=88484825-1b3c-4e8c-8b14-b05d025e1541&displaylang=en Blend_Trial_en.exe This tool will enable us to create content that targets Silverlight 4 and to create rapid prototypes with the SketchFlow tool. Silverlight Toolkit (Updated for Silverlight 4 compatibility) http://codeplex.com/Silverlight Silverlight_4_Toolkit_April_2010.msi It is convenient to download the latest stable release. This toolkit provides a nice collection of Silverlight controls, components, and utilities made available outside the normal Silverlight release cycle. It will be really helpful to use these controls to provide even more attractive user interfaces. Besides, it includes more Silverlight themes. Run the installers in the same order in which they appear in the above table and follow the steps to complete the installation wizards. Once the installations have successfully finished, run Visual Studio 2010 or Visual Web Developer 2010 (or later). Select File | New | Project... or press Ctrl+Shift+N. Select Visual C# | Silverlight under Installed Templates in the New Project dialog box. You will see many Silverlight templates, including Silverlight Business Application and WCF RIA Services Class Library, as shown in the following screenshot: Discovering the rich controls offered by the Silverlight Toolkit Silverlight Toolkit is a Microsoft project offering many rich controls, components, and utilities that can help us to enhance our Silverlight UI (User Interface). As we want to create a very attractive UI for SharePoint, it is convenient to get familiar with its features. Follows these steps to see the controls in action and to change the values for many of their properties. Select Start | All Programs | Microsoft Silverlight 4 Toolkit April 2010 | Toolkit Samples and your default web browser will display a web page with a Silverlight application displaying a list of the controls organized in ten categories as follows: Controls Data DataForm Data Input DataVisualization Input Layout Navigation Theming Toolkit By default, the default.htm web page is located at C:Program Files (x86)Microsoft SDKsSilverlightv4.0ToolkitApr10Samples in 64-bit Windows versions. Click on a control name under the desired category and the right panel will display the control with different values assigned for its properties, creating diverse instances of the control. For example, the following screenshot shows many instances of the Rating control under the Input category. Click on the buttons shown at the bottom of the web page and you will be able to see both the XAML and the C# code used to create the sample for the control. For example, the following screenshot shows the XAML code for the DataGrid control example, DataGridSample.xaml. You can also click on DataGridSample.xaml.cs and check the C# part. This control appears under the Data category.
Read more
  • 0
  • 0
  • 1195

article-image-through-web-theming-using-python
Packt
26 Jul 2010
2 min read
Save for later

Through the Web Theming using Python

Packt
26 Jul 2010
2 min read
Download code from here (Read more interesting articles on Plone here.) Examining themes in the Zope Management Interface Now that we have seen in part how themes work, let us take a closer look at their representation in Zope Object Database (ZODB). Browse to http://localhost:8080/Plone. Click on Site Setup Zope Management Interface| and you should see: This is a Through the Web (TTW) representation of all the objects in the database at the Plone site level (the application root is one level above). The most frequently used theme-related objects here are: portal_css portal_javascripts portal_skins portal_view_customizations Of these, portal_css and portal_javascripts are most often used to enable their respective debug modes, wherein the CSS and JavaScript files are not compiled into a single file (not to be confused with Zope 2's debug mode which detects filesystem changes in real time when enabled). Take a look at your site with Firebug, in particular the style tab. You should see: Now enable debug mode in portal_javascripts and look again. You should see: When portal_css debug mode is enabled, we can see (or by viewing the HTML source) that the CSS files are loaded individually in Firebug. The same applies to portal_javascripts debug mode. This can be absolutely invaluable when trying to correlate various visual elements with their respective sources. In addition to debug mode, you can also add CSS/JavaScript files to their respective registries through the Web, which brings us to the next topic.
Read more
  • 0
  • 0
  • 1181

article-image-security-plone-sites
Packt
26 Jul 2010
6 min read
Save for later

Security in Plone Sites

Packt
26 Jul 2010
6 min read
Download code from here More about securityFor a closer look at a variety of Plone-related security information, visit http://plone.org/products/plone/security/overview.For Erik Rose and Steve McMahon's excellent Plone Conference 2008 talk, visit http://plone.org/events/conferences/2008-washington-dc/agenda/securing-zope-and-plone-against-the-big-bad-internet/. Restricting TCP/IP access to localhost or LAN host One of the simplest things we can do to secure our system is to operate our Zope 2 instances only on the IP addresses that they are required to listen on. In most cases, it is 127.0.0.1 (or localhost, as it is commonly referred to) but it can also be a LAN host that is a private, non-routable IP address used only on your local area network (LAN). In this article, we will not cover LAN hosts. However, we suggest you consider using them when you need to access instances from another host on the LAN; otherwise, just use localhost. In the case of LAN hosts, once confgured, they will protect ports from being accessed by the outside world (that is Internet). However, it will allow them to be accessible from the LAN where you may want to confgure monitoring, for example via Munin , Zenoss (http://community.zenoss.org), and so on. What we will cover is how to use the localhost IP address. In 07-security-localhost.cfg, we have: [buildout]extends = 06-deployment-optimization-munin.cfg[instance1]http-address = 127.0.0.1:8081[instance2]http-address = 127.0.0.1:8082 You will notice we have re-configured the http-address parameter to include the entire HTTP address and not just the port number. You will also notice we have used the private, non-routable localhost address 127.0.0.1. Now run Buildout: $ bin/buildout -c 07-security-localhost.cfg Afterward, in parts/instance1/etc/zope.conf, you should see: ...<http-server> # valid keys are "address" and "force-connection-close" address 127.0.0.1:8081 # force-connection-close on # You can also use the WSGI interface between ZServer and ZPublisher: # use-wsgi on </http-server> This means that our instances will listen for connections only on 127.0.0.1; any attempt to connect from another host will fail. More about localhostFor more information about how the localhost really works, visit http://en.wikipedia.org/wiki/Localhost. For our purpose though, we can think of running the Plone site on localhost as "having a party that only your laptop or development workstation can join". Managing IP addresses and ports effectively As your production configuration grows, it may become more diffcult to manage a large number of IP addresses and ports. As such, it is often helpful to have them defned in their own part. In 07-security-ports.cfg, we have: [buildout]extends = 07-security-localhost.cfg[hosts]localhost = 127.0.0.1[ports]instance1 = 8081instance2 = 8082 Notice that we are not using these definitions for anything yet. But we can use them like this: ${hosts:localhost}:${ports:instance1}${hosts:localhost}:${ports:instance2} Effectively from now on, we have to change IP addresses and port numbers only in one place (assuming we change all static references such as 127.0.0.1:8080 to the new syntax). Configuring the Zope 2 effective user dynamically Another simple thing we can do to secure our system is to operate our Zope 2 instances with only those operating system users who have enough permission to execute the instances. In fact, Zope 2 will not run as root on UNIX-like systems. However, we frequently forget to do this. More importantly, sometimes we want to be more explicit with our configuration. This is where the effective-user parameter comes in handy. If no effective user is set, then Zope 2 will run as whoever executes the process. You could set the effective-user manually or you could use the gocept.recipe.env recipe (http://pypi.python.org/pypi/gocept.recipe.env) to set it. In the case of manual configuration, you may find it tedious to test your production configuration on systems that do not have the desired effective user (or you may not; this is mostly subjective). In the case of no configuration, you may find it annoying to be reminded that you cannot run Zope 2 as root when you get to production (or you may not; this is also subjective). In any event, we can formalize the configuration and automate the username selection process as follows. In 07-security-effective-user.cfg, we have: [buildout]extends = 07-security-ports.cfgparts += env[env]recipe = gocept.recipe.env[instance1]effective-user = ${env:USER}[instance2]effective-user = ${env:USER} Now run Buildout. $ bin/buildout -c 07-security-effective-user.cfg Afterward, in parts/instance1/etc/zope.conf you should see: ...effective-user aclark... This technique has several subtle, but important advantages over manual, or no configuration: The effective user is always set, so even if you try to start Zope 2 as root, it will run as the effective user The effective user is set to the user that runs the buildout, which means you can change the effective user easily The ${env:USER} variable can be used to configure user settings for additional services such as Pound, Varnish, and so on. Installing Cassandra to audit through the web (TTW) security If you ask anyone familiar with Plone about the permissions settings in the Security part of the Zope Management Interface, you are likely to get the following response: "DO NOT TOUCH!" That is because with so many possible permutations of settings, it is almost impossible to manage them all effectively by pointing and clicking. The next thing out of their mouth is likely to be: "USE WORKFLOW INSTEAD!" That is because Plone's workfow feature provides a much better way to effectively manage large amounts of permission changes. However, people do not always use workfow. They point and click away anyway, despite the warnings. You, however, have been warned. It is much better to manage permissions with workfow as compared to pointing and clicking on Permissions in the ZMI. Permissions and roles in the ZMI If you do not believe me, consider this. If you browse to http://localhost:8080/Plone and click on Site Setup | Zope Management Interface | Security, you will see almost two hundred permissions that look like the following (first ten): Next to each group of 10 permissions are checkboxes that correspond to the possiblerole assignments: Hopefully, enough has been said. The point again is two-fold: The ZMI opens the gateway to enormous complexity (categorically, not just with roles and permissions) In the case of roles and permissions, managing this complexity is best left to workfow (in which case, role-to-permission mappings are configured by the state) Roles and groups Similarly, the same Plone folks will often remind you to assign roles to groups and not users, and put users in groups to enable them to perform various tasks. They might say: "DO NOT ASSIGN ROLES TO INDIVIDUAL USERS!" This may be followed by: "ASSIGN THEM TO GROUPS INSTEAD!" Why? This is because to manage intricacies such as which user can perform which tasks and where, you are better off using the right tool for the job, that is adding users to groups with proper role assignments. Unfortunately, end users are still able to assign roles to individual users if they really want to via the Sharing tab or Local roles form in the ZMI. So, it is the site manager's responsibility to make sure they do not, to avoid having a site littered with individual role assignments.
Read more
  • 0
  • 0
  • 1193
article-image-yui-28-menus
Packt
26 Jul 2010
9 min read
Save for later

YUI 2.8: Menus

Packt
26 Jul 2010
9 min read
(For more resources on YUI, see here.) Common navigation structures All but the most limited of websites must have a mechanism by which visitors can navigate around the pages of the site from the home page. In order to meet accessibility guidelines, several methods of navigation will usually be available, including at least a navigation menu and a site map. There have been many different implementation styles that have been popular over the years. Before anyone really worried about accessibility or standards compliance, a common way of designing a navigation menu was to use a series of images that linked to other pages of the site, and there was also the popular frame-based navigation structure. While these methods saved the designer a lot of time, effort, and any real skill, they led to hugely increased page load times and a legacy of bad coding practice. Thankfully, those days have long since passed, and with the continued development of CSS, it's now possible to design an effective navigation structure based on semantic HTML and styled with CSS. Designing a navigation menu that is effective, robust, and presented effectively can still pose a challenge, and troubleshooting the compatibility of a menu between different browsers can be a very time-consuming process. This is where the YUI steps in. Instant menus—just add water (or a Menu Control) The Menu Control is used to add one of several different menus to your website, saving you the chore of adding this almost essential feature yourself. It's another control that takes a complex, difficult, or time-consuming task, and one which is an almost inherent requirement of any website, and packages it up into a convenient and easy-to-use module. The three different types of menu you can create are: A standard navigation menu An application-style menu bar A right-click context menu The navigation menu can be implemented as either a vertical or horizontal menu and generates a clean and attractive interface, which your visitors can use to navigate to different areas of your site. The navigation model of any site is key to whether using the site is easy and enjoyable; nothing turns off visitors more than a poorly designed or inconsistent navigation structure. Another type of menu that the Menu Control is able to create is an application-style menu bar, which stretches across the screen horizontally, building on the current trend in the online world to blur the distinction between the browser and the desktop. As well as taking care of navigation for you, it can also be used to add right-click context (pop-up) menus to any part of your web application, which again can give a web application a definite desktop feel to it. The Menu Control is very flexible and can be built from existing HTML markup using a clean and logical list structure, or it can be generated entirely through JavaScript and built at runtime. Each of the different menu types is also given a default appearance with the sam skin so there is very little that is required to generate the attractive and highly functional menus. We'll be looking at implementing each of the different types of menu ourselves in just a moment. Before we do this, let's take a quick look at the classes that go together to make the Menu Control. The Menu classes This component is made up of a small family of different types of menu. There is a range of different classes that work together to bring the functionality of the different types of menu to you. The three main classes behind the Menu family are: YAHOO.widget.Menu YAHOO.widget.ContextMenu YAHOO.widget.MenuBar Menu is a subclass of Overlay, part of the Container family, and the other two are subclasses of Menu. Just as each TabView is made of several Tabs, each kind of Menu has a different class for its items: YAHOO.widget.MenuItem YAHOO.widget.ContextMenuItem YAHOO.widget.MenuBarItem ContextMenuItem is simply an alias for MenuItem created just for the sake of symmetry. All types of menu items can have a Menu as a submenu; neither ContextMenu nor MenuBar can be nested in a menu item, they are only good at the outermost level. All the menus are coordinated by YAHOO.widget.MenuManager, which listens to events at the document body level and dispatches them to the corresponding menus or menu items using the technique of Event Delegation to the limit; after all, the document body is the furthest out an event can bubble. Like the other members of the Container family, the constructor for Menu and its subclasses take two arguments; first a reference to existing markup or, if built via code, the id we want the Menu to have once rendered. The second argument takes the configuration options, if any, and accepts any configuration attribute as would be expected. However, in Menu, it can also take a couple of properties: itemData and lazyLoad, while MenuItem can also take value. We will see what they can be used for shortly. Menus can be built from existing markup or from code or any combination of both. The required markup for a Menu might seem a little complicated at first but it is intended to work in older clients or for users without JavaScript enabled. This, we know, is called Progressive Enhancement and Menu supports it very well; the CSS style sheet for Menu works whether JavaScript is active or not and by using the correct class names the Menus will look just the same for all our visitors regardless of the capabilities of their browsers. The markup will usually consist of a series of unordered lists <ul>, each of their list items <li> containing an anchor element <a> that leads to the next non-JavaScript enhanced page and optionally followed by a further nested unordered list. Menus will also read <select> elements creating a MenuItem for each <option>. When building a Menu from code, we may create and add each individual MenuItem to the Menu or we may use the itemData configuration option we've just mentioned, which takes an object literal with the description of the whole Menu at once. This is particularly handy for ContextMenus as they hardly make any sense without JavaScript enabled. Just as with any container, Menus have to be rendered. ContextMenus are usually rendered into document.body, as they have no place in the normal flow of the page. If the menu structure is too complex and takes too long to render, the lazyLoad option tells the Menu to render just the first level of items, those that would be visible initially, postponing rendering the rest until needed. Menu subclasses The ContextMenu is a specialized version of the control that provides a menu hidden from view until the element that it is associated with (the trigger element) is clicked with the right mouse button (except in Opera on Windows and OS X which requires the left-click + Ctrl key combination). The trigger element is defined using the trigger configuration attribute; this is the only configuration attribute natively defined by the ContextMenu class, all others are inherited. The MenuBar is similar to the standard Menu, but is horizontal instead of vertical. It can behave like an application-style menu bar, where the top-level menu items must be clicked in order for them to expand, or it can behave more like a web menu where the menu items expand on a simple mouse over and have submenu indicators. This is controlled with the autosubmenudisplay Boolean configuration attribute. The MenuItem class Each menu type has a subclass representing the individual menu items that form choices within the menu. They will be created automatically when a Menu is built from existing markup or by setting the itemData configuration option to a menu description. You will only create individual MenuItems when extending the functionality of an existing menu. MenuItems have several interesting configuration attributes: checked: Shows a checkmark to the left of the label, useful for items that toggle in between two states. classname: Added to the existing if any further styling is required. It can read this from existing markup. disabled: This item cannot be selected and will be grayed out. When built from markup, it can read this attribute from an tag. keylistener: The key combination (Shift, Control, or Alt + character) that will trigger this item. It can be read from markup. onclick: The method to be called when this item is clicked. text: A string to be shown in the label. url, target: The destination page for this item when not handled via code. selected: The item shows highlighted. submenu: A nested instance of Menu, an object description of a nested Menu, or a reference to the markup that would produce it. value: A value associated with this item. MenuItem subclasses The two subclasses YAHOO.widget.ContextMenuItem and YAHOO.widget. MenuBarItem both extend the MenuItem class, providing a constructor and some basic properties and methods for programmatically working with individual ContextMenu or MenuBar menu items. As a matter of fact ConextMenuItem is simply an alias for MenuItem. MenuBarItem has different defaults than MenuItem to suit the different layout of the MenuBar. Creating a Basic Navigation Menu Let's put together a basic navigation menu. Our menu will be built from underlying HTML rather than from script. We'll be enhancing the example of the image portfolio by first providing a landing, home page that will welcome us. We'll later add a context menu to the image portfolio itself so that instead of adding an extra button (like Rate!) for each option, we'll handle them via menus. Once complete, our landing page should appear like this:
Read more
  • 0
  • 0
  • 1087

article-image-examining-themes-omelette-and-python
Packt
23 Jul 2010
3 min read
Save for later

Examining themes with Omelette and Python

Packt
23 Jul 2010
3 min read
Installing themes with Buildout For a lot of website projects, a theme downloaded from plone.org (http://plone.org/products) or the Python Package Index (http://pypi.python.org) is enough to launch a professional-looking site. If your project falls into this category, or if you just want to experiment, follow the steps in this chapter. Searching for themes on plone.org We will need to find a theme we like. We can do that by browsing to http://plone.org. Next, click on Downloads Add-on Product Releases | Themes|. You should see (result similar to): Click on a theme to view a screenshot and select one you like, for example beyondskins.ploneday.site2010, and add the package to your buildout.cfg file. Adding themes with Buildout In 03-appearance-wpd2010.cfg, we extend the last known working configuration file from Chapter 2, that is 02-site-basics-blog.cfg. It looks like this: [buildout]extends = 02-site-basics-blog.cfg[instance]eggs += beyondskins.ploneday.site2010zcml += beyondskins.ploneday.site2010 In addition to adding the package name to the eggs parameter, we must add it to the zcml parameter as well. Now stop Plone (with Ctrl + C or Ctrl +Z/Enter) and run: $ bin/buildout -c 03-appearance.cfgUpdating zope2.Updating fake eggsUpdating instance.Getting distribution for 'beyondskins.ploneday.site2010'.Got beyondskins.ploneday.site2010 1.0.3. Now start Plone: $ bin/instance fg Installing themes in Plone Browse to http://localhost:8080/Plone. Now, click on Site Setup Add/Remove Products| and you should see: Check the box next to WorldPloneDay: Theme for 2010 edition 1.0.3 and click on Install. Now browse to http://localhost:8080/Plone and you should see: This theme is the courtesy of Simples Consultoria (http://www.simplesconsultoria.com.br/). Thank you! You can examine the anonymous view (what everyone else sees) by loading http://127.0.0.1:8080/Plone in your browser (that is. by using the IP address instead of the hostname). You can also load either of these URLs (http://127.0.0.1:8080/Plone or http://localhost:8080/Plone) from another web browser (besides the one you are currently using) to see the anonymous view (for example, Safari or Internet Explorer, instead of Firefox). To display the blog entry to the public, we have transitioned the other objects in the site root to the private state. Examining themes with Omelette and Python Simply put, a theme is a collection of templates, images, CSS, JavaScript, and other files (such as Python scripts) that control the appearance of your site. Typically these files are packaged into a Python package, installed in your Plone site with the help of Buildout, and installed in Plone via the Add/Remove Products configlet in Site Setup. Once installed, certain elements of the theme can be edited through the Web using the ZMI. However, these changes only exist in the site's database. Currently there is no easy way to transfer changes made through the Web from the database to the filesystem; so there is a trade-off for performing such customizations through the Web. If you lose your database, you lose your customizations. Depending on your goals, it may not be entirely undesirable to store customizations in your database. But nowadays, most folks choose to separate their site's logical elements (for example themes, add-on functionality, and so on) from their site's content (that is data). Creating a filesystem theme and resisting the urge to customize it through the Web accomplishes this goal. Otherwise, if you are going to customize your theme through the Web, consider these changes volatile, and subject to loss.
Read more
  • 0
  • 0
  • 1293

article-image-removing-unnecessary-jquery-loads
Packt
23 Jul 2010
7 min read
Save for later

Removing Unnecessary jQuery Loads

Packt
23 Jul 2010
7 min read
The first thing that you should always do before making any changes is take a backup of your site. You can do this manually or by using an extension like Akeeba backup, which can be found in the JED or at the following link: http://extensions.joomla.org/extensions/access-a-security/backup/1606 Having a backup copy is essential to restore a working copy of our site if a mistake is made. Also, you may be wondering whether, later, if you install a newer version of the extension, you may lose all of the changes made. This can happen; therefore, we have made these modifications after we have finished installing the extensions we need. But don't worry too much about that. You won't be installing a newer version of an extension every day. Mostly, you will install a newer version of the extension if bugs have been found or if the version introduces some features you want. Otherwise, if the site is working nicely and there are no bugs or newer features, we don't need to update these extensions. Anyway, the most important thing to remember is to backup. Always keep a backup of your work. As mentioned earlier, each one of the extensions that we are using is loading its own jQuery library, and thus makes our site needlessly load the library many times. This makes our site download more files than are really necessary. Just take a look at the source code of your site. In the head section we can see the script tags that are loading the required libraries: <script type="text/javascript" src="/plugins/system/cdscriptegrator/libraries/jquery /js/jsloader.php?files[]=jquery-latest.packed.js&amp;files[]= jquery-noconflict.js"></script> <script type="text/javascript" src="/plugins/system/cdscriptegrator/libraries/jquery/ js/ui/jsloader.php?file=ui.core"></script> <script type="text/javascript" src="/plugins/system/scjquery/js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="/plugins/system/scjquery/js/jquery.no.conflict.js"></script> <script type="text/javascript" src="/plugins/system/scjquery/js/ jquery-ui-1.7.2.custom.min.js"></script> <script type="text/javascript" src="/media/system/js/mootools.js"></script> <script type="text/javascript" src="/media/system/js/caption.js"></script> <script type="text/javascript" src="/plugins/content/ppgallery/res/jquery.js" charset="utf-8"></script> <script type="text/javascript" src="/plugins/content/ppgallery/res/jquery.prettyPhoto.js" charset="utf-8"></script> <script type="text/javascript" src="http://wayofthewebninja.com/modules/ mod_ninja_shadowbox/ninja_shadowbox/js/adapter/ shadowbox-jquery.js"></script> <script type="text/javascript" src="http://wayofthewebninja.com/modules/ mod_ninja_shadowbox/ninja_shadowbox/js/shadowbox.js"></script> <script type="text/javascript" src="/modules/mod_ajaxsearch/js/script.js"></script> <script type="text/javascript" src="http://wayofthewebninja.com/modules/ mod_superfishmenu/tmpl/js/jquery.event.hover.js"></script> <script type="text/javascript" src="http://wayofthewebninja.com/modules/ mod_superfishmenu/tmpl/js/superfish.js"></script> <script type="text/javascript" src="http://wayofthewebninja.com/modules/ mod_c7dialogmod/jquery/ui.core.js"></script> <script type="text/javascript" src="http://wayofthewebninja.com/modules/ mod_c7dialogmod/jquery/ui.dialog.js"></script> <script type="text/javascript" src="http://wayofthewebninja.com/modules/ mod_c7dialogmod/jquery/ui.draggable.js"></script> <script type="text/javascript" src="http://wayofthewebninja.com/modules/ mod_c7dialogmod/jquery/ui.resizable.js"></script> Here we can see that lots of JavaScript files are being loaded, and some of them are repeated. Surely, that doesn't make our site load faster. Let's try to improve this as much as we can. We will use the SC jQuery plugin in order to load the jQuery library. With the help of a variable created by this library we can also determine if the jQuery library needs to be loaded or not. How is this done? If we open the plugins/system/scjquery.php file, at the very bottom of the file you can see the following code: $app->set( 'jquery', true ); In newer versions of the plugin this line of code seems to have been removed. However we can modify the plugins/system/scjquery.php file and add that line to it, at the very bottom, just like this: ... $app->set( ‘jquery’, true ); $doc->setHeadData($headData); return true; } } This way we will be able to use the techniques we are about to show.   This will set a variable jquery with the value true. Our next step is to use this variable to our benefit, just like we did in the ajaxSearch module. Open the modules/mod_ajaxsearch/mod_ajaxsearch.php file. We modified this file and it now appears as follows: $app =& JFactory::getApplication(); if( !$app->get('jquery') ){ $document->addscript(JURI::root(true).'modules'.DS. 'mod_ajaxsearch'.DS.'js'.DS.'jquery-1.3.2.min.js'); } First we need to get an instance of the global application object. We will then use the get method to try and read the 'jquery' variable. If this variable doesn't exist, it would mean that the SC jQuery plugin has not been loaded, and thus the jQuery library won't be present. If this happens, we will let the module load its own copy of the library. This helps us in reducing the number of times the library has been loaded. Now we are going to look into the other extensions that we used, seeing how we can solve each situation. Code highlight Remember the Core Design Chili Code plugin extension? We used it to reformat some code, as we can see in the next image: This plugin required the jQuery library, but as the plugin itself doesn't have the library included, another plugin from the same developers was needed—the Core Design Scriptegrator plugin. You can check it in Extensions | Plugin Manager: This plugins works much like the SC jQuery plugin, but for the extensions of the Core Design Chili Code plugin developers. This plugin loads the jQuery library, and some others that we don't need, in order for the other extensions to use it. As we are using the SC jQuery plugin, we can disable the Scriptegrator plugin: But hey, then the Core Design Chili Code plugin stops working. Why? We have said that the Chili Code plugin needs the jQuery library, but we are using the SC jQuery plugin to provide it. At this point we need to check the Chili Code plugin source code, so just open plugins/content/cdchilicode.php. Here we can see the following piece of code: // define language if (!defined('_JSCRIPTEGRATOR')) { Error::raiseNotice('', JText::_('CHILICODE_ENABLE_SCRIPTEGRATOR')); return; } // require Scriptegrator version 1.3.4 or higher $version = '1.3.4'; if (!JScriptegrator::versionRequire($version)) { JError::raiseNotice('', JText::sprintf('CHILICODE_SCRIPTEGRATOR_REQUIREVERSION', $version)); return; } if (!JScriptegrator::checkLibrary('jquery', 'site')) { JError::raiseNotice('', JText::_('CHILICODE_MISSING_JQUERY')); return; } What does all this code do? It checks for the Core Design Scriptegrator plugin. If it doesn't find any evidence of the plugin, it raises some errors and returns. We know that jQuery will be loaded. So we can comment the code mentioned, and the Chili Code plugin will work again. That's it; we have just reduced one jQuery library load; ready for the next one?
Read more
  • 0
  • 0
  • 1702
article-image-creating-theme-package-zopeskel
Packt
23 Jul 2010
4 min read
Save for later

Creating a theme package with ZopeSkel

Packt
23 Jul 2010
4 min read
(Read more interesting articles on Plone here.) Download code from here Creating a theme package with ZopeSkel Now that we have examined someone else's theme, let us try creating our own. Remember, we will not cover theme creation in depth; this is only a sample for site administrators (who may or may not be required to develop themes, in addition to managing their site). For more information about creating themes, Visit: http://plone.org/documentation/kb/how-to-create-a-plone-3-theme-product-on-thefilesystem. To create a theme, we will use the ZopeSkel tool (http://pypi.python.org/pypi/ZopeSkel) to generate some of the boilerplate code. ZopeSkel uses PasteScript (http://pypi.python.org/pypi/PasteScript) to facilitate package generation using a set of templates. Other options include: Write everything by hand from memory Copy the contents of another theme package Use another tool such as ArchGenXML to generate boilerplate code (http://plone.org/products/archgenxml) Adding ZopeSkel to a buildout Now let's add ZopeSkel to our buildout. In 03-appearance-zopeskel.cfg, we have this: [buildout] extends = 03-appearance-zopepy.cfg parts += zopeskel [zopeskel] recipe = zc.recipe.egg dependent-scripts = true We extend the previous working configuration file, and add a new section called zopeskel. This section uses the zc.recipe.egg recipe (http://pypi.python.org/pypi/zc.recipe.egg) to download ZopeSkel from the Python Package Index (zc.recipe.egg will search the Python Package Index for packages that match the section name zopeskel). We set dependent-scripts to true, to tell Buildout to generate Python scripts for ZopeSkel's dependencies such as PasteScript, which includes the paster script. Now stop Plone (with Ctrl + C or Ctrl + Z/Enter) and run Buildout: $ bin/buildout -c 03-appearance-zopeskel.cfg You should see: $ bin/buildout -c 03-appearance-zopeskel.cfg Uninstalling plonesite. Updating zope2. Updating fake eggs Updating instance. Installing plonesite. … Updating zopepy. Installing zopeskel. Getting distribution for 'zopeskel'. Got ZopeSkel 2.16. Getting distribution for 'Cheetah>1.0,<=2.2.1'. … Got Cheetah 2.2.1. Getting distribution for 'PasteScript'. Got PasteScript 1.7.3. Getting distribution for 'PasteDeploy'. … Got PasteDeploy 1.3.3. Getting distribution for 'Paste>=1.3'. … Got Paste 1.7.3.1. Generated script '/Users/aclark/Developer/plone-site-admin/ buildout/bin/ zopeskel'. Generated script '/Users/aclark/Developer/plone-site-admin/ buildout/bin/ paster'. Generated script '/Users/aclark/Developer/plone-site-admin/ buildout/bin/ easy_install'. Generated script '/Users/aclark/Developer/plone-site-admin/ buildout/bin/ easy_install-2.4'. You will notice that in addition to bin/zopeskel, Buildout also installed the "dependent scripts" bin/paster and bin/easy_install (the latter of which we do not really need in this case). Running ZopeSkel Now try running ZopeSkel with the command: $ bin/zopeskel You should see: Usage: zopeskel <template> <output-name> [var1=value] ... [varN=value] zopeskel --help Full help zopeskel --list List template verbosely, with details zopeskel --make-config-file Output .zopeskel prefs file ... This tells us we need to pick a template and output-name. ZopeSkel goes on to list the available templates. They are: archetype: A Plone project that uses Archetypes content types kss_plugin: A project for a KSS plugin plone: A project for Plone products plone2_theme: A theme for Plone 2.1 plone3_portlet: A Plone 3 portlet plone_app: A project for Plone products with a nested namespace plone_pas: A project for a Plone PAS plugin plone2.5_theme: A theme for Plone 2.5 plone3_theme: A theme for Plone 3 plone2.5_buildout: A buildout for Plone 2.5 projects plone3_buildout: A buildout for Plone 3 installation plone_hosting: Plone hosting: buildout with ZEO and Plone recipe: A recipe project for zc.buildout silva_buildout: A buildout for Silva projects basic_namespace: A basic Python project with a namespace package nested_namespace: A basic Python project with a nested basic_zope: A Zope project<
Read more
  • 0
  • 0
  • 1391

article-image-customizing-prestashop-theme-part-2
Packt
22 Jul 2010
13 min read
Save for later

Customizing PrestaShop Theme Part 2

Packt
22 Jul 2010
13 min read
(For more resources on PrestaShop 1.3, see here.) Let's move on with our next step. Of course, exploring every tab in the back office would be advantageous, but we will specifically touch only those points that will affect your theming process. We will now look at how we can modify the following: Logo Top of page Adding FEATURED PRODUCTS block Footer Title Placing the other modules useful for your store on other section of your pages. Before going further, I would like to emphasize two important points. They are: Always work on a copy of your default theme: If you have not copied the default theme file, I would advise that when you start your development work, you copy the default theme file so that you have a backup or a comparison to work with. We will be working on the copy of the default theme, as in some cases, we will still change a few lines of codes to modify the theme. This means that if you ever make a huge blunder, you will at least have the original to start with again. If the worst ever happens, you can always upload the original file again to overwrite your errors, but that will be a big waste of time. Keep a quick reference list of any modifications made to any file: It may sound a bit tedious, but you will find this advice useful to heed. There are a few ways of making modifications to your theme, sometimes through modification of your other files (which are not in the theme folder). You may copy the file and put it into the theme folder to make the changes, or it is also possible to merely modify them by overwriting the file in its location. Whichever way you chose, when you need to modify files which are not in your custom theme folder, you should make a quick note of what changes you have made and where have you made them. Why? Because when there is a new version of PrestaShop, you will need to upgrade your PrestaShop site, thus the modifications you have made will be lost. The modifications in the theme folders will remain even if you update the version of your PrestaShop site. By keeping a list of the modifications you've made, it will be much easier to track back to where to re-apply them after you have upgraded your PrestaShop installation. Never procrastinate on making this quick list because you will always find that it is a waste of time to find and trace those changes later; even just six months down the road. Copying the default theme file When you download PrestaShop, by default, you will have a copy of the PrestaShop theme folder. Go to the PrestaShop_1.3.1/themes/PrestaShop folder. Copy this entire folder and save it on your computer. You may rename the theme accordingly, for example, theme1. Compress this into a ZIP file. Upload the renamed folder into the themes directory on your hosting through your cPanel or FTP. You will now have two themes in your /themes folder which are PrestaShop and theme1. You can now log in to your PrestaShop Back Office | Preferences | Appearance and switch to your theme1 that you just installed and click on the Save button. On this page, you may also control what logo, favicon, and the navigation pipes you want to use throughout your website. Now, let's start with the modification of these theme elements to complete the look of your new theme. Logo A logo is an important element of a company's or store's image, and it can contribute to the brand's marketing success. Therefore, getting a good quality logo is fundamental for the business. Getting a unique and attractive logo design can be daunting, especially for those who are not born with a flair for design. However, fortunately, there are various resources that you can use to get ideas or even create a very professional looking logo that you can use in your new online store. Some online resources for logo designs can be found at: http://www.logomaker.com—This is an online resource that allows you to freely create a logo, but you have to pay to download your new creation, which basically uses their online inputs. Quite attractive and interesting looking logos can be found and designed here. http://cooltext.com—This one describes itself as A free graphics generator for web pages and anywhere else you need an impressive logo without a lot of design work. It allows you to choose the image you would like through a few simple steps. You only need to enter the words or company name using a form and you'll have your own custom image created on the fly. The logo you designed is downloadable for free. http://www.simwebsol.com/ImageTool/Default.aspx—This is a Web 2.0 logo generator. Free to use and download. It requires you to fill in a few fields and generates the image file quite easily. However, the background is limited to RGB flat choices and you only have 23 images that can be chosen from to insert. http://www.onlinelogomaker.com/ - A full featured free online logo design tool with a clean and easy interface and thousands of logo templates Another element, which is quite important here, is the favicon. The Favicon is the little icon representing the website you are visiting which gets displayed in the address bar of every browser. Usually, the favicon and the logo are the same thing, except for their sizes and the formats. They are not necessarily the same though. You may find some online resources that you can use to generate a favicon for the store. Make sure you have prepared the favicon icon before you try to replace the current favicon. If you are unsure of how to go about making a favicon, you may generate it online (using,http://www.favicon.cc/ or http://www.freefavicon.com/). Save the file on your hard drive and then upload it to your PrestaShop store. Uploading it is shown in the next section. Time for action—Replacing the default logo and favicon on your site The logo and the favicon can be replaced through Back Office | Preferences | Appearance, as shown in the following screenshot:     Browse the file you want to use from your computer. Upload the files and click on the Save button. You need to refresh your back office browser before you replace the logo and the new favicon.ico file. You also need to clean up your browser's cache and refresh the browser to see the favicon in the frontend of the website.     Upon saving and refreshing your browser, the updated images will be displayed. What just happened? In this simple exercise, you have just uploaded the logo that you had created, and PrestaShop has, by default, placed it in the correct directory in your new theme1 directory through the back office panel. If you did not choose the new theme, for example, theme1 in Preferences | Appearance under Themes, the logo you upload will go to the wrong directory. The Center Editorial Block The Center Editorial Block is where you see the main image at the center column, as we indicated previously in the front office. This is an important block, as this is where your visitors first arrive when they visit your store. It gives a first impression to your site visitor, and therefore, you need to consider what to include in it very carefully. Time for action—Modifying the Center Editorial block The Centre Editorial Block can be modified through Back Office | Modules | Tools | Home text editor. In this section, you can also edit the Centre Block image, which is referred to as Homepage's logo, and this title can be quite misleading as it may be confused with the actual logo. However, we have covered this matter in the previous article and did a mapping of each field here to the front office page of the store. You only need to upload the image you want to replace it with and continue with editing the Homepage logo link, which is the link for this image (Homepage's logo). You may just leave it set to your current website address if you want (for example, www.mydomainname.com). You can also leave it blank if you don't want the image to be a link. Furthermore, you will see Homepage logo subheading, which is the small letters you see on the default theme page that appear under the image. Let's replace the Homepage's logo image, Homepage logo link, and a new Homepage logo subheading: Click on the Update the editor button. Review your changes in your front office browser. You will need to refresh the page once to see the effect. It is possible to work with different image sizes, but the width of the image will "disturb" your column settings. If you are not going to make any unnecessary changes, then it is best to use images of the safe maximum width for the center column which is 530 pixels. If you exceed this width it will push your right column outside the standard browser view. Now let's have a look at what you have achieved so far. What just happened? You have modified your Center Editorial Block by inserting a new Homepage's logo image, Homepage logo link, and a new Homepage logo subheading. Top of pages block We will look at the header section of the page. The default layout comprises the following in the header section: Currency block (links to the available currencies used on the site). Languages block (links to the available language translation of the pages interface). Permanent link block: Contact (icon that links to the contact form page) Sitemap (icon that links to the sitemap page) Bookmark (icon that helps you bookmark a particular page on the site) Search block User links block: Your Account (icon that links to the login page or registration page). When logged in, it links to the account page that lists everything the customer can do with their account. It is only when the viewer is logged out that it links to the authentication page Cart (icon that links to the shopping cart summary page ) Welcome, Log in (links to the login page or registration page)     Time for action—Modifying the Top of pages To get these elements back on the pages, you will need to install and enable the relevant modules. These simple steps will need little modifications unless you want to add a new currency and a new language. Let's enable these modules through these simple steps: Currency block—go to Modules | scroll down to Blocks | Currency block. Languages block—go to Modules | scroll down to Blocks | Language block. Search block—go to Modules | scroll down to Blocks | Quick Search block. Permanent link block—go to Modules | scroll down to Blocks | Permanent links block. By default, these modules tend to appear on the pages in the order you installed and enabled them. The first one will appear the leftmost while the last one will be the rightmost. You can shift the arrangement by installing them according to what you want to appear on the leftmost or the rightmost sides. Notice that the Permanent link block is on the right as we enabled it last. There is an easier way to do this as well, which we will cover in the next section. You can modify this by working on the position of the modules within the Top of pages hooks. There are two similar hooks, which can be quite confusing, that is, the Top of pages and Header. The blocks are positioned or "transplanted" in a Top of pages hook and not Header of pages. The Welcome, Log in, Cart, and the User login links can be enabled through Back Office | Modules | Blocks | User info block. Upon installing and enabling the module, you will have the Welcome, Log in, Your Account, and Cart link displayed on your front office. By default, all those are automatically hooked to the Top of pages once they are enabled. If it is not, you can have it hooked through transplanting the module to the hook, as shown in the next screenshot. This can be done by following these simple steps: Go to Back Office | Modules | Position | Transplant a module.     Choose the Module you want to transplant from the drop-down menu. Choose the hook from Hook into, the one you want the Module to go into. Click on the Save button. The arrangement of the blocks can be done by moving them around within the hooks, which we will see next. Go to Modules | Positions. There you can arrange the position of the modules within the hooks by dragging each of them to the required position. As you can see, there are the two similar hooks which may be confusing, namely, the Header of pages and the Top of pages. Compare it with what you have at the front office in the next screenshot.   The Quick Search block does not appear despite it being hooked at the Header of pages. The other blocks which are hooked to the Top of pages are displayed in the front office. The same thing with the User info block; you only see the one which is hooked to the Top of pages and not the one in the Header of pages. The Top of pages hook is used to display a module at the top of the page. The Header of pages hook is used to put code in the <head> tag of the website. If you want to move a module or delete it from the top of the page, you should use the Top of pages hook, not the Header of pages hook. Modules that are in the Header of pages hook should not be removed, since they are required for the module to function correctly. For example, if you remove the Quick search block from the Header of pages hook, the search autocomplete will not work, since the code for it is missing. The resulting JavaScript error will also cause other problems on the website such as the Categories block not displaying any categories. To move the modules to the left or right, you need to move them up within the hook. The lower it is within the hook, the more to the right the module will appear, whereas the upper within the hook will be displayed on the left. For example, the Currency block is first in the list, and it is displayed on the left of the Top of pages section on the webpage. What just happened? You just learnt the differences between the hooks Top of pages and Header of pages in PrestaShop. You also get to modify the blocks you want to use on the top of the page and how to move them around within the hook.
Read more
  • 0
  • 0
  • 2846