THE COMPLETE CMSB COOKBOOK
CLICK TO VIEW THE RECIPES AS A "TABLE OF CONTENTS"
We now have 559 recipes!
Section 1 (Recipes 001 - 100) - Download PDFSection 2 (Recipes 101 - 200) - Download PDFSection 3 (Recipes 201 - 300) - Download PDFSection 4 (Recipes 301 - 400) - Download PDFSection 5 (Recipes 401 - 500) - Download PDFSection 6 (Recipes 501 - 559) - Download PDF
LAST UPDATE -
Aug 8th, 2023
Click To View The Recipe
Click Here To Skip Down To The Complete Cookbook
INTRODUCTION
If you’re reading this then you have probably started to create your first web sites with CMS Builder, either from scratch or as conversions of existing web sites. You’ve also probably started to research the CMSB forum and have found, like I did when I first started designing with CMSB, that this PHP stuff is like learning a new language.
Although I was pretty proficient with HTML coding and using Dreamweaver, when I started applying this new approach, it was clear that the devil is in the details and that I had a lot to learn about those details.
I started documenting everything that I learned, either from much trial and many errors, from the excellent Interactive Tools users forum, or from Dave and others on the Interactive Tools staff, who freely gave of their time to help us newbees solve what seemed to be the same problems over and over again.
This cookbook is designed to answer many of the questions that you’ll have as you try to understand this powerful and versatile new web design paradigm.
The first chapter, “Where to Begin” describes the basic philosophy of how CMS Builder works and describes some basic approaches to understanding some of the concepts required to make your design work correctly.
As you continue to develop pages, designing with content management in mind will become easier, the new concepts will become clearer, and you’ll discover, as I did, that CMS Builder is the best professional content management system in the marketplace.
THE FINE PRINT
Since, in most cases the examples in the cookbook came from a number of designers, you’ll have to replace paths, table names, field names and other information to match your particular application.
We don’t guarantee that the recipes provided in our cookbook will be appropriate for your application exactly as written, but they should give you a good idea of how to approach and accomplish a given task.
Although we’ve made an effort to correct mistakes and ambiguities in the examples, there are probably some that got away from us.
Also, as CMS Builder has developed over time, some menus and functions have been modified. Because of this, some of the details in the examples may reference the placement or menu entries in previous versions.
If you find any mistakes or ambiguities we’d appreciate it if you’d drop us an e-mail about them, including your corrections, to: corrections@thecmsbcookbook.com We’ll incorporate your suggestions into subsequent editions of the cookbook and post them on our web site.
The CMSB Cookbook is a compilation of some of the hottest ideas from web designers around the world who have discovered the power and flexibility of CMS Builder and were willing to share their discoveries with the rest of the CMSB user community.
While developing your applications, you’ll be learning new tricks and having some “Ah Ha” moments. It’s important that you document those discoveries so that they’ll be available to you the next time they’re needed. We hope that you’ll share your discoveries with us so that we can share them with other CMSBers by sending them to: share@thecmsbcookbook.com
|
WHAT IS CMS BUILDER AND HOW DOES IT WORK?
CMS Builder is a PHP based Content Management System (CMS) that lets non-technical users update the content on their website using a simple browser based interface, without learning any HTML or programming skills.
From the web designers perspective CMS Builder allows us to design web pages that rely on an on-line database to store their content. It also facilitates the retrieval of that information from database records and the insertion of that information into specific locations on a web page.
From the end user’s perspective, CMS Builder facilitates the modification and addition of content to both the database record and web pages by means of a simple, browser based interface. Modifications to existing pages can be made from any computer that has internet access. Information is modified using any web browser (Internet Explorer, FireFox, Safari, etc.), and no special software is required on the home computer.
WHAT'S PHP? PHP, which is an acronym for Hypertext PreProcessor, is a general-purpose scripting language that’s especially suited for web development.
CMSB uses PHP to both populate pages and to access a MySQL database and manipulate the acquired data to render dynamic, client controlled web pages.
A major strength of PHP is that it’s server side scripting, so the end user has no access to the actual PHP code. It can be embedded into HTML coding and interpreted by the web server, which renders the output as HTML.
PHP was originally created sometime in 1994 or 1995 by the Danish/Greenlandic programmer Rasmus Lerdorf, but has since been improved and updated by a group called the PHP group.
As your skills and your curiosity grow, you can learn a lot more about PHP at:
http://www.php.net
HOW DO I IMPLEMENT CMS BUILDER? Once you’ve installed CMS Builder following the really simple instructions on the Interactive Tools web site, you’ll probably want to dive right in and create your first web site. I would urge you to wait until you’ve watched the videos on the Interactive Tools website, and until you’ve read at least the introductory chapter of this cookbook. I’d also suggest that you follow the creation of the 2 sample pages later in this chapter.
In order to use CMS Builder effectively, and to minimize the frustration that’s common to all first timers, there are a few new concepts that you’ll have to get your head around.
TYPES OF DATA BASE INTERFACES USED CMS Builder uses 2 basic types of database interfaces to manage web pages.
1) A single record interface, for information that may be changed but only exist in one form at a time. Examples of this type of information would be an “about me” page, “contact information” and the directions to a specific location.
2) A multi record interface for information about a series of items that have the same basic informational structure, (name, address, description). Examples of this type of information would be a list of images, a calendar of events, and a list of products.
The multi record interface manages 2 types of pages. "List" pages that show a listing of either image thumbnails, event titles and dates, or products, and "details" pages that shows detailed information about a specific item in the list.
SECTION EDITORS In CMSB, the database record interface that you’ll create is called a section editor. A section editor contains the menu of fields that will be used to organize the content of your web page. It is where you will set up certain restrictions regarding the type of data that can be entered (only certain file types, certain characters), how much information can be entered (300 characters, 12 images), how that information is processed and displayed (show or hide the record on a certain date), and in some cases who is allowed to enter the information (the administrator only, or the original author).
You can create either Multi Record editors or Single Record editors depending on the type of data they are to manage, and create a menu structure that contains the types of fields that suite your application.
You can also choose from a set of preset menu structures, and even use copies of your own editors to create additional editors for use on the same or different sites.
FIELDS Once you’ve created either a basic single record or multi record section editor, you can add a number of types of fields to that editor’s menu structure to facilitate the entry of various types of information.
The simplest of these fields is a “text” field, which is a one line field that can only accept text as it’s input.
The next type is the “text box”. A text box is similar to a text field, but it can accept multi line text entry.
If you need a greater degree of flexibility in entering their data, you can create “WYSIWYG” fields that present a WYSIWYG editor interface, either allowing uploads or not, your choice.
There are “list” fields that can take their input from either single or multiple entry pull down lists or radio buttons.
There are “checkbox” fields that output different values depending on whether they’re checked or not.
There are “upload” fields that allow users to upload documents, images and even flash, video and audio files. Upload fields have a great deal of flexibility attached to them and are among the most complex.
There are also some “special” fields that can let you show or hide a record from a web page, enter a date and sort or control your records using those dates, decide when to publish a record to a website or when to remove or un-publish that record, and other special functions that help to customize your implementation.
Once you understand these few basic tools that are in your arsenal, you can begin to implement CMSB into your web design.
QUALIFIERS PHP and MySQL offer a full range of qualifiers and search criteria including if, then, else, and, not, equals, where, limit, and others that can add complex functionality to your pages.
GENERATING THE PHP CODE REQUIRED FOR YOUR WEB PAGES After you've created your section editors and included various fields to enter your data you’ll need build web pages to display your data. The good news is that the basic code to accomplish this can be automatically generated by the code generator that is built in to CMS Builder.
|
SOME TERMS YOU'LL NEED TO KNOW (AND SOME THAT YOU KNOW ALREADY)
CSS - This Acronym stand for Cascading Style Sheets. Styles are a series of instruction groups that specify how specific items should appear on a Web page.
“External” Style sheets are separate files that contain the styling information that determines what text, links, font sizes, borders, and other elements will look like across an entire web site.
Using these predefined styles is an easy way to standardize the “look” of a web site.
If you want to change the look of a particular type of item, say how links are displayed on your web pages, that styling information can be changed in one external style sheet and the item's appearance will automatically be changed on the entire web site.
DATABASE - This is a specially structured file that is used to store collections of information. CMS Builder stores information in a database that is located on your on-line server. Any type of information can be stored in a database. Images and other uploaded documents are not stored in the on-line database, however the information on where to find these documents is stored in the database records.
PUBLISH - When you modify the information in your database records using the CMS Builder interface, you’re working on an editing screen (called a section editor) that’s located on the computer you’re working on. When you save that information, you’re saving your changes to a record in your on-line database.
CMS Builder automatically publishes the information stored in the database to the location you’ve specified in the design of your web page.
RECORD - A database can store a great deal of information in a structured format. Each structured group of information is called a record. In some situations, the information in these records can be modified. When you add or revise information using the CMS Builder interface, that information is stored in a database record.
SECTION EDITORS - The interfaces that you create to manage the information in the various records in your database.
FIELD - This refers to a specific information entry area in a database record. It can be a single line (text field), or a multi-line field (text box), a date field, a check box, or other special information entry area types.
MENU - The set of fields within a Section Editor
SERVER - This refers to a computer at the company that supplies your web site hosting services that is always connected to the internet via a high capacity, high speed connection. When users log on to a web page from their home computer, the server “serves” or allows the home computer to download that web page, as well as any associated images and other files that are stored there.
For even more definitions, explore the Glossary on the Interactive Tools web site at: http://www.interactivetools.com/docs/cmsbuilder/glossary.html
|
CMSB SECURITY AND ACCESS CONTROL
Updating privileges for each Section Editor are controlled and protected by an unlimited series of user names and passwords.
Access to specific editors can be assigned to specific users with varying levels of permissions. (Manager, Administrator, or Writer (Author)) Only those pages and content areas that are associated with a particular user name and password combination are accessible to be updated by that user.
Access rights can be changed or reassigned by the administrator at any time.
Another concern is that of hackers and your CMSB website.
The discussion seems to center around 2 areas. Passwords and File Permissions.
Dave Edis of Interactive Tools weighed in with these thoughts.
Our site is constantly being scanned for vulnerable scripts. It adds thousands of lines to our 404 log.
My advice would be to not use dictionary words for passwords (add a number and special character !@# for added security).
I suggested it might not be a bad idea to change passwords on both FTP access and CMSB access on a regular basis.
On the topic of file permissions, while a file permission of 777 may be OK for installation, it’s not really a secure enough permission to remain on your web site unattended. Many feel that a 755 permission is more secure.
WILL CMS BUILDER WORK WITH THE 755 PERMISSION
On that topic, Dave Edis, Senior programmer at Interactive tools had this to say:
Basically, if you (can) change permissions on /data/settings.dat.php and then you can update: Admin > General > Program Name, it means everything works.
So lower away, but don’t forget to check to make sure that you won’t have issues later on.
|
WHAT’S THE BEST WAY TO BEGIN USING CMSB?
The easiest way to begin using CMS Builder is to design your page using standard HTML and CSS first. Then list the areas that you’d like to allow CMSB to control, and those areas that you want hard coded into your design.
Once that’s done, you should look for similarities in the design. (A list of identical entries that all have a title, a description and an image associated with them, etc.)
HINT: If you know that you are going to show many items with a similar structure, you should enter at least enough of them to show the basic layout of your page, like the table structure, etc.
Once that’s done, you can start to think about the format that you can use to store and retrieve that information. Here are 2 examples that will illustrate the process. We’ll be designing an “About Us” page using a single record section editor and then create an “Events” page using a multi record section editor.
We suggest that you create your own pages for this exercise from scratch, using your favorite text or html editor.
If you download our sample pages from:
http://www.thecmsbcookbook.com/downloads/firstpages.zip
you’ll be able to troubleshoot the process by comparing our results to yours.
|
DESIGNING YOUR FIRST CMSB PAGES
|
CREATING AN "ABOUT US" PAGE WITH A SINGLE RECORD SECTION EDITOR - Jun 7th, 2015
AN “ABOUT US” PAGE This “About Us” page get it’s content through a single record section editor interface.
Our “About Us” page contains the company name, an address, a phone number, and a few paragraphs describing the company.
CREATING THE “ABOUT US” HTML PAGE The first step is to design the “About Us” page using HTML and to make sure that it looks the way you want it to.
Then you’d make a list of all the areas (fields) that you want the user to be able to modify. In our example we’ll want the user to be able to modify the company’s name, their current address, phone number, and a company description.
THE SINGLE RECORD SECTION EDITOR
Since this page will contain only one set of information, it uses a single record section editor.
Log on to your CMS Builder interface as administrator and click on the admin tab on the menu. Then click on the section editors tab and again on the “Add New Editor” button. From there, click on the “Single Record” radio button. Then enter “About Us” in the “Menu Name” field and click on ”Create New Menu”.
On the next screen, which is a list of existing section editors, click on “modify” next to the “About Us” entry. That will bring you to a screen that will allow you to add new information fields to the section editor’s field menu.
We’ll keep things pretty simple to begin with, so for the menu of fields on your section editor, in addition to the “Title” and “Content” fields that are automatically created, you’ll be creating a text field called “Street Address”, a text field called “City” a text field called “State” a text field called “Zipcode”, a text field called “Phone” and a text box called “Description”.
You’ll add these fields by clicking on the “Add Field” button at the bottom of the field list.
For the first field, type “Street Address” in the “Field Label” box.
You’ll notice that your entry is reflected in the Field Name” box, but there are only lower case letters and numbers, and that any spaces or special characters are replaced by underscores. After you’ve created a field, you can modify your “Field Label” to say anything that you want to, but the “Field Name”, which is the actual name of your field in your MySQL database, is restricted to those types of characters.
From the “Field Type” pull down select “text field”.
Click on the Show All link next to “Input Validation” and check the box that says “Required” so that the user can not leave this field blank.
You’ll be creating a number of text fields, so instead of clicking on “Save”, click on “Save & Copy”. You’ll notice that the Field Label now says “Copy of Street Address” and all the other parameters (like the “Required” checkbox) are the same as they were for the original field.
Change the “Field Label” to “City”. Notice that the “Field Name” changes as well.
Click on “Save & Copy” to create the “State” field, the “Zipcode” field, and the “Phone” field. Then click on “Save” because this is the last text field that we’ll be creating for this exercise.
HINT: To create a field that maintains all of the parameters of any original field, click on “modify” next to the original field and then click on “Save and Copy” to create the new field and then change the “Field Label” of the new field.
There’s one more information field to create and that is the text box for the “Description”. You should be able to do that on your own.
For this exercise we won’t be using the “content” field so you can click on the “erase” link next to the “content” entry.
|
ADDING A SEPARATOR FIELD - Jun 7th, 2015
The “About Us” editor is a pretty simple section editor, but if you had a large number of fields, you’d probably want to be able to group them into sections, and then insert header bars at the top of each section. With CMSB it’s a snap to create as many header bars as you need. You can also customize their color and other properties to meet your specific needs using standard HTML tags..
For this editor, let’s create a header bar that says “Company Information”.
Click on “Add Field” and in the “Field Type” pull down select “–separator--”
This type of field doesn’t use a “Field Label” or “Field Name”, so click on the “Header Bar” check box and type “Company Information” into the box just below the radio button. Then click save.
|
RESTRICTING ACCEPTABLE DATA - Jun 7th, 2015
Now it’s time to modify the parameters of the “State” field, so click on modify next to the “State” field entry.
If the input validation fields are not showing, click on “show all”.
The Required box should already be checked.
State/Possession abbreviations all have 2 letters so enter a 2 in the “Min” and the “Max” length boxes.
State/Possession abbreviations are always capital letters, so select “only allow characters” from the “Allowed Content” menu and type all the capital letters A through Z (no commas and no spaces) in the box to the right. Don’t include a “B” or a “Q” since they do not appear in any of the official abbreviations.
In the “Field Description” Box type “Enter only official 2 capital letter abbreviations”. Then click “Save” to save your changes to this field.
!!!YOU MUST ALSO CLICK ON THE “SAVE DETAIL” BOX OR YOUR CHANGES WILL NOT BE SAVED TO YOUR DATABASE!!!
|
PUTTING YOUR FIELDS IN A LOGICAL ORDER - Jun 7th, 2015
You’ve created 7 information fields and one separator field, but when you look at the list of fields, they are not in an order that makes the most sense, so for convenience, let’s rearrange them so that the header bar appears at the top, followed by Title, Street Address, City, State, Zipcode Phone and Description. Just click on one of the up/down arrows in the “Drag” column and drag any field up or down in the list to where you want it to appear.
HINT: You can rearrange any field list using this technique. It does not affect your web pages, just it’s position on the field list.
|
ENTER THE “ABOUT US” DATA - Jun 7th, 2015
Now that you’ve created all of the fields needed for your “About Us” page, it’s time to enter some data so that it will appear on your page. Click on “About Us” in the menu on the left side of your page. This will display a user interface with all of the fields that you created. Enter the appropriate information into all of the fields and click “Save”.
CAUTION: Your information is not uploaded to the database until you click “Save”. If you don’t save your work, it will be lost when you close the page in your browser.
HINT: Instead of typing information directly into the interface, you can copy and paste text from your favorite word processor.
|
CONVERTING YOUR HTML PAGE - Jun 7th, 2015
Now it’s time to convert your “About Us” web page to work with CMS Builder.
Make a copy of your HTML page and change the file extension from .html to .php, then open the new .php page in your web page editor.
In your CMSB interface, click on the Admin tab on the CMS Builder main page and then on “Code Generator”. This is one of the most powerful and useful tools in CMS Builder. It allows you to copy and paste code snippets into your web page minimizing the need for retyping and the possibility for error.
Select the About Us” section from the pull down menu and click on the “Detail Page” radio button. Leave all of the other entries at their default settings and click on “Show Code”.
The first thing that you’ll want to change on your web page is the code above the <head> tag. Using copy and paste, replace all the code above the <head> tag on your web page with the code from the Code Generator that’s above the <head> tag.
Then, in the “Step 2 area” of the code generator code, locate the word “Title:”. The code that follows, including the less than and greater than sign will replace the text for Company Name on your web page. Don’t replace any of the formatting, just the text.
Repeat this for the code next to Street Address:, City:, State:, Zipcode:, Phone:, and Description:. Then save your new page and upload it to your server.
If you’ve done all the steps correctly, you should see your web page, exactly as you designed it.
If you get error, open the sample PHP page and compare the code with the code on your page. The most common mistakes are missing a less than “<”, or greater than “>” sign when copying and pasting, or missing some of the information above the <head> tag.
Now that you’ve succeeded in creating your first page, let’s move on to create the next one.
|
CREATING AN “EVENTS” PAGE WITH A MULTI RECORD SECTION EDITOR - Jun 7th, 2015
This page utilizes a multi record section editor to manage it’s content.
In your “Events” section editor, you’ll want to be able to enter a thumbnail image, a title, some dates and times, and a brief description for each event.
On your “Events” listing web page, you’ll want surfers to be able to click on one of the event listings and be taken to that event’s “detail” page which displays the event title, the event date and times, and much more detail about that event.
|
UNDERSTANDING A LIST PAGE - Jun 7th, 2015
Here’s where things get a little different, so stick with me.
In the table that we created to hold the content for this example there are 2 columns and 2 rows . The left column holds the thumbnail image for an event and the right column holds an event title and a link, The date and time of the event, and a brief description of the event.
<table width="800" border="0" cellpadding="5"> <tr> <td><img src="images/image1.jpg" width="150" height="250" alt="image 1" /></td> <td><a href="event1.htm">Event # 1Title</a><br />List Page Description<br /> Date and Time<br /> </td> </tr> <tr> <td><img src="images/image2.jpg" width="150" height="250" alt="image 2" /></td> <td><a href="event2.htm">Event # 2 Title</a><br />List Page Description<br /> Date and Time</td> </tr> </table>
There are 2 events listed in the 2 rows of the table.
But wait you say, if we’re going to display all of the events listed in the multi record section editor, the basic idea for the layout is what we want, but we need a more flexible approach then a new hard coded row for each event.
So here’s the more flexible approach.
First, get rid of the extra row in the table, since it will no longer be used:
<table width="800" border="0" cellpadding="5"> <tr> <td><img src="images/image1.jpg" width="150" height="250" alt="image 1" /></td> <td><a href="event1.htm">Event # 1Title</a><br />List Page Description<br /> Date and Time<br /> </td> </tr> </table>
Then, inside the beginning of the table, insert an instruction that says for each record in our events database table, execute the following steps, and at the end of the table, insert an instruction that says stop executing the instructions and look for the next record. Our table will then look like this:
<table width="800" Align="center" border="0" cellpadding="5"> <?PHP foreach ($eventsRecords as $record): ?> <tr> <td> <img src="images/image1.jpg" width="150" height="250" alt="image 1" /></td> <td><a href="event1.htm">Event # 1Title</a><br />List Page Description<br /> Date and Time<br /> </td> </tr> <?PHP endforeach; ?> </table>
Since the looping instructions surround the code necessary to create a new row, each event will be displayed in a separate row.
Then, from the “Step 2 area” of the Code Generator code, locate the word “Title:”. The code that follows, including the less than “<,”and greater than “>” sign, will replace the text for the event name on your web page. Don’t replace any of the HTML formatting, just the text. Repeat this process for the code next to “Dates and Times:”, and “List Page Description:”. Then find the code next to” _link:” and insert one set in place of the link URL. Like this:
<table width="800" border="0" cellpadding="5"> <?PHP foreach ($eventsRecords as $record): ?> <tr> <td><img src="images/image1.jpg" width="150" height="250" alt="image 1" /></td> <td><a href="<?PHP echo $record['_link'] ?>"><?PHP echo $record['title'] ?></a><br /><?PHP echo $record['list_page_description'] ?><br /> <?PHP echo $record['date_and_time'] ?><br /> </td> </tr> <?PHP endforeach; ?> </table>
That leaves only the image thumbnail to deal with.
There's a lot of extra code in the “Step2a” area in the Code Generator code. There's a complete walk through of what it all means in a later recipe, but for now, just paste the following code into your table to replace the entire <img src.../> statement on your page to display the image thumbnail on your web page.
<?php foreach ($record['image'] as $index => $upload): ?>
<img src="<?PHP echo $upload['thumbUrlPath'] ?>" width="<?PHP echo $upload['thumbWidth'] ?>" height="<?PHP echo $upload['thumbHeight'] ?>" alt="" /><br />
<?PHP endforeach ?>
The table on your page should now look like this:
<table width="800" border="0" cellpadding="5"> <?PHP foreach ($eventsRecords as $record): ?> <tr> <td> <?php foreach ($record['image'] as $index => $upload): ?>
<img src="<?PHP echo $upload['thumbUrlPath'] ?>" width="<?PHP echo $upload['thumbWidth'] ?>" height="<?PHP echo $upload['thumbHeight'] ?>" alt="" /><br />
<?PHP endforeach ?> </td> <td><a href="<?PHP echo $record['_link'] ?>"><?PHP echo $record['title'] ?></a><br /> <?PHP echo $record['date_and_time'] ?><br /><?PHP echo $record['list_page_description'] ?>> </td> </tr> <?PHP endforeach; ?> </table>
And that completes the listing page. Save it and move to the detail page.
|
CREATING THE HTML PAGES - Jun 7th, 2015
First, as before, design both the list page and the detail page in HTML and make sure that they look the way you want them to and that all the functions work as planned. Include a thumbnail image on the list page. Call them events.html and eventsdetail.html
For the content area of the example events listing page, create a simple table that looks like this:
<table width="800" Align="center" border="0" cellpadding="5"> <tr> <td><img src="images/image1.jpg" width="150" height="250>" alt="" /></td> <td><a href="event1.htm">Event # 1Title</a><br />List Page Description<br /> Date and Time<br /> </td> </tr> <tr> <td><img src="images/image2.jpg" width="150" height="250>" alt="" /></td> <td><a href="event2.htm">Event # 2 Title</a><br />List Page Description<br /> Date and Time</td> </tr> </table>
For the html detail page, you only need to code the information for a single event.
Then make a list of all the areas (fields) that you want to be able to enter information about. In this example you’d have an Event title, event dates, an image that’s representative of the event. You’d also have a short description of the event and a longer detailed description of that event.
|
CREATING THE MULTI RECORD “EVENTS” SECTION EDITOR - Jun 7th, 2015
Since you’re going to have multiple events on your listing page you’ll use a multi record section editor. That way the user can create additional events and all the events will be listed on your list page.
For the menu of fields in your section editor, in addition to the title and content fields that are automatically created you’ll add a text field called “Date and Time” a text box called “List Page Description”, a text box called “Long Description” and an upload field called “Image”
After you have added these four fields, you should erase the automatically created field called “content” since you won’t be using a WYSIWYG field for this example.
|
RESTRICTING ACCEPTABLE DATA - Jun 7th, 2015
Now let’s set up some important parameters for the upload field.
First click on “modify” next to the upload field. We’ll assume that the thumbnail on your list page should be a maximum of 150 pixels wide and 150 pixels high, which is the default size, so all we’ll have to do is remove the entries in the “file extensions allowed” area that we don’t want. You should be left with jpg,png (just the 2 extensions with a comma in between them and no spaces or periods)
HINT: There’s nothing special about these entries, so you can remove them all and just enter the few that you want. You can add ones that are not on the list and the program will apply that filter to the upload.
HINT: CMS Builder does not change the aspect ratio of your images when it resizes them. It also will not enlarge your images to fit an allotted space. It just shrinks them to fit within the allotted dimensions.
Next change maximum uploads from 25 to 1, and maximum upload size from 5120 Kbytes to 1000 Kbytes (1 megabyte)
Scroll down and delete the word “Title” and the word “Caption” from the “info” fields since you won’t be using these optional fields in this example, and click on “save”.
Then click on the Viewer URL tab and enter “/event.php” for the List Page URL and “/eventdetail.php” for the Detail Page URL (don’t forget the slashes but leave out the quotation marks)
!!!YOU MUST CLICK ON THE “SAVE DETAIL” BOX OR YOUR CHANGES WILL NOT BE SAVED TO YOUR DATABASE!!!
|
PUTTING FIELDS AND EVENT LISTINGS IN A LOGICAL ORDER - Jun 7th, 2015
As in the “About Us” example, you can click on one of the up/down arrows in the “Drag” column and drag any field up or down in the list to where you want it to appear. Also, if you want to change the order that events appear on your events listing page, you can drag them in the events list to rearrange them.
|
CREATING THE EVENTS - Jun 7th, 2015
Now you’re going create 2 events for our page and enter some data for them into the section editor, so you’ll need 2 images that are each less than 1mb in size.
On the CMS Builder main interface page, click on Events in the menu on the left side of your screen. Then click on “Create” and a new blank record will appear.
The text information in this record is entered the same way as it was in the “About Us” editor interface.
Upload fields work a little differently. You’ll see a box next to the Image “Field Label”, and under that a link that says “Add or Upload File(s)”. If you click on that link you’ll see an “Upload File” box. Click on the “Browse” button and navigate to the image that you want to appear on that event listing. Then click on Upload. When the upload is complete you will see a thumbnail of the image in the upload field box.
In addition to uploading the image, CMS Builder has automatically created thumbnails of your image with the maximum dimensions that you specified when you created the upload field.
After you’re done, click “Save” to save your work (upload it to the on-line database)
|
CONVERTING YOUR HTML PAGES - Jun 7th, 2015
Now it’s time to convert the 2 web pages to .PHP pages that will work with CMS Builder.
As in the “About Us” example, make copies of your 2 web pages and change their extensions to .PHP
The information above the <head> tag is going to be different on each of your pages.
Open the list .PHP page.
In the Code Generator, choose “Events” from the pull down menu but this time leave the “List Page” radio button checked. Don’t change any of the default choices and click on “Show Code”.
As in the “About Us” example, the first thing to do is to replace the new page code above the <head> tag with the code from the Code Generator.
|
CREATING THE EVENTS DETAIL PAGE - Jun 7th, 2015
Now let’s create the event detail page. Remember, this page contains only the event title, event dates and times, and a long description of the event.
Go back to the main CMSB admin page and click on the Code Generator. Select the “Events” Section editor, but this time click on the “Detail Page” radio button. Leave the default setting for everything else and click on “Show Code”.
Open your HTML detail page and replace the code before the <head> tag as before.
Then find the code after Title:, Date and Time:, and Long Description:, and replace the text in your page with the appropriate PHP code.
And that’s it. Upload events.php and eventsdetails.php to your server and everything should work as planned. Again, if you get any errors, compare the code of your PHP pages with the sample pages. Again, the most common mistakes are missing a less than or greater than sign when copying and pasting, or missing some of the information above the <head> tag.
Now that you understand the basics of CMSB, happy coding. If you’re stumped, look for an example here in the cookbook, or visit the CMS Builder Forum at:
http://www.interactivetools.com/iforum/CMS_Builder_F35/
|
UNDERSTANDING THE BUILT IN CODE GENERATOR - Jun 7th, 2015
The code generator built in to the CMSB Interface (Adnin>Code Generator can save time and effort when creating viewers for your site, but it can be a bit confusing at first.
To help you to understand the code generator, after you’ve created your 2 section editors, click on “Code Generator” in the admin section of your CMSB interface.
You’ll see a list of options under “Create a Viewer”. The only two you should focus on are “List Page” and “Detail Page”.
List pages are used to show the records in a multi-record editor. Detail pages are used to show data from a single record editor or from a specific record in a multi record editor.
Once you’ve populated your sections with some data, you can copy the entire generated code into a blank PHP document and upload it to your server to see what that generated code looks like in a viewer.
DETAIL PAGE CODE Start by clicking on “Detail Page”. Click on the “Single record sections: Load first record in database” radio button and choose “About Us” from the pull down list. And click on “Show Code”
The first lines of code up to <!DOCTYPE html PUBLIC... are required to load CMSB and the data from your “about_us” database.
From <!DOCTYPE html PUBLIC... through <!-- STEP2: Display Record... is pretty standard HTML code
After that you’ll find the PHP code that pulls data from your database and displays that data.
For example, the line of code Title: <?php echo htmlencode($about_usRecord['title']) ?> pulls the information from the “title” field of your “abou_us” editor and displays (echos) that information after the text “Title:”. “htmlencode” is not mandatory, but it helps to insure that the code is displayed correctly.
LIST PAGE CODE Now let’s look at the code that gets generated for a list page.
Go Back to Admin>Code Generator but this time choose List Page from the “Create A Viewer” list “Events”. Then choose “Events” from the pull down menu, make sure that “Show all records” is checked, and Click on Show Code.
Notice that the LOAD RECORDS code at the top of the page is different then it was for the Detail Page. This is because you will be looping through the records in this multi-record editor and showing specific data from all “events” records on your list page viewer, together with links to show detailed information about a specific record on your detail page.
In Step2: you’ll see <?php foreach ($eventsRecords as $record): ?>. This tells the database to loop through each record in the database and pull specific information from each record.
The next lines, for example, Title: <?php echo htmlencode($record['title']) ?> pull the data from the title field of the record, and displays (echoes) that information after the text “Title:”.
STEP 2a: Display Uploads for field 'images' STEP 2a may seem a bit confusing at first because of the amount of information that it contains, but let’s take it piece by piece and it will become clearer.
The first lines through the <blockquote> is just a reminder of some of the special field names can be used inside this foreach loop to pull data from your records.
Next you’ll find a second foreach loop. <?php foreach ($record['images'] as $index => $upload): ?> This one says loop through each upload in the field “images” (in the record that the first foreach loop is looking at) so that some information about that upload can be displayed.
This is where it gets a bit confusing...
Next, there’s Upload Url: <?php echo $upload['urlPath'] ?>, which is the code that you’d use to display (echo) the URL of the upload.
Then there’s a line of commented code <!-- Uploads: Copy the tags from below that you want to use, and erase the ones you don't need.
You’ll need to remove that line if you want to display the entire generated code as a viewer.
The next lines of code are the ones that you will use in your viewer to display different types of uploads.
Since you have uploaded images and have generated thumbnails for those images, you would use the line: <img src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" alt="" /> as your image tag.
Since foreach loops have to be instructed to end, you would need to use one <?php endforeach ?> tag to end the $upload loop and another <?php endforeach ?> to end the $record loop in your viewer code.
DETAIL PAGE FOR A MULTI-RECORD EDITOR This time, when you go to Admin>Code Generator, choose Detail Page, then choose “Events” from the pull down list, check Multi record sections: Get record # from end of url, and click on “Show Code”.
Again the LOAD RECORDS Code is slightly different from the others and in STEP 2 and 2A the code specifies the name of the section in the PHP code, as it did for Single Record viewers.
|
CHAPTER 1 - SECTION EDITORS
|
CREATING A NEW PAGE FROM AN EXISITING HTML PAGE OR A TEMPLATE - Aug 1st, 2010
1. Examine your HTML page to determine what data fields will be necessary. 2. Create a new section editor from the preset template that most closely meets your needs. 3. Modify or add any fields as required for the particular HTML page. 4. Enter any default information as required. 5. Save. 6. View the code generator. 7. Make a copy of the html page. 8. Change the .html file extension to .php. 9. From the code generator, copy all code above the <head> tag and paste it into the new PHP document Replacing all the information above the <head> tag. 10. Copy the appropriate PHP echo code to replace the variable text segments in your new PHP document, keeping any formatting or CSS tags in place. 11. Upload your new PHP document to your server and test it. 12. After you’re happy, delete the old HTML version from your server.
|
ERROR MESSAGES ABOUT FIELD NAMES NOT FOUND - Aug 1st, 2010
If after you delete fields from a multi-record section editor, you get errors about field names that are not found Go to “viewer URLS” and” searching” and 'sorting" tabs on the section modification screen and delete the field names that no longer exist or change the field names as appropriate.
You should also check the ListPage Fields on the "general" tab to make sure that the correct fields will be displayed on the editor list page.
|
DUPLICATE A RECORD WITHOUT HAVING TO RETYPE THE DATA - Dec 29th, 2018
BLUKABM did, and said, “That way I could modify the copied record instead of creating a new one and re-entering data that won't change much. “
In Dave’s (unsupported) approach to add a "Save as Copy" button to the bottom left of the edit page he said:
“It doesn't support uploads or all the field types but worked for this case. I'm posting in here in case it turns out to be useful for someone else as well.”
1. - Create a backup copy of /lib/menus/default/edit.php 2. - Open /lib/menus/default/edit.php 3. - Search for showWysiwygGeneratorCode 4. - Add the new code below(about 15 lines above showWysiwygGeneratorCode)
<table border="0" cellspacing="0" cellpadding="0" width="690"> <tr> <!-- Insert This Code --> <td> <input type="submit" name="action=save" value="<?PHP _e('Save as Copy') ?>" onclick="document.getElementById('num').value=''; document.getElementById('preSaveTempId').value='1234567890abc'" class="inputButton" /> </td> <!-- End of Insert--> <td align="right"> <input type="submit" name="action=save" value="<?PHP _e('Save') ?>" class="inputButton" /> <input type="button" name="cancel" value="<?PHP _e('Cancel') ?>" class="inputButton" onclick="window.location='?menu=<?PHP print urlencode($menu) ?>'" /> </td> </tr> </table> </form> <?PHP showWysiwygGeneratorCode() ?>
This approach was made into a free plugin in November 2010. The plugin adds the functionality of copying the record and its upload as well. Pretty cool.
You can download the free plugin from:
http://www.interactivetools.com/add-ons/?user_submitted=1
|
GET RID OF (OR REPLACE) “THESE UPLOADS MAY BE DISPLAYED OR LINKED ON OUTPUT PAGE.” ABOVE ALL THE IMAGE UPLOAD FIELDS. (LEGACY). - Aug 1st, 2010
Navigate to your cmsAdmin/lib/menus/default folder and backup the edit_functions.php file
Then open the file and search for “// display field”
You’ll find the comment there and you can either delete the comment between the ‘ marks, or change it to something more appropriate to your needs.
|
SPECIAL FIELD NAMES - Aug 1st, 2010
These "special" fields can add functionality to your sections. Here’s the list so you won’t have to look for them.
Fieldname - Editable -Description createdDate - Not editable - Automatically stores the date the record was first created createdByUserNum - Not editable - Automatically stores the 'num' of the user who created the record. This value is also used to identify the 'owner' of the record. updatedDate - Not editable - Automatically stores the date the record was last updated updatedByUserNum - Not editable - Automatically stores the 'num' of the user who last updated the record. publishDate - Editable Date Field - Record won't be displayed on website before this date. This allows users to prepare content in advance and have it appear on a certain date and time. removeDate Editable Date Field - Record won't be displayed on website after this date. This allows users to have content automatically "expire" from website after a certain date and time. neverRemove Editable - Checkbox - This checkbox field indicates that "removeDate" should be ignored. This lets users have some records that expire (are hidden) after a certain date and other records that never expire. hidden - Editable Checkbox - This checkbox field indicates that the record should be not be displayed on the website. This lets users temporarily make records visible or not. dragSortOrder - Editable - This field allows the user to drag records in the section editor record list to change their order. Just create this field and add it as the first entry of "ListPage Fields" and "Order By" to enable this functionality.
|
IMPLEMENTING AN APPROVAL PROCESS BEFORE A REVISION GOES LIVE (LEGACY) - Mar 10th, 2011
As of Version 2.07, the ability to preview a page before it goes "live" is built in to CMSB.
If you're using an older version you can still implement an approval process so that you can approve entries before they can be seen by the public.
Assuming you're using a multi-record editor, you can hide a record form your public web site pages using the special "hidden" checkbox field. If you set it to be an admin only field to only administrators and section managers can take a record live, but not the original author.
You could get really slick by setting up a special copy of the viewer for this information with the code:
'where' => " hidden = '0' ",
In the list records call at the top of your viewer
Setting the user account permissions for editing by author and changing the owner (Created By) after approval is one way to implement an approval process and prevent further changes by the user.
In a single record editor you’d have to create a new set of “for Approval” fields and once the new information is approved, the admin or section manager would have to paste the approved information into the “live” fields.
|
POPULATE A FIELD IN A DATABASE TABLE FROM FIELDS IN ANOTHER TABLE - Aug 1st, 2010
A way to take 3 fields from one table entered in one Editor and have then populate one field in another Editor. Let’s say in the first section there are 3 fields: code, product and format. I enter all my products using that Editor. I have setup another Editor to enter some specials for some chosen products. When adding new special I would like to be able to select products - entered in the previous Editor - from a list that is populated from the code, product, format field from the other table (Editor).
Under list options selected "Get options from MySQL Query (advanced)" and enter this (use your own table prefix and table name instead of cms_tablename):
SELECT num, CONCAT_WS(" ", code, product, format) FROM cms_tablename
The CONCAT_WS mysql function means "concatenate with string" or "join these fields together with this first value". So in the above example it would join code, product, and format together with a space and return that as the pull down "label". I set the pull down "value" as the num field. If you want the joined value for both just use this:
SELECT CONCAT_WS(" ", code, product, format), CONCAT_WS(" ", code, product, format) FROM cms_tablename
|
INSERT INFORMATION FROM ONE SECTION EDITOR INTO ANOTHER - Mar 17th, 2011
Sagentic had this challenge:
We have a section called "products" .
Then we have a section called "pricing" that allows you to enter in different sizes of that product and the price. The first field in this section is a list that pulls the name of the product from the "products" section.
In short, I want to pull all "pricing" entries for Metal Garden Sheds and put it on the "product" page for Metal Garden Sheds - all "pricing" entries for Wood Garden Sheds and put it on the "product" page for Wood Garden Sheds - etc....
Dave Edis from Interactive Tools observed:
What you want to do is have your first viewer that loads the product accept "url searching" like this: products.php?4 That's the default so that should be fine.
For your price viewer you want it to ignore the search values and hard code the search as a where. That's because you want to base the search off the value of the product record, not what's in the url. First add a line to get the escaped productName value:
$escapedProductName = mysql_real_escape_string( $productsRecord['name'] );
Next add this in your price viewer code:
'allowSearch' => false, 'where' => " product = '$escapedProductName' ",
ANOTHER EXAMPLE Here’s an example of how to use this approach to restrict the records shown on a video list page to only those that belong to a specific exhibition.
For this example 2 multi record editors are involved.
One multi record editor, called “exhibitions” contains a separate record for each exhibition. Each record has a field for a unique exhibition_name and an upload field containing a series of still images of those exhibitions. The exhibitions detail page has a link to the video list page with the exhibitions record number appended .
The other, called “videos” has a separate record for each video with a field for the exhibition_name (which gets it’s value from a radio button list populated from the exhibition_name field of the exhibitions editor) and an upload field containing one of the video taken at that exhibitions.
<a href='<a href='videos.php?num=<?php echo $exhibitionsRecord['num'] ?>'>WATCH THE VIDEO FROM THIS EXHIBITION</a>
Then in the video list page in the get records area:
<?php header('Content-type: text/html; charset=utf-8'); ?> <?php
// load viewer library $libraryPath = 'cmsAdmin/lib/viewer_functions.php'; $dirsToCheck = array('/path_to_your_server/','','../','../../','../../../'); foreach ($dirsToCheck as $dir) { if (@include_once("$dir$libraryPath")) { break; }} if (!function_exists('getRecords')) { die("Couldn't load viewer library, check filepath in sourcecode."); } // load records list($exhibitionsRecords, $exhibitionsMetaData) = getRecords(array( 'tableName' => 'exhibitions', )); $exhibitionsRecord = @$exhibitionsRecords[0]; // get first record $escapedExhibitionName = mysql_real_escape_string( $exhibitionsRecord['exhibition_name'] ); // load records list($videosRecords, $videosMetaData) = getRecords(array( 'tableName' => 'videos', 'allowSearch' => '0', 'where' => " exhibition_name = '$escapedExhibitionName' ", )); ?>
And in the body of the videos list page a straightforward (except I’ve included the MaxWords function that you can find in the recipe “MAXWORDS - LIMITING THE NUMBER OF WORDS SHOWN ON A PAGE”):
<table> <?php foreach ($videosRecords as $record): ?> <tr> <td> <?php foreach ($record['list_image'] as $upload): ?> <a href="<?php echo $record['_link'] ?>"><img src="<?php echo $upload['thumbUrlPath2'] ?>" width="<?php echo $upload['thumbWidth2'] ?>" height="<?php echo $upload['thumbHeight2'] ?>" alt="" /></a> <?php endforeach; ?> </td> <td><a href="<?php echo $record['_link'] ?>"><?php echo $record['video_title'] ?></a><br /></td> </tr> <tr> <td colspan="2"> <?PHP echo maxWords($record['description'], 25); ?>...<a href="<?php echo $record['_link']; ?>">Read More...</a></td> </tr> <tr> <td colspan="2"><hr align="center" width="300" color="#99945e"/></td> </tr> <?php endforeach; ?> </table>
NOTE: If you have other tables being accessed in your get records calls, you may have to include the line:
'allowSearch' => false,
in those calls, so that the search at the end of the URL does not affect the records returned from those tables. (This will cause some very strange results on your pages)
|
CHOOSING A BACKGROUND IMAGE FROM A LIST - Jan 8th, 2012
My client wanted to change the background image behind their masthead to reflect the seasons. They required the process to be both easy (one click selection) and flexible (the list needed to be dynamic)
Here’s what I came up with.
1) First, I created a multi-record editor called Masthead Background Image Bank with only a title field and an image upload field. The field allowed only a single image to be uploaded. I then created a record for each background image and uploaded them.
And, in a single record section that I call common_information:
1) I created a list field that’s called masthead_background_image. This list field gets it’s list options from a database (the masthead_background_image_bank) with option values from the num (record number) field and option labels from the title field.
2) Then I added an image upload field called masthead_image which allows only one image to be uploaded and that contains the foreground masthead image. HINT: If transparency is important, restrict this field to accept png images only, and create a 24bit png for the actual masthead.
At the top of my viewers I added load records calls for both section editors.
// load records list($common_informationRecords, $common_informationMetaData) = getRecords(array( 'tableName' => 'common_information', 'allowSearch' => '0', 'limit' => '1', )); $common_informationRecord = @$common_informationRecords[0]; // get first record
// load records list($masthead_background_image_bankRecords, $masthead_background_image_bankMetaData) = getRecords(array( 'tableName' => 'masthead_background_image_bank', ));
Then, in the viewer body, where I wanted show the masthead, I used:
NOTE: Since I'm pulling the information for the $recnum variable from a list field, the option value (in this case the record number) is displayed by default. If for some reason I needed to display the option label instead, I'd display the pseudo field :label value by adding that to the fieldname like this: $common_informationRecord['masthead_background:label']
<table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <?php $recnum = $common_informationRecord['masthead_background'] ?> <td background="<?php foreach ($masthead_background_image_bankRecords as $record ): ?><?php if ($record['num'] == $recnum): ?><?php foreach ($record['image'] as $upload): ?><?PHP echo $upload['urlPath'] ?><?PHP endforeach; ?><?php endif ?><?PHP endforeach; ?>" >
<img src="<?php foreach ($common_informationRecord['masthead_image'] as $upload): ?><?PHP echo $upload['urlPath'] ?>" width="<?php echo $upload['width'] ?>" height="<?php echo $upload['height'] ?>" alt="" <?PHP endforeach; ?>"> </td> </tr> </table>
|
USING "RELATED RECORDS" TO POPULATE PAGES FROM A MASTER “ADDRESS BOOK” OR “PRODUCT LIST” - Aug 30th, 2017
Let’s say you have a number of address book entries that contain things like name, address, phone, travel directions, map URL, etc. Or you have a number of products with detailed information about each of them.
Instead of retyping all of your information each time you want to display it on a list or detail page, you can pull that information directly from your master information list. Chris Waddell from Interactive Tools created a “relatedRecordLookupFunctions” plugin to add the required functionality this and suggested the following approach, I modified the table and field names for this “Address Book” example:
MULTI-VALUE LIST FIELDS (THE CODE REQUIRED FOR SINGLE VALUE LIST FIELDS FOLLOWS)
Step 1: Set up your address book section. for this example call it “Venue Address Book”.
This is a standard multi-record section with the necessary information fields. Since this example is an address book of venues for an events listing, I’ve set up fields for Venue Name, Venue Address, Venue Phone, Venue Contact E-mail, Venue URL, Venue URL link text (I like to keep these separate to add flexibility for my clients but I set the default text to WEB SITE or CLICK HERE FOR WEB SITE), Venue Travel Directions, and Venue Map URL (either from Mapquest or Google maps).
Step 2: In the section where you want this information to appear you’ll add a list type field called “Venue” with the following parameters.
Field Label: Venue Field Name: venue Field Type: list Field Options: Display As: pull-down or checkbox (multi-value for multi-value lists only) List Options: Get options from database (advanced) Section Table name: venue_address_book Use this field for option values: num Use this field for option labels: venue_name
Step 3: Install the Related Record Lookup Functions Plugin which you can download from:
http://www.thecmsbcookbook.com/downloads/relatedRecordLookupFunctions.zip
Upload the file to your server in the /cmsAdmin/plugins directory, then log into CMSB, go to Admin > Plugins, and click Activate on it.
LIST PAGES Step 3: To set up your viewer to display the fields required you'll need to add some code to the top of your page. You probably already have most of the required code in your PHP source code. Just add this code:
beta_lookupRelatedFields(array( 'table' => 'e_blast_events_notice', 'recordList' => &$e_blast_events_noticeRecords, 'fieldList' => array( 'venue' ) )); $e_blast_events_noticeRecord = @$e_blast_events_noticeRecords[0]; // get first record
to your existing code, like this:
<?php header('Content-type: text/html; charset=utf-8'); ?> <?php require_once "/your_path_to/cmsAdmin/lib/viewer_functions.php";
list($e_blast_events_noticeRecords, $e_blast_events_noticeMetaData) = getRecords(array( 'tableName' => 'e_blast_events_notice', 'where' => whereRecordNumberInUrl(1), 'limit' => '1', )); ?> <?php if ($e_blast_events_noticeRecords): ?> <?php beta_lookupRelatedFields(array( 'table' => 'e_blast_events_notice', 'recordList' => &$e_blast_events_noticeRecords, 'fieldList' => array( 'venue' ) )); $e_blast_events_noticeRecord = @$e_blast_events_noticeRecords[0]; // get first record
?> <?php endif ?>
<?php // show error message if no matching record is found if (!$e_blast_events_noticeRecord) { header("HTTP/1.0 404 Not Found"); print "Record not found!"; exit; }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">
Step 4: Then in the body, where you want to display your address book fields:
<?php if (empty($e_blast_events_noticeRecord['venue'])): ?> No Venue Information is available. <?php else: ?> <div align="left"> Venue Information: <br />
<?php foreach ($e_blast_events_noticeRecord['venue'] as $venue): ?> <?php echo $venue['venue_name'] ?><br /> <?php echo $venue['venue_address'] ?><br /> <?php echo $venue['venue_contact_e_mail'] ?> <br /> <?php echo $venue['venue_phone'] ?><br /> Directions: <br /><?php echo $venue['venue_travel_directions'] ?> <br /> <a href="<?php echo $venue['venue_map_url'] ?>">Click / Tap for a Map</a><br /> <?php endforeach ?> </div> <?php endif ?>
You can display the fields separately but you’ll need a foreach loop for each field or set of fields that you want to display.
DETAIL PAGES:
To set up your viewer to display the fields required you'll need to add some code to the top of your page. You probably already have most of the required code in your PHP source code. Just add this code:
The <?php if ($e_blast_events_noticeRecords): ?> <?php beta_lookupRelatedFields(array( 'table' => 'e_blast_events_notice', 'recordList' => &$e_blast_events_noticeRecords, 'fieldList' => array( 'venue' ) )); $e_blast_events_noticeRecord = @$e_blast_events_noticeRecords[0]; // get first record ?> <?php endif ?>
Then, on the detail page where you want the information to be displayed:
<?php $venue = $e_blast_events_noticeRecord['venue']; ?> <?php echo $venue['venue_name'] ?><br /> <?php echo $venue['venue_address'] ?><br /> <?php echo $venue['venue_contact_e_mail'] ?> <br /> <?php echo $venue['venue_phone'] ?><br /> Directions: <br /><?php echo $venue['venue_travel_directions'] ?> <br /> <a href="<?php echo $venue['venue_map_url'] ?>">Click / Tap for a Map</a><br />
SINGLE VALUE LIST FIELDS According to Chris Waddell from Interactive Tools, “The process works with single value lists too, but the interface is slightly different.(Don't forget to make your list a single value pulldown or check box) The plugin replaces the field with the associated record, instead of a list of records. For this reason, you wouldn't use foreach to loop over the records.”
Here’s how. First, define the variable $venue before it's first use:
<?php $venue = $e_blast_events_noticeRecord['venue']; ?>
Then where you want to echo the fields in your viewer:
<?php echo $venue['venue_name']; ?>
And if you wanted to include an “if” statement the code would look like this:
<?php if ($venue['venue_name']): ?> <?php echo $venue['venue_name']; ?> <?php endif; ?>
Or you could leave out the define variable step and just use:
<?php echo $e_blast_events_noticeRecord['venue']['venue_name']; ?>
LIST PAGES If you want to implement this on a list page:
Again here’s the code for the head of the list page:
<?php require_once "/hsphere/local/home/apbcweb/artistsofpalmbeachcounty.org/cmsAdmin/lib/viewer_functions.php";
list($e_blast_events_noticeRecords, $e_blast_events_noticeMetaData) = getRecords(array( 'Table name' => 'e_blast_events_notice',
));
?> <?php if ($e_blast_events_noticeRecords): ?> <?php beta_lookupRelatedFields(array( 'table' => 'e_blast_events_notice', 'recordList' => &$e_blast_events_noticeRecords, 'fieldList' => array( 'venue' ) )); $e_blast_events_noticeRecord = @$e_blast_events_noticeRecords[0]; // get first record ?> <?php endif; ?>
And here’s the code to display the related records in the body of the list page:
<?php foreach ($e_blast_events_noticeRecords as $record): ?> <?php $venue = $record['venue']; ?> Location:<br /> <?php echo $venue['venue_name']; ?><br /> <span class="body-text"><?php echo $venue['venue_address'] ?><br /> <?php endforeach ?>
Note: Whether you’re using this once, or multiple times on your page, the:
<?php if ($e_blast_events_noticeRecords): ?>
before the:
<?php beta_lookupRelatedFields...
makes sure that if there are no records matching your particular criteria, you wont get a “lookupReferringRecords: 'recordList' option missing” error.
IMAGES When implementing this function for images, Dan Maitland from Heelatch.com found that the “if” statement was important.
<?php if ($venue['venue_image']): ?> <?php foreach ($venue['venue_image'] as $upload): ?> <img src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" alt="" /><br /> <?php endforeach ?> <?php endif; ?>
The code from the venue_address_book code generator was
<?php foreach ($venue_address_book['venue_image'] as $upload): ?>
I changed that to:
<?php foreach ($venue['venue_image'] as $upload): ?>
to match the rest of the code in my viewer.
Of course, as always, styling is up to you.
|
PULLING DATA FROM AN ACCOUNT RECORD USING THE CREATEDBY FUNCTIONALITY BUILT INTO CMSB - Feb 1st, 2017
If you need to be able to pull information from the account record of the record owner (determined by the CreateBy field of the record), there's a built in function that will save you a great deal of grief.
I had a number of product listing records that were created by subscribers, and wanted to give the subscribers the option of filling in all of their contact information on each of the product listing records, or using their user profile information to automatically populate those contact information fields in a viewer.
Ross Fairbairn, the consulting guru at Interactive Tools came to my rescue with a really easy fix.
His suggestion, "Just substitute:
$your_listing_tableRecord['createdBy.your_field'] instead of $your_listing_tableRecord['your_field'] (or use $record['createdBy.your_field'] in your foreach loop)
This will use the built in createdBy function to do all the heavy lifting for you."
To offer the subscriber a choice, just include a checkbox in your listing table. and call it something like, "use_profile_contact_information"
Then use an if statement to display the appropriate code.
<?php if($your_listing_tableRecord['use_profile_contact_information'] == '0'):?> <?php if ($your_listing_tableRecord['your_field']) :?> <b>Contact:</b> <?php echo $your_listing_tableRecord['your_field'] ?> <?php endif ?> <?php elseif ($your_listing_tableRecord['use_profile_contact_information'] == '1'):?> <?php if ($your_listing_tableRecord['createdBy.your_field']) :?> <b>Contact:</b> <?php echo $your_listing_tableRecord['createdBy.your_field'] ?> <?php endif ?>
Ross added that, "createdBy fields load by default. You can disable them if you want in getRecords with:
'loadCreatedBy' => FALSE,
He went on to say that, "The only reason to disable them would be to save a on overhead when loading the page. In some cases we've seen sites with 10,000+ users and loading the createdBy data can have a noticeable slowing effect on page load times."
|
USING SEPARATORS - Sep 6th, 2010
Separators are fields whose only function is to neaten up your section editor layout. You can either: Leave a blank line between groups of fields (blank line), Create a text heading (Heading) for a groups of fields, or create a heading for the editor with special features like font size, bolding, or colored text (HTML)
CUSTOMIZING THE LOOK OF A SEPARATOR You can use html coding to change the look and contents of the header bar, so if you want the separator to be a horizontal line 300px wide that is aligned too the left you would type this in the header bar field:
<hr align="left" width="300" color="#FF0000">
If you want your header bar text to be red and bold you could type:
<font color=”#FF0000" ><b>YOUR HEADER TEXT</b></font>
If you get the wrong result, make sure that any leading and trailing quotation marks are the correct double quote symbol. Sometimes they can be different than what’s expected and cause a problem.
|
CREATING COLOR CODED LEGENDS AND COLOR CODED FIELD LABELS IN SECTION EDITORS - Aug 2nd, 2010
To make it easier for those doing the data entry on some section editors, my client asked if, in addition to heading separators, I could create a color coded legend at the top of the Section Editor and color code the “Field Labels” in certain places.
Here’s what I did. First I added an HTML separator field to my section editor (Add field - Field type “separator” - click on HTML) Next I added the following HTML code in between the <tr> and the </td> tags, replacing the <td colspan='2'> (I wanted the legend cell background to be a light grey).
<tr> <!-- Insert This Code --> <td bgcolor="lightgrey" colspan='2'> <font size="5"><b>LEGEND</b></font> <font size="3"> All fields in this editor are color coded according to where they will appear on the events web pages <hr> <font color="red">Special Information Only</font> <font color="darkorchid">Public List Page Only</font> <font color="green">Members standard form only</font> <font color="yellow">Appears on all Pages</font> </font> <!-- End of Insert--> </td> </tr>
Then, after I had created and saved all of my fields for the editor, I modified the field labels to the font size I wanted and to the colors that I set up in the legend with the following code:
<font size="3" color="Red"><b>Your Field Label</b></font>
If you save the field before you go back and modify the “Field Label”, your changes will not affect the “Field Name”.
You can change the values to suite your needs. My client found this approach very helpful and I hope that you will also.
|
USING CATEGORY MENUS - Aug 1st, 2010
The Basics...
If you want to create a series of “Nested” or “Unordered List” menus on your page and display the contents of that record on the page here’s how.
Create a new section editor called “Category” of the advanced menu type “Category Menu”. (You can call the new section anything that you want to, but “Category” will work with the demo code below)
Under Admin > Section Editors > Your Category Section > Viewer URLs - set both the List page and Detail page viewer URLs to /categoryList.php
Now add some Main Category and some Sub Category records, using the “Parent Category” pull down menu to organize them. (The list will automatically grow with Parent and Child categories after you create new records).
Enter some descriptive text in the content fields, like “this is the description of Main Category 1, this is the description of sub category 1, etc. so that you can follow the results.
Click on the up and down “order” links to reorder the records. (Changing the order of a parent category moves the entire category up or down)
Now create a sample List Page viewer called categoryList.php
At the top of your page
<?php require_once "your server _path /cmsAdmin/lib/viewer_functions.php"; list($categoryRecords, $selectedCategory) = getCategories(array( 'Table name' => 'category', 'selectedCategoryNum' => '', // defaults to getNumberFromEndOfUrl() 'categoryFormat' => 'showall', // showall, onelevel, twolevel )); ?>
Use this code where you want the category menu to appear:
<!-- category menu --> <h3>Nested Menu</h3> <?php foreach ($categoryRecords as $categoryRecord): ?> <?php echo str_repeat(" ", $categoryRecord['depth']); ?> <?php if ($categoryRecord['_isSelected']): ?><b><?php endif; ?> <a href="<?php echo $categoryRecord['_link'] ?>"><?php echo $categoryRecord['name'] ?></a> <?php if ($categoryRecord['_isSelected']): ?></b><?php endif; ?> <br /> <?php endforeach; ?> <!-- /category menu -->
OR - use this code to display the menu in <ul> format:
<!-- unordered list --> <h3>Unordered List Menu</h3> <ul> <?php foreach ($categoryRecords as $categoryRecord): ?> <?php echo $categoryRecord['_listItemStart'] ?> <?php if ($categoryRecord['_isSelected']): ?> <b><a href="<?php echo $categoryRecord['_link'] ?>"><?php echo $categoryRecord['name'] ?></a></b> <?php else: ?> <a href="<?php echo $categoryRecord['_link'] ?>"><?php echo $categoryRecord['name'] ?></a> <?php endif; ?> <?php echo $categoryRecord['_listItemEnd'] ?> <?php endforeach; ?> </ul> <!-- /unordered list -->
And then use this code to display the selected category:
<?php if (!$selectedCategory): ?> No record selected <?php endif; ?> <?php if ($selectedCategory): ?> <h3><?php echo $selectedCategory['name'] ?></h3> <?php echo $selectedCategory['content'] ?> <?php endif; ?>
Those are the basics of using the Category Menu feature that’s built in to Version 1.20 and above.
According to Dave Edis at Interactive Tools, you can control which field is displayed in the URL before the "id" by setting "filename fields" under: Section Editors > Viewer URLS.
The simplest solution might be to just set this to 'name' instead of 'breadcrumb'
But by default it will use 'breadcrumb' and convert non-word characters to "-" so if you have a breadcrumb of: News : Technology : Web. So it becomes: News-Technology-Web
You can also create the links in whatever format you like instead of using _link. For example if you created a fieldname called filename you could have:
<a href="/path/to/viewer.php?<?php echo $categoryRecord['filename'] ?>-<?php echo $categoryRecord['num'] ?>">
To link as:
viewer.php?filename-here-123
You can learn more about using the Category Menu feature from the posts at:
http://www.interactivetools.com/forum/gforum.cgi?post=64259
If any of you have found interesting ways to use this feature, please share them in an e-mail to:
cookbook@thecmsbcookbook.com
Thanks
|
USING “RESERVED” MYSQL WORDS FOR FIELD NAMES - Mar 24th, 2015
A number of field names are “reserved” words in the MySQL world. If you use one of them by mistake, you may get a MySQL error similar to:
MySQL Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use...
It’s a pretty long list , and you can find it at:
http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html
If you must use one of those words as a field name, Dave Edis from Interactive Tools has a suggestion. He says, '' A trick for dealing with those is either renaming the field -or- surrounding it with `backticks` (beside the 1 on most keyboards). Since ''show'' is a reserved word, you’d surround it with backticks like this:
'where' => 'active ="1"' . ' AND `show` ="1" ',
Backticks are a way of telling MySQL that you mean a table or fieldname and not anything else.
Most of the time it's just easier to rename the field, though. :)''
|
DUPLICATING A RECORD INSTEAD OF RE-ENTERING THE DATA - Dec 29th, 2018
NOTE: This function has been turned into a free plugin that you can access at
http://www.interactivetools.com/add-ons/detail.php?Save-Copy-Button-1030
This plugin requires at least CMSB Version 2.11. The information below is implementation into earlier versions.
User blukabm was curious if there was a way to duplicate a record. “That way I could modify the copied record instead of creating a new one and re-entering data that won't change much.”
Dave Edis from Interactive Tools came up with an answer for both versions before and after 2.x
He said:
“Here's an (unsupported) hack I wrote up to add a "Save as Copy" button to the bottom left of the edit page.
(Note:) It doesn't support uploads or all the field types.”
- Create a backup copy of /lib/menus/default/edit.php - Open /lib/menus/default/edit.php
FOR CMSB VERSIONS PRIOR TO 2.X
- Search for: showWysiwygGeneratorCode
- Add this code:
<td> <input type="submit" name="action=save" value="<?php _e('Save as Copy') ?>" onclick="document.getElementById('num').value=''; document.getElementById('preSaveTempId').value='1234567890abc'" class="inputButton" /> </td>
to the existing code(about 15 lines above showWysiwygGeneratorCode)
<table border="0" cellspacing="0" cellpadding="0" width="690"> <tr> <!-- Insert This Code --> <td> <input type="submit" name="action=save" value="<?php _e('Save as Copy') ?>" onclick="document.getElementById('num').value=''; document.getElementById('preSaveTempId').value='1234567890abc'" class="inputButton" /> </td> <!-- End of Insert--> <td align="right"> <input type="submit" name="action=save" value="<?php _e('Save') ?>" class="inputButton" /> <input type="button" name="cancel" value="<?php _e('Cancel') ?>" class="inputButton" onclick="window.location='?menu=<?php print urlencode($menu) ?>'" /> </td> </tr> </table> </form> <?php showWysiwygGeneratorCode() ?>
FOR CMSB VERSION 2.X AND ABOVE
search for: "_action=save"
HINT: It occurs in 2 places line 34 and line 72 Add this code to the existing code in both places.
<input type="submit" name="action=save" value="<?php et('Save As Copy') ?>" onclick="document.getElementById('num').value=''; document.getElementById('preSaveTempId').value='1234567890abc'" class="button" />
<div style="float:right"> <!-- Insert This Code --> <input type="submit" name="action=save" value="<?php et('Save As Copy') ?>" onclick="document.getElementById('num').value=''; document.getElementById('preSaveTempId').value='1234567890abc'" class="button" /> <!-- End of Insert--> <input class="button" type="submit" name="_action=save" value="<?php et('Save') ?>" /> <input class="button" type="button" name="cancel" value="<?php et('Cancel') ?>" onclick="window.location='?menu=<?php print urlencode($menu) ?>'" /> </div>
|
CREATE MULTIPLE RECORDS WITH ONE MYSQL QUERY - May 8th, 2011
If you need to populate a database with multiple records, instead of creating each record individually, you can create a MySQL query in your word processor and then create all the records and populate all the fields at once.
Here’s how:
Create a new PHP document and load the viewer_functions.php with this code at the top of your page (don’t forget to change the server path information), or copy the code block from one of your other viewers.
<?php header('Content-type: text/html; charset=utf-8'); ?> <?php /require_once "/path_to_your/cmsAdmin/lib/viewer_functions.php";
Then for adding values to a single field use this format:
$query = "INSERT INTO cms_table_name (field_1) VALUES
(‘field_1_value1'), (‘field_1_value2’), (‘field_1_value3’), (‘field_1_value4’)”; mysql_query($query) or die("MySQL Error: " .mysql_error(). " with query $query\n");
?>
If you wanted to populate 2 fields at the same time, you’d use:
$query = "INSERT INTO cms_table_name (field_1,field_2) VALUES
(‘field_1_value1',‘field_2_value1'), (‘field_1_value2’,‘field_2_value2'), (‘field_1_value3’,‘field_2_value3'), (‘field_1_value4’,‘field_2_value4')”; mysql_query($query) or die("MySQL Error: " .mysql_error(). " with query $query\n");
?>
NOTE 1: There is no comma after the last set of values. NOTE 2: Unless you’ve changed the default prefix for your table names, the correct cms_table_name format in the MySQL query for a table called “articles” would be cms_articles NOTE 3: If you execute the query more than once, you'll insert more than one set of records into your table.
EXAMPLES:
To Insert individual records for all 50 United State's State names (plus the District of Columbia) into a table called "states" with fields for State and Country you can use the following MySQL query:
$query = "INSERT INTO cms_states (state,country) VALUES
('Alabama','UNITED STATES'), ('Alaska','UNITED STATES'), ('Arizona','UNITED STATES'), ('Arkansas','UNITED STATES'), ('California','UNITED STATES'), ('Colorado','UNITED STATES'), ('Connecticut','UNITED STATES'), ('Delaware','UNITED STATES'), ('District of Columbia','UNITED STATES'), ('Florida','UNITED STATES'), ('Georgia','UNITED STATES'), ('Guam','UNITED STATES'), ('Hawaii','UNITED STATES'), ('Idaho','UNITED STATES'), ('Illinois','UNITED STATES'), ('Indiana','UNITED STATES'), ('Iowa','UNITED STATES'), ('Kansas','UNITED STATES'), ('Kentucky','UNITED STATES'), ('Louisiana','UNITED STATES'), ('Maine','UNITED STATES'), ('Maryland','UNITED STATES'), ('Massachusetts','UNITED STATES'), ('Michigan','UNITED STATES'), ('Minnesota','UNITED STATES'), ('Mississippi','UNITED STATES'), ('Missouri','UNITED STATES'), ('Montana','UNITED STATES'), ('Nebraska','UNITED STATES'), ('Nevada','UNITED STATES'), ('New Hampshire','UNITED STATES'), ('New Jersey','UNITED STATES'), ('New Mexico','UNITED STATES'), ('New York','UNITED STATES'), ('North Carolina','UNITED STATES'), ('North Dakota','UNITED STATES'), ('Ohio','UNITED STATES'), ('Oklahoma','UNITED STATES'), ('Oregon','UNITED STATES'), ('Pennsylvania','UNITED STATES'), ('Rhode Island','UNITED STATES'), ('South Carolina','UNITED STATES'), ('South Dakota','UNITED STATES'), ('Tennessee','UNITED STATES'), ('Texas','UNITED STATES'), ('Utah','UNITED STATES'), ('Vermont','UNITED STATES'), ('Virginia','UNITED STATES'), ('Washington','UNITED STATES'), ('West Virginia','UNITED STATES'), ('Wisconsin','UNITED STATES'), ('Wyoming','UNITED STATES')";
mysql_query($query) or die("MySQL Error: " .mysql_error(). " with query $query\n"); ?>
|
DRAG SORT QUICKLY TO TOP (OR BOTTOM) OF A FIELD LIST, RECORD LIST OR IMAGE LIST INCLUDING MOVING BY PAGE - Aug 19th, 2022
This one's from Chris Waddell from Interactive Tools:
Maybe this trick is obvious to some, but I've found myself taking forever to move items to the top of a long list by dragging a page-length, scrolling the page, dragging a page-length, scrolling the page, etc.
Here's a much faster method:
1. Click and hold the item you want to move, and start dragging the item down (or up) in the list until it's between 2 fields. 2. While continuing to hold the item with the left mouse key, Press the <END>, <PAGE UP>, <PAGE DOWN>, or <HOME> key on your keyboard (this will scroll the visible part of the list to (near) the new location on the list. NOTE:As long as you don't let go of the mouse button, you can combine <END>, <PAGE UP>, <PAGE DOWN>, or <HOME> commands as many times as necessary to get you near the place you want to drop the field. 3. Make sure that the dragged item is visible at the new location on the list (if necessary, drag it up or down slightly to make it visible) 4. Drop the item (release the left mouse key).
Being between field locations before using the navigation commands and visibility before letting go seems to be keys, along with a little practice.
Dave Edis from Interactive Tools added:
"So that works because the images are listed in an iframe. So any keyboard shortcuts that jump you to the top/bottom of a page will work.
If it's not working in the iframe you can try making sure that you've clicked on something in the iframe first so the browser knows which page to navigate. And you can also try ctrl-home, ctrl-end or the mac equivalents. It may be limited by the browser, though, but that's what's happening. Just find keyboard shortcuts for navigating the page."
According to Daniel Louwe, Technical lead at Interactive Tools,
While it's not currently possible to "Quick Add" in a specific location, as of CMSB v3.52 the section editor does have an "Insert Field Here" feature. Hovering over a row in the field list will show a "(+)" along the right-hand side. Clicking this allows you to insert a field at that spot.
|
CREATING USER FRIENDLY MENUS
|
USING V1.33 + MENU ENHANCEMENTS - Aug 2nd, 2010
These are some really cool enhancements, but it took a bit of playing around to really get the picture.
The first thing that you’ll notice when you upgrade (or install) to v1.33 or above is that when you click on Admin, instead of an Admin home page that lists all of your admin options, you’ll see an accordion style menu. When you click on one of these options you’ll get to the associated admin function. Cool you say, but how do I create one of these for my users?
Enter Menu Groups: Lets say that you’ve got a series of product categories and each one has it’s own section editor. Up to now, no matter whether you’re client is thinking of updating one of these products or not, they will see the whole list of product section editors and may have to scroll past them to find the editor that they really want to modify.
1) log in as Admin, 2) click on the “Admin” menu group and then on “section editors”. 3) click on “Add New Editor” (a bit counterintuitive, but it works nonetheless. 4) Instead of creating a new editor, click on the “Advanced Menus” pull down and choose “Menu Group”. 5) Enter the group name you want into the “Menu Name” field. 6) click on “Create New Menu” and the group heading will appear in your section editor list.
Now here’s the best part.
Any existing section editors that are below this heading in the list, (and before the next Group Menu) will automatically become part of this group, and when you click on the group heading the group will expand and show its members.
Even better, any other expanded group will collapse, so there’s less clutter to confuse a user.
If you combine this ability with the “Indent on menubar” option on the section editor’s “modify” page (which does exactly what is says) and “Separator” fields that you can add to any section editor, you can really get some serious organization going.
Now, how about Text Links”. To quote Dave Edis::” You can now add text links to the menu bar that link to external sites or any url. This makes it easier to provide links to other applications or services your clients might need and more tightly integrate your system with CMSB. This is great for adding links back to your company website (for your clients), your support page, and links to any other control panels or web applications the client might need to access.
So how do I do this? Really simply.
1) As you did with the Group Menus, go to “Add New Editor”, click on the “Advanced Menus” pull down but this time choose “Text Link”. 2) In the “Menu Name” field enter the words that you want to appear on the item in the menu list. You could choose Help with Products, Go to my Web Site, or whatever you want. 3) When you click on “Create New Menu” the text link will appear in your section editor list. 4) Click on “Modify” and enter the URL that you want the link to lead to. 5) Save and then just as you would with other section editors, drag the link item in the section editor list to where you want it to appear in the menu.
The difference is that when you click on the menu item, it will open the URL that you specified in a new browser window.
So, now you can create as many “context sensitive” links for your clients as you like.
|
CHANGING HIDDEN FIELD TO DISPLAY YES/NO INSTEAD OF “0" /"’1" (LEGACY) - May 7th, 2011
Jason from RentItToday asked if it was possible to change the 0 and1 that displays as the hidden field value in the record list to something more meaningful. (This is incorporated in all current versions)
Dave answered with a resounding “YES”. He said, “ Just make sure you're using a recent version of CMS Builder and try setting the checked and unchecked value for the "hidden" field in the field editor to “Yes” and “No” (without the double quotes) under: Admin > Section Editors > Your Section > Hidden
Sometimes the simplest solutions are not the most obvious.
|
USING MYSQL QUERIES IN LIST FIELDS - Oct 30th, 2015
For this example, create a multi record section called "rules_list" with only one text field called "rules"
Then create another multi record section with one list field called "test" and choose "Get options from mySQL Query (Advanced)" from the list options pull down.
You'll be presented with this generic query as an example.
SELECT field1, field2 FROM `<?php echo $TABLE_PREFIX ?>your_table`
field1 is the equivalent of the "Options Value" field2 is the equivalent of the "Options Label" that will be displayed your_table is the name of the section to pull these options from.
In this case, the section you'll get your options labels and options values from is the rules_list" table so enter "rules_list" in place of your_table in the sample code You'll be getting the Options Labels from the text field called "rules" so enter that as field2 Your options values will come from the "record number" so enter num as field1.
Your query should now look like this:
SELECT num, rule FROM `<?php echo $TABLE_PREFIX ?>rules_list`
If you want to filter your list into groups you can add a new list field called "group" to the "rules_list" table, with the sample values, Guidelines, Presentation Rules, and Required Entry Materials.
Then you can list only those records where the "group" field contains the text between the % signs below.
This example, we want to list all of the records that have Guidelines selected as the "group" value, so enter "guide" between the % signs as below
SELECT num, rule FROM `<?php echo $TABLE_PREFIX ?>rules_list` WHERE `group` LIKE '%guide%'
To list only those records that are part of the "Required Entry Materials" group, change the characters between the % signs to "reqi" or "mater"
Just make sure that the character string is unique to that group.
NOTE There are 2 sets of back ticks (under the tilde character "~") and one set of single quotes used in the code.
|
SHOW MULTIPLE FIELD VALUES FOR LIST OPTION LABELS IN A MULTI- VALUE LIST FIELD USING ‘GET OPTIONS FROM MYSQL QUERY’ - Nov 7th, 2017
The task was to show the field values for both the 'presentation_date' and the 'presentation_title' for the option labels in a multi-value list field that pulled information from the table 'all_presentations'.
In a post on the forum, Daryl Maximo, a programmer at Interactive Tools suggested that I could add two or more field values for my list option labels by using "Get options from MySQL query (advance)" instead of "Get options from database (advance)" and use CONCAT() to combine two or more columns.
Here’s the final query code:
SELECT num, CONCAT(DATE_FORMAT(`presentation_date`, '%b %D, %Y'), ' - ', presentation_title) FROM `<?php echo $TABLE_PREFIX ?>all_presentations` WHERE hidden = 0 ORDER BY presentation_date DESC
|
CHAPTER 2 - VIEWERS
|
VIEWERS-CODING
|
IMPLEMENTING CLIENT PREVIEW VIEWERS (LEGACY) - May 7th, 2011
As of Version 2.07, a "preview" function is built in to the program that allows an author to see how their live page will look before it goed "live".
For those of you who for some reason are using an earlier version of CMS Builder, Dave Edis from Interactive Tools had an interesting and simple workaround.
He suggested adding a "hidden" check box to the editor, and hide the record from the "real" page until you're satisfied with the contents.
To see a "preview" of the contents, make a copy of your detail viewer and use this option in the record call in the head section which will ignore the "hidden" flag and show records even if they are hidden:
'ignoreHidden' => true, // don't hide records with hidden flag set
or
'where' => " hidden = '1' ",
|
WRAPPING TEXT AROUND AN IMAGE - Dec 25th, 2018
Here’s a simple way to wrap an image in the first few lines of text, like a head shot surrounded by descriptive text on an about page.
The concept depends on some css to wrap the text around the image.
<style type="text/css"> .pad { border-right: 20px solid transparent; } .padr { padding-right:20px; } </style>
And in the body:
<div style="float:left"><div class="padr" style="float:none"> <?php foreach ($record['head_shot'] as $index => $upload): ?><img src="<?php echo htmlencode($upload['thumbUrlPath2']) ?>" width="<?php echo $upload['thumbWidth2'] ?>" height="<?php echo $upload['thumbHeight2'] ?>" alt="" /><?php endforeach ?></div> </div> <div><?php echo $record['content'] ?></div>
You can see a screen shot of the result here: http://www.thecmsbcookbook.com/downloads/image-wrap.jpg
|
CHANGING METATAG OR OTHER DATA FROM WITHIN CMSB - Aug 2nd, 2010
One key is that this type of information is usually best called from a single record editor. The good news is that you can simultaneously use information from any combination of editors to populate your web pages.
The first step is to create the fields required for the information. So say your single record section editor is called "Pages". You would go into: Admin > Section Editors > Pages and add a new textfield called "Page Title", one called “Meta Keywords” and a third called “Meta Description”, and save the result and the detail. Now go to your section editor and enter the values that you’d like to appear in these fields. (Remember to follow the syntax conventions required for the particular field)
You'll have tags in your viewer page that look like this:
<?PHP echo $pagesRecord['page_title']; ?> <?PHP echo $pagesRecord['meta_keywords']; ?> and <?PHP echo $pagesRecord['meta_description']; ?>
In your web page, you would display your field information like this:
<title><?PHP echo $pagesRecord['page_title']; ?> </title> <META NAME="KeyWords" CONTENT="<?PHP echo $pagesRecord['meta_keywords']; ?>"> <META NAME="Description" CONTENT="<?PHP echo $pagesRecord['meta_description']; ?>">
You can use this approach to populate (almost) any html tag information. (I’m sure that there’s one that won’t work somewhere.)
|
USING CMSB TO CUSTOMIZE LINK INFORMATION IN A LIST - Aug 2nd, 2010
You can replace the link text and URL in a link, or any other area in an HTML document by placing a PHP call in place of the area you want to make variable, and creating textfields in a multi record section editor. Here’s an example of making the text and url in a link variable:
<?PHP foreach ($other_eventsRecords as $record): ?> <p align="left"><a class="special" href="<?PHP echo $record['url'] ?>"><?PHP echo $record['organization_name'] ?></a><br /> <?PHP endforeach ?> If you’re going to use this to display a list of links on your web page, don’t forget to remove the:
'where' => whereRecordNumberInUrl(1), 'limit' => '1',
and
$other_eventsRecord = @$other_eventsRecords[0]; // get first record
from the code before the head or you’ll only show a single listing on your page.
|
FIXING VIEWER SHOWING ONLY THE FIRST RECORD - Aug 2nd, 2010
If you’re only seeing information on the first record and not on subsequent records, or you’re getting “Undefined index” errors about fields you know exist, you’re not alone.
According to Dave Edis, of Interactive Tools the fix may be really simple. He says:
What may be happening is that the line:
'where' => whereRecordNumberInUrl(1),
in the “required” code at the top of the page is trying to load the record number that is on the end of the url:
list($your_tableRecords, $your_tableMetaData) = getRecords(array( 'Table name' => 'your_table', 'where' => whereRecordNumberInUrl(1), 'limit' => '1', ));
So when the URL ends in 1 (or nothing) that works fine, but when it's another record number, it won't work. Try removing that ‘where’ line:
Dave added: You can also, add:
allowSearch => false,
so later when you add searching capability it won't "pre-filter" those records, since he’s assuming you’ll want to show them all the time:
list($your_tableRecords, $your_tableMetaData) = getRecords(array( 'Table name' => 'your_table', 'limit' => '1', 'allowSearch' => false, ));
|
FIXING WEIRD RESULTS IN A MULTI RECORD VIEWER - Aug 2nd, 2010
The placement of "foreach" and "endforeach" elements can make a huge difference in how a list of records appears in your viewer. If your results are not what you expected, before you panic, check the placement of those elements.
For example, if the elements are outside your table, a new table will be created for each record. You can place the "foreach"elements between a <tr> and a <td>, or anyplace else in the table code, but they're very literal, so everything between the "foreach" and the "endforeach" will be recreated for each record.:
If tyhat's not what you had in mind, make sure that the:
<?PHP foreach ($your_table_nameRecords as $record): ?> and <?PHP endforeach ?>
elements are inside your table. Like this:
<table> <?PHP foreach ($your_table_nameRecords as $record): ?> <tr> <td><div align="left"><span class="your_css" ><?PHP echo date("D, M jS, Y g:i a", strtotime($record['your_first_ field'])) ?></span></div></td> <td><div align="left"><span class="your_css" >Location: <?PHP echo $record['l your_second_ field'] ?></span> </div> </td> </tr><?PHP endforeach ?> </table>
|
DISPLAY LINKS ON YOUR WEB PAGE WITHOUT ERRORS - Nov 23rd, 2012
REVISED TO ACCOMMODATE HTTPS:// WEBSITE URLs
If a link URL is entered into a textfield without an http://, you'll end up with a broken link when you try to follow that link in you viewer.
Here’s how to make sure that your URL’s work, even if the person entering the information doesn’t enter http://
Note: The solution in this recipe is not case sensitive. This means that if you’ve entered HTTP:// , or Http:// the code will still work.
In this example the code is designed for use with a single field. The field containing the URL is called web_site_link_url, and the field containing the link text is called web_site_link_text.
Once you understand the concepts involved, to use this for multiple link fields in the same viewer, see USING A FUNCTION TO ACCOMPLISH THE SAME RESULT, later in this recipe.
An "if" statement is used to check if the URL starts with http:// and if not, it adds one to the beginning of the URL.
So, for a multi-record list viewer, you’d put the if statement before the link code in the viewer like this:
<?php if(!preg_match("/^https:\/\//i", $record['web_site_link_url'] )):?> <?PHP if (!preg_match("/^http:\/\//i", $record['web_site_link_url'])) { $record['web_site_link_url'] = "http://" . $record['web_site_link_url']; } ?>
<?PHP endif ?>
<a href="<?PHP echo $record['web_site_link_url'] ?>"><?PHP echo $record['web_site_link_text'] ?></a>
And for a detail viewer:
<?php if(!preg_match("/^https:\/\//i", $yourRecord['web_site_link_url'] )):?> <?PHP if (!preg_match("/^http:\/\//i", $yourRecord['web_site_link_url'])) { $yourRecord['web_site_link_url'] = "http://" . $yourRecord['web_site_link_url']; } ?> <?PHP endif ?> <a href="<?php echo $yourRecord['web_site_link_url'] ?>"><?php echo $yourRecord['web_site_link_text'] ?></a>
Or if you’re using one of the info fields in an upload to contain the URL:
<?php if(!preg_match("/^https:\/\//i", $upload['info1'] )):?> <?php if (!preg_match("/^http:\/\//i", $upload['info1'])) { $upload['info1'] = "http://" . $upload['info1']; } ?><?php endif ?>
<a href="<?php echo $upload['info1'] ?>"><img src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" alt="" /></a>
Or for a single record viewer:
<?php if(!preg_match("/^https:\/\//i", $your_tableRecord['web_site_link_url'] )):?> <?PHP if (!preg_match("/^http:\/\//i", $your_tableRecord['web_site_link_url'])) { $your_tableRecord['web_site_link_url'] = "http://" . $your_tableRecord['web_site_link_url']; } ?> <?php endif ?> <a href="<?php echo $your_tableRecord['web_site_link_url'] ?>"><?php echo $your_tableRecord['web_site_link_text'] ?></a>
PLACEMENT ON THE PAGE As long as the preg_match PHP code is before the link code, this technique will work. So, for consistency, you might want to insert all you preg_match PHP code blocks at the top of your <body> code.
HOW IT WORKS
The first line is an if statement that surrounds the rest of the regex operations
<?php if(!preg_match("/^https:\/\//i", $record['web_site_link_url'] )):?>
This statement looks for https:// at the beginning of a field called “web_site_link_url“.
If https:// is not found then the next line is executed.
(The “i” make the expression case insensitive. If you want to make it case sensitive, just remove the “i”)
!preg_match("/^http:\/\//i", $record['web_site']
This code looks for http:// at the beginning of a field called “web_site_link_url“.
(Again, the “i” make the expression case insensitive. If you want to make it case sensitive, just remove the “i”)
If http:// is not found (! = NOT) then the next line adds it to the beginning of 'web_site_link_url:
$record['web_site_link_url'] = "http://" . $record['web_site_link_url']
This line uses the concatenation operator, which is just a dot (.) The above expression can be thought of like 2 = 1 + 1 or in our case maybe http://www.cnn.com = (http://) + (www.cnn.com)
The end if statement <?PHP endif ?> ends the conditions that must be met.
The last line would go where you want the link to appear, as ling as it's below the if statement.
<a href="<?PHP echo $record['web_site_link_url'] ?>"><?PHP echo $record['web_site_link_text'] ?></a>
This displays the $record[web_site_link_ur] as the link and the $record['web_site_link_text'] as the link text.
USING A FUNCTION TO ACCOMPLISH THE SAME RESULT Instead of having to duplicate the code and change the field name, you can use a function that can easily be called for each occurrence.
Just remember to insert the function before and outside of any foreach loops that require it.
<?php function ensure_url($url) { if(!preg_match("/^https:\/\//i", $url )) { if (!preg_match("/^http:\/\//i", $url)) { $url = "http://" . $url; } } return $url; } ?>
Then, each time you need to check the format of a link, call the function like this:
<?php echo ensure_url($record['your_link_field']) ?>
or
<?php echo ensure_url($your_tableRecord['your_link_field']) ?>
Here's a Regex quick reference to help you to customize your regular expressions to meet your needs
[abc] A single character: a, b or c [^abc] Any single character but a, b, or c [a-z] Any single character in the range a-z [a-zA-Z] Any single character in the range a-z or A-Z ^ Start of line $ End of line \A Start of string \z End of string . Any single character \s Any whitespace character \S Any non-whitespace character \d Any digit \D Any non-digit \w Any word character (letter, number, underscore) \W Any non-word character \b Any word boundary character (...) Capture everything enclosed (a|b) a or b a? Zero or one of a a* Zero or more of a a+ One or more of a a{3} Exactly 3 of a a{3,} 3 or more of a a{3,6} Between 3 and 6 of a
options: i case insensitive m make dot match newlines x ignore whitespace in regex o perform #{...} substitutions only once
|
DISPLAYING ONLY CERTAIN CATEGORIES AND/OR ALPHABETICAL LIMITATIONS - Aug 27th, 2010
I had an Artist’s membership database and I wanted to allow searches for specific categories of artists (disciplines) or limit a search to particular alphabetical criteria.
The disciplines field contained a V" for Visual Artists, "M" for Media Artists, "P" for Performance Artists, "L" for Literary Artists
Here’s the link code:
http://www.mysite.com/visualartists.php?sort_discipline=V
Which works to search for visual artists when combined with the code at the head of the visualartists.php web page
<?PHP require_once "/hsphere/local/home/web/mysite.com/cmsAdmin/lib/viewer_functions.php";
list($artistsRecords, $artistsMetaData) = getRecords(array( 'Table name' => 'artists', // Insert This Code 'where' => "discipline_code LIKE '%" .mysql_real_escape_string(@$_REQUEST['sort_discipline']). "%'", // End of Insert )); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>
Of course you’ll have to replace the path information with your own.
NOTE: The word "sort" is not necessary in the link code or $_REQUEST, it's just a visual indicator that you are sorting by a specific criteria. the request can be anything as long as you're consistent.
If you need to meet multiple parameters, then you could change the link to:
http://www.mysite.com/visualartists.php?sort_letter=A&sort_discipline=V
An extra % after LIKE will match the occurrence of that letter anywhere in the field:
'where' => "last_name LIKE '%" .mysql_real_escape_string(@$_REQUEST['sort_discipline']). "%'", 'where' => "last_name LIKE '%" .mysql_real_escape_string(@$_REQUEST['sort_letter']). "%' AND discipline_code = '" .mysql_real_escape_string(@$_REQUEST['sort_discipline']). "'",
This format will match the first letter of the fields only...
'where' => "last_name LIKE '" .mysql_real_escape_string(@$_REQUEST['sort_discipline']). "%'",
or
'where' => "last_name LIKE '" .mysql_real_escape_string(@$_REQUEST['sort_letter']). "%' AND discipline_code = '" .mysql_real_escape_string(@$_REQUEST['sort_discipline']). "'",
For a message regarding no members found, you could add:
<?PHP if (!$artistsRecords): ?> <div class="body-text-bold" align="center"><?PHP echo "Sorry, but no active members were found who match this category.<br /><br />"; ?> <?PHP endif ?><div>
|
SETTING UP IF/THEN CONDITIONS - Aug 2nd, 2010
This time it was me that was in need of some guidance and Dave Edis from Interactive Tools was able to help.
Here was my situation: I had set up a multi record section editor and included a pull down list field with a list of categories. IE: “book, CD, Magazine, etc.
(BTW, the difference between a simple pull down list and a multi value pull down list is that in a multi value pull down if you hold the CTL key you can select more than one value)
Here’s what I was trying to do:
If the group_code of the particular record is “book” then I wanted to display field “A”, if it’s “CD” I’d like to display field “B”, if it’s “magazine” I’d like to display field “C”, and if it’s none of those I’d like to display field “D”.
The task is pretty straightforward once you know the correct format to use.
If you’re using it on multi record a list page:
<?PHP foreach ($pub_category_listRecords as $record): ?> <?PHP if ($record['group_code'] == "book"): ?> <?PHP echo $record['fieldA'] ?> <?PHP elseif ($record['group_code'] == "CD"): ?> <?PHP echo $record['fieldB'] ?> <?PHP elseif ($record['group_code'] == "Magazine"): ?> <?PHP echo $record['fieldC'] ?> <?PHP else: ?> <?PHP echo $record['fieldD'] ?> Sorry, couldn't find a match for '<?PHP echo $record['group_code'] ?>' <?PHP endif ?> <?PHP endforeach; ?>
And if it’s on a single page or a detail page:
<?PHP if ($pub_category_listRecord['group_code'] == "book"): ?> <?PHP echo $pub_category_listRecord['fieldA'] ?> <?PHP elseif ($pub_category_listRecord['group_code'] == "CD"): ?> <?PHP echo $pub_category_listRecord['fieldB'] ?> <?PHP elseif ($pub_category_listRecord['group_code'] == "Magazine"): ?> <?PHP echo $pub_category_listRecord['fieldC'] ?> <?PHP else: ?> <?PHP echo $pub_category_listRecord['fieldD'] ?> Sorry, couldn't find a match for '<?PHP echo $pub_category_listRecord['group_code'] ?>' <?PHP endif ?>
You can use this to display anything that you want to, in another situation I’m using it to display different thumbnail groups for different group codes. Just replace the <?PHP echo $record['fieldn'] ?> codes with the code that will display what you want to.
There’s much more on understanding and using if statements later in the Cookbook.
|
SHOWING HIDDEN RECORDS IN A VIEWER - Aug 2nd, 2010
If you need to show a list of the records that have been hidden using the special ‘hidden’ field, you’ll need to put a set of ‘where’ statements in the getrecords() block at the top of your viewer page.
list($artistsRecords, $artistsMetaData) = getRecords(array( 'Table name' => 'artists', // Insert This Code 'where' => " hidden = '0' ", 'orWhere' => " hidden = '1' ", )); // End of Insert
Then you can use the ‘if’ statements:
<?PHP if ($record['hidden'] == '1'): ?> and <?PHP if ($record['hidden'] == '0'): ?>
after your ‘foreach ‘statements to show the records that match either criteria, like this:
<?PHP foreach ($artistsRecords as $record ): ?> <?PHP if ($record['hidden'] == '1'): ?> <?PHP echo $record['last_name'] ?>, <?PHP echo $record['first_name'] ?> <?PHP endif ?> <?PHP endforeach; ?>
I was curious, why is it necessary to use the 'where' statements in the getRecord() block for the "hidden" field and not necessary for any regular fields?
According to Dave Edis from Interactive Tools: The "hidden" field is a special field. Anytime it exists CMS Builder automatically adds "WHERE hidden = 0" to the query. You can see the MySQL query CMS Builder creates by temporarily adding this option below the others:
'debugSql' => true,
You can see a list of other "special" fieldnames here:
http://www.interactivetools.com/docs/cmsbuilder/special_fieldnames.html
Since the purpose and design of the “hidden” field is to hide those records, when you want to show them instead we need to do some extra work to make it work. :)
Thanks Dave, it makes sense now
|
OVERRIDING THE HIDDEN VALUE, PUBLISHDATE & REMOVEDATE TO SHOW RECORDS - Jul 31st, 2013
User In-House-Logic needed to override the hidden value and the publishStart & publishEnd date fields to show records on a web page.
Greg Thomas from Interactive Tools came to the rescue...
He said:
If you're using a getRecords function to retrieve your data you can get it to override the hidden and display before/after dates with these variables:
// load records from 'blog' list($blogRecords, $blogMetaData) = getRecords(array( 'tableName' => 'blog', 'loadUploads' => true, 'allowSearch' => false, 'ignoreHidden' => true, // don't hide records with hidden flag set 'ignorePublishDate' => true, // don't hide records with publishDate > now 'ignoreRemoveDate' => true, // don't hide records with removeDate < now ));
So these array keys tell the getRecords function to ignore the hidden field, publish and remove dates.
|
AUTOMATICALLY HIDE AND SHOW RECORDS BY DATE RANGE - Aug 2nd, 2010
You can automatically have records show and be hidden with the special fields 'publishDate' and 'removeDate'. You’ll want to create date fields for those.
Once that's done, your list should only show records within the date range, but if you only want to show the first matching record, add this to your viewer code
list($yourRecords, $yourDetails) = getRecords(array( 'Table name' => 'yourTable', // Insert This Code 'limit' => '1', // End of Insert ));
|
RESTRICTING VIEWER ACCESS TO LOGGED IN USERS ONLY - Dec 29th, 2018
If you're using a current version of CMSB (2.51+) Greg Thomas from InteractiveTools explains how to restrict access. He said:
There is a new getCurrentUserFromCMS function you can use to get the current CMS user, and it works if you're not using the website membership plugin on a site:
<?php if (!defined('START_SESSION')) { define('START_SESSION', true); } // load viewer library $libraryPath = 'cmsAdmin/lib/viewer_functions.php'; $dirsToCheck = array('/path_to_your_server/','','../','../../','../../../'); foreach ($dirsToCheck as $dir) { if (@include_once("$dir$libraryPath")) { break; }} if (!function_exists('getRecords')) { die("Couldn't load viewer library, check filepath in sourcecode."); } //Get the current CMS users details $CMS_USER = getCurrentUserFromCMS(); //redirect the browser if no user is currently logged into the back end if (!@$CMS_USER['num']){ redirectBrowserToUrl("http:/your_site.com/cmsAdmin/admin.php?redirectUrl=" . $_SERVER['REQUEST_URI']); exit; } ?>
*** LOG OUT ISSUES ***
Using this approach, you might discover a log out issue, especially If you're trying to restrict access to Admins only, or show information a page for users and additional information for admins.
If you do, a possible fix is in a companion recipe called LOG OUT NOT LOGGING OUT IN VER 2.51+ ? at http://thecmsbcookbook.com/recipedetail.php?475 LEGACY (Version 2.1+) If you surround your "require once" code with the 2 if statements, the page will be hidden from anyone who is not logged in to the CMS Interface and all they will see is a notice that says "You must login first".
if (!defined('START_SESSION')) { define('START_SESSION', true); } require_once "/path_to_your/cmsAdmin/lib/viewer_functions.php"; if (!@$_SESSION['username']) { die("You must login first!"); }
If you want to redirect your users to the login screen, replace the following line:
if (!@$_SESSION['username']) { die("You must login first!"); }
with this one:
if (!@$_SESSION['username']) { header("Location: http://mydomain.com/cmsAdmin/admin.php"); exit; }
and replace the URL with the (full) URL to your login screen.
Alternatively, to automatically direct the user back to your "hidden" page, you could use this instead:
if (!@$_SESSION['username']) { header("Location: http://mydomain.com/cmsAdmin/admin.php?redirectUrl=" . $_SERVER['REQUEST_URI']); exit; }
There are some interesting ways to create forms to "hide" the real location of the login screen that can be found on this post:
http://www.interactivetools.com/forum/gforum.cgi?post=73920
|
AUTO LOGOFF WITH REDIRECT - Apr 1st, 2017
In the Website Membership Plugin I had my post_logoff page set to a generic "log-out" page.
I was having trouble automatically logging a user out of the system and then automatically redirecting them to a special "log-out" page after they updated their profile.
Dave Edis, Senior Guru at Interactive Tools reminded me that the user_logoff() is an internal CMSB function and takes an optional redirect url as an argument.
So, in your profile update form, search for:
### Change Password
Before the brace "}" that precedes ### Change Password, insert the code
### Automatic Log Off and Redirect user_logoff("http://www.my_site.com/logout_index.php");
That will execute the logoff and redirect after the profile has been updated.
|
CREATING A SIMPLE PHP HIT COUNTER - Aug 2nd, 2010
For each page that you want to count hits on, create a text document with the number that you want your counter to start with, and a unique file name, like: aboutpagecounter.txt and upload it to your site.
I usually insert the number 500 in my text files, so that my counters will not display a really small number at first, but you can start them with any number you want to.
If you have many separate counters, you might want to create a folder for your counter text files.
Then somewhere in the body of the page that you want to count, insert this code, changing the file name and path to suit your particular situation:
<?php $count_my_page = ("aboutpagecounter.txt"); $hits = file($count_my_page); $hits[0] ++; $fp = fopen($count_my_page , "w"); fputs($fp , "$hits[0]"); fclose($fp);?>
Then, where you want your hit count to appear, insert this line of code:
<?php echo $hits[0]; ?>
You can, of course style your counter any way you want to.
|
CREATE A HIT COUNTER USING THE BUILT IN INCREMENTCOUNTERFIELD FUNCTION - Jul 24th, 2020
Using the built in incrementCounterField function, you can create a hit counter for a single record editor or a detail page of a multi record editor like this:
In the section editor, create a text field called 'hits' (or whatever you want to call it). Then insert this code on your viewer page.
<?php incrementCounterField('your_table_name', 'your_field_name', $your_table_name Record['num']); ?>
Or if you don’t want the counter to be incremented when the page is accessed by a particular IP Address (yours for example), try this recommendation by Chris Waddell from Interactive Tools:
<?php if ($_SERVER['REMOTE_ADDR'] != '127.0.0.1') { incrementCounterField('your_table_name', 'your_field_name', $your_tableRecord['num']); } ?>
Wherever on the viewer that you want to display the number of hits, insert this code as you would for any other field.
<?php echo $your_table_name['your_field_name '] ?>
LIST PAGE IMPLEMENTATION For a counter on the list page of a multi-record editor, the process gets a bit more complex. This is because if you used the approach above in a “foreach” loop, all the counters on all your records would increment each time the list page was accessed.
Create a table called “Counter” or something similar.
Create a text field for each list page that you want to count. Name the fields something that will be meaningful, preferably with the same name as the editor where you’ll be implementing the count.
Insert the record call to that table at the top of your viewer:
list($counterRecords, $counterMetaData) = getRecords(array( 'Table name' => 'counter', 'where' => whereRecordNumberInUrl(1), 'limit' => '1', )); $counterRecord = @$counterRecords[0]; // get first record
Then insert:
<?php incrementCounterField('counter', 'your_field_name', $counter Record['num']); ?>
Or again, if you don’t want the counter to be incremented when the page is accessed by a particular IP Address (yours for example), try this version of Chris’s recommendation:
<?php if ($_SERVER['REMOTE_ADDR'] != '127.0.0.1') { incrementCounterField('counter' 'your_field_name', $counterRecord['num']); } ?>
Into your viewer and:
<?php echo $counter['your_field_name '] ?>
Where you want the counter to appear.
As an added plus, you can enter any starting number in any of the counter fields and the count will begin from there, so none of your pages need to show only a small number of hits.
GOING FURTHER If you're using your counter to show how many times a particular record's detail page was viewed, you can insert your counter display into your list page code and have it appear only if an admin has logged in.
Here's how:
Put this code after your load records calls to determine if an admin is logged in.
<?php $CMS_USER = getCurrentUserFromCMS(); ?>
Then, in the body of the viewer, where you want the counter to appear, use this:
<?php if( $CMS_USER['isAdmin'] && $record['your_field_name'] > 0): ?>This page was viewed <?php echo $record['your_field_name'] ?> time<?php if($record[your_field_name'] == 1): ?><?php else :?>s<?php endif ?><?php endif ?>
If you wanted to decrement the counter, according to Chris Waddell from Interactive Tools:
There's nothing built-in, but you could copy the code, rename it, and change it to do what you want.
Here's an example. Call it with -1 as the fourth parameter to decrement a counter.
function incrementCounterFieldBy($tablename, $fieldname, $recordNumber, $amount = 1) { global $VIEWER_NAME; // error checking if (!$tablename) { die(__FUNCTION__ . ": No 'tablename' value specified!"); } if (!$fieldname) { die(__FUNCTION__ . ": No 'fieldname' value specified!"); } if (!$recordNumber) { die(__FUNCTION__ . ": No 'recordNumber' value specified!"); } // update counter $escapedTableName = mysql_escape(getTableNameWithPrefix($tablename)); $query = "UPDATE `$escapedTableName` SET `$fieldname` = IFNULL(`$fieldname`,0) + $amount"; $query .= " WHERE `num` = '" .mysql_escape($recordNumber). "'"; $result = @mysql_query($query); if (!$result) { die(__FUNCTION__ . " MySQL Error: ". htmlspecialchars(mysql_error()) . "\n"); } if (!mysql_affected_rows()) { die(__FUNCTION__ . ": Couldn't find record '" .htmlspecialchars($recordNumber). "'!"); } }
|
DISPLAYING THE FIRST X CHARACTERS ON A LISTING PAGE - Feb 27th, 2011
SAMSAM92 asked: If, for example I have a field <?PHP echo $record['your_field'] ?>, how would I show only the first 100 characters?
And the answer found was:
Just add this function at the top of the page:
<?PHP function textLimit($string, $length, $replacer = '...') { if(strlen($string) > $length) return (preg_match('/^(.*)\W.*$/', substr($string, 0, $length+1), $matches) ? $matches[1] : substr($string, 0, $length)) . $replacer;
return $string; }
?>
and then inside the foreach loop where you want to display your content:
<?PHP echo textLimit($record['your_field'], 100) ?>
You can change the 100 to any character count that you want.
Note:
If you're using this for a URL or anything with either a "." (period) or a "/" (forward slash) it won't work.
As soon as there's a fix, I'll post it here
|
DISPLAYING THE FIRST X CHARACTERS IN A WYSIWYG FIELD ON A LISTING PAGE - May 8th, 2011
User Deborah had this challenge.
She said: I am (trying to use) a cutText function to limit the number of characters in a WYSIWYG field. Because the WYSIWYG content automatically generates a closing </p> tag, I am unable to append a dot leader and "more" link such as this at the end of the snipped text:
<p>WYSIWYG content blah, blah, blah ... <a href="<?php echo $record['_link']; ?>”>Read More</a>></p>
The first step in using cutText is to define the function in the head section of your viewer.
<?php function cutText($string, $setlength) { $length = $setlength; if($length<strlen($string)){ while (($string{$length} != " ") AND ($length > 0)) { $length--;} if ($length == 0) return substr($string, 0, $setlength); else return substr($string, 0, $length);} else return $string; } ?>
But when Deborah tried to implement the cutText function and preg_replace to accomplish her goal, it resulted in this code:
<?php echo cutText($record['my_field']= preg_replace("|</p>\s*$|i", "...</p>", $record['my_field'] ), 90); ?>
but that did not work consistently.
Chris Waddell from Interactive Tools said:
Using the cutText() function (in this way) is (sometimes) stripping off the </p>. With no </p>, the preg_replace() can't find the right place to add the ...
For consistency, I'd recommend stripping the </p> off first, then calling cutText(), then adding your read more link, and finally replacing the </p> using the following code in the foreach loop:
<?php $html = preg_replace("|</p>\s*$|i", "", $record['my_field'] ); $html = cutText($html, 90); $html = $html . "...</p>"; echo $html; ?>
|
MAXWORDS - LIMITING THE NUMBER OF WORDS SHOWN ON A PAGE - Sep 2nd, 2011
If you use the character limiting function that’s exactly what you’ll get, and words can be cut off. But if you want to limit the word count, Dave Edis from Interactive Tools shares his usual uncanny wisdom:
Insert this function at the top of your page, or before you want to invoke the word limiting function:
<?PHP function maxWords($textOrHtml, $maxWords) { $text = strip_tags($textOrHtml); $words = preg_split("/\s+/", $text, $maxWords+1); if (count($words) > $maxWords) { unset($words[$maxWords]); } $output = join(' ', $words); return $output; } ?>
Then put this code where you want the words limited (to 5 words):
<?PHP echo maxWords($record['content'], 5); ?> If you want to add ...more and a link, use something like this:
<?PHP echo maxWords($record['content'], 5); ?>...<a href="<?php echo $record['_link']; ?>”>Read More</a>
or
<?PHP echo maxWords($record['content'], 5); ?>...<a class="read-more" href="http://www.your_site.com/your_detail_page.php?<?php echo $record['num'] ?>">(Read More)</a>
To allow certain tags like or <p> to appear in your text, change the strip_tags code:
$text = strip_tags($textOrHtml);
to
$text = strip_tags($textOrHtml, '<br />');
The function is pretty literal, but it seems to automatically include the closing tag, so include all the flavors of all the tags (spaces and slashes, slashes with no space, etc.) that you want to include. Like this:
$text = strip_tags($textOrHtml, '<br /><p>');
The strip_tags function is optional and is used to insure that extra tags, spaces, etc are not counted in the word count. If this is not a great concern (like if you're using text box fields, you can eliminate the line of code entirely.
WYSIWYG EDITORS If you’re using a WYSIWYG Editor and are losing some formatting when using the MaxWord function, Jason Sauchuk of Interactive Tools suggests using this version of the function instead:
<?PHP function maxWords($textOrHtml, $maxWords) { $text=str_replace("<p>","*P*",$textOrHtml); $text= str_replace("</p>","*/P*",$text); $text = strip_tags($text); $words = preg_split("/\s+/", $text, $maxWords+1); if (count($words) > $maxWords) { unset($words[$maxWords]); } $output = join(' ', $words); $output=str_replace("*P*","<p>",$output); $output=str_replace("*/P*","</p>",$output); $output.="</p>"; return $output; } ?>
If you want to display an alternate link text, or nothing if the field contains less words then you've specified, according to Jason, you'll first have get the actual number of words from your original string.
Here' a function he offered that goes through the same process as maxWords, but just returns the count. You'd add it to your code in addition to the maxWords function:
<?PHP function wordCount($textOrHtml) { $text = strip_tags($textOrHtml, "<b></b><i></i>"); $words = preg_split("/\s+/", $text); return count($words); } ?>
Then in your body code you can use this: (Since my client wanted to control the amount of words allowed in the maxWords call, I added a field called "words" in a single record editor called "common_information" and defined the variable $word1 to reflect that value )
<?php $word1 = $common_informationRecord['words'] ?> <?PHP echo maxWords($record['description'], $word1); ?> <?php if (wordCount($record['description']) > $word1) : ?>...<a href="<?php echo $record['_link']; ?>">Read More</a><?php endif ?>
You can also add alternative text or links using an <?php else :?> like this:
<?php if (wordCount($record['description']) > $word1) : ?>...<a href="<?php echo $record['_link']; ?>">Read More</a><?php else :?> <a href="<?php echo $record['_link']; ?>">Your Text Here</a><?php endif ?>
|
REDIRECTING A PAGE IF A CONDITION ISN’T MET - Mar 31st, 2015
According to Dave Edis at Interactive Tools, if you wanted to redirect a page if there were no records in a table, here’s how:
Just put this at the top of your page, after the get records call, and before any viewer code is output.
<?PHP list($your_tableRecords, $your_tableMetaData) = getRecords(array( 'tableName' => your_table',
));
if (!$your_tableRecords) { header("Location: http://www.example.com/newurl.php"); exit; } ?>
If you want to change this to when a condition is met, take out the ! Which is the “not” operator in PHP.
And, if you wanted to redirect a page if there was only one record in the table, here's how you'd do that:
<?PHP list($your_tableRecords, $your_tableMetaData) = getRecords(array( 'tableName' => your_table',
));
if($your_tableMetaData['totalRecords'] == 1) { header("Location: http://www.example.com/newurl.php"); exit; } ?>
If you wanted to redirect if there was more than one record, just change the == 1 to > 1
______________________________________________
Expanding on this, if you want to redirect and pass one or more variables to the new page, try a variation of this.
In this case there are 2 variables; group_code which is the value of a field in the portfolio_title_details table, and noback which is a way to hide certain code on the new page
Right after the load records calls, insert the following code:
<?php if($portfolio_title_detailsMetaData['totalRecords'] == 1):?> <?php foreach ($portfolio_title_detailsRecords as $record): ?> <?php $group_code= $record['group_code'] ?> <?php endforeach; ?> <?php header("Location: http://www.your_domain.com/your_new_page.php?group_code=$group_code&no_back=1"); exit; ?>
Then on the new page, define the variables $group_code and $no_back
<?php $var1= $_REQUEST['group_code']; ?> Use $var1 however you see fit.
and
<?php $var2= $_REQUEST['no_back']; ?> <?php if (!$var2 == 1 ):?> Your code to hide... <?php endif ?>
|
SORTING BY GROUP AND INSERTING GROUP HEADINGS IN A LIST VIEWER - Aug 2nd, 2010
If you’d like to display group headings on your list page here’s one approach:
For this example, a multi-record editor, called “events” has the following fields:
Title (a text field) Type (a pull down list of “Groups” to minimize entry errors) Starting Date (a date field) * in the viewer, only the Month, Day and Year are visible Preview (a short description of the event for the listing page)
In your application, you could add a full description of the event for the details page, images, etc.
The sort is by Type (ASC)ending and then by Start Date (ASC)ending
On the list viewer page the following code appears where you want your list to appear .
<?php $old_group = ''; // init blank var. foreach ($eventsRecords as $record): $group = $record['type']; // load sub-group value from record. if ($group != $old_group) { // If different from the last sub-group value, print the sub-group name. echo "<h2>$group</h2>"; }?> <a href="<?php echo $record['_link'] ?>"><?php echo $record['title'] ?></a> <?php echo $record['preview'] ?> <br /><br /> <?php $old_group = $group; // retain sub-group name before moving to new record. ?> <?php endforeach ?>
If you want to use alternate text or graphics to represent your groups you could use the following.
For Text:
<?php $old_group = ''; // init blank var. foreach ($eventsRecords as $record): $group = $record['type']; // load sub-group value from record. if ($group != $old_group && $record['type'] == "Group 1") { // If different from the last sub-group value, and equals Group 1, print the sub-group name. echo "<h2>Group 1 text </h2>";}
if ($group != $old_group && $record['type'] == "Group 2") { echo "<h2>Group 2 text</h2>";}
if ($group != $old_group && $record['type'] == "Group 3") { echo "<h2>Group 3 text</h2>";}
if ($group != $old_group && $record['type'] == "Group 4") { echo "<h2>Group 4 text</h2>";} ?> <a href="<?php echo $record['_link'] ?>"><?php echo $record['title'] ?></a> <?php echo $record['preview'] ?> <br /><br /> <?php $old_group = $group; // retain sub-group name before moving to new record. ?> <?php endforeach ?>
To display images instead of text for the headings, one approach would be to create a separate single record editor called “Graphics” with each image as a separate upload field named Group 1 Graphic, Group 2 Graphic, etc., and use something like this on the viewer page (don’t forget to add the getrecord call at the top of your page).
<?php $old_group = ''; ?>
<?php foreach ($eventsRecords as $record): ?>
<?php $group = $record['type']; ?> <?php if ($group != $old_group && $record['type'] == "Group1"): ?>
<div align="center"><?php foreach ($graphicsRecord['group_1_graphic'] as $upload): ?> <img src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" alt='' /><br /><br /></div> <?php endforeach ?> <?php endif ?>
<?php if ($group != $old_group && $record['type'] == "Group 2"): ?>
<div align="center"><?php foreach ($graphicsRecord['group_2_graphic'] as $upload): ?> <img src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" alt='' /><br /><br /></div> <?php endforeach ?> <?php endif ?>
<?php if ($group != $old_group && $record['type'] == "Group 3"): ?> <div align="center"><?php foreach ($graphicsRecord['group_3_graphic'] as $upload): ?> <img src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" alt='' /><br /><br /></div>
<?php endforeach ?> <?php endif ?>
|
SORTING BY GROUP AND INSERTING GROUP HEADINGS IN A LIST VIEWER (ANOTHER APPROACH) - Mar 23rd, 2012
This approach seems to be a bit easier to implement but it only worked with a bit of help from Jason Sauchuk, from Interactive Tools.
I wanted to allow for an expanding list of categories (actually board of director positions in an organization) that could be managed by my client from the management interface, without resorting to any coding changes.
The first thing I did was to create a multi-record editor called board_of_director_positions with only one text field called position. I set the sort to dragSortOrder DESC so that the positions would appear in the correct order.
Then, in the accounts editor, since some board members held 2 positions, I populated 2 single value list fields (board_of_director_position_1 and board_of_director_position_2) using the board_of_director_positions table as the source, the num field for the option values and the position field for the label values.
Then I used array_pluck after the list records call to create a variable containing a list of the positions so that I could display their names in my viewer
<?php
list($accountsRecords, $accountsMetaData) = getRecords(array( 'tableName' => 'accounts',
));
list($board_of_director_positionsRecords, $board_of_director_positionsMetaData) = getRecords(array( 'tableName' => 'board_of_director_positions', ));
$directorposition = array_filter(array_pluck($board_of_director_positionsRecords, 'position')); ?>
In the body of the viewer, I looped through and listed all of the positions, and then looped through all of the accounts editor records for matches to those positions.
After much consternation, Jason suggested adding the pseudo field :label to the accounts record fields, since otherwise I was trying to compare a record number to a text label. And that popped the office holders names into their correct slots.
?php foreach ($directorposition as $position): ?>
<h3 class="your_class_1"><?php echo strtoupper($position); ?></h3>
<?php foreach ($accountsRecords as $record): ?>
<?php if ($record['board_of_director_position_1:label'] == $position || $record['board_of_director_position_2:label'] == $position) : ?>
<span class="your_class_2"><?php echo strtoupper($record[full_name']); ?></span> <?php endif ?> <?php endforeach ?> <hr /> <?php endforeach ?>
This concept is easily applied to something like an FAQ page where there are multiple categories and multiple questions in each category.
Create a multi-record FAQ CATEGORIES editor with one text field called category, a dragSortOrder field and an optional hidden checkbox. Create a multi-record FAQ editor with a single value pull down list field populated using the faq_categories table as the source, the num field for the option values and the position field for the label values.
Then, as above, I used array_pluck after the list records call to create a variable containing a list of the categories so that I could display their names in my viewer
$faqgroup = array_filter(array_pluck($faq_categoriesRecords, 'category'));
Again as above, In the body of the viewer, I looped through and listed all of the categories, and then looped through all of the FAQ editor records for matches to those categories.
<?php foreach ($faqgroup as $group): ?> <h1 class="your_class_1"><?php echo strtoupper($group); ?></h1> <?php foreach ($faqRecords as $record): ?> <?php if ($record['category:label'] == $group) : ?> <?php $question = htmlspecialchars($record['question']); ?> <span class="your_class_2"><?php echo strtoupper($question); ?></span> <div align="left" class="your_class_3"><?php echo maxWords($record['answer'], 25); ?> <?php if (wordCount($record['answer']) > 25) : ?><a class="special" href="<?php echo $record['_link']; ?>"><span class="body-text-bold-10">... read more</span></a><?php endif; ?> </div> <?php endif ?> <?php endforeach ?> <hr /> <?php endforeach ?>
Since I'm using a detail page for the complete answers, I included functions called maxWords and wordCount to show a "read more" link only if there were more than 25 words in the answer. These functions are defined in the head section of my viewer, with:
<?PHP function maxWords($textOrHtml, $maxWords) { $text = strip_tags($textOrHtml); $words = preg_split("/\s+/", $text, $maxWords+1); if (count($words) > $maxWords) { unset($words[$maxWords]); } $output = join(' ', $words);
return $output; } ?>
<?PHP function wordCount($textOrHtml) { $text = strip_tags($textOrHtml, "<b></b><i></i>"); $words = preg_split("/\s+/", $text);
return count($words); } ?>
This works well and allows for discontinuous category entries in the record list, but I'd like to be able to skip categories headings with no record matches.
Any ideas? Pass them on through the contact page.
|
ALTERNATING THE BACKGROUND COLOR OF TABLE ROWS AND MORE - Jun 30th, 2012
Markr wanted to know how to automatically alternate between 2 background colors in a table.
Dave Edis, from Interactive Tools had an effective approach as always, he said:
Here's some code to do that:
<?php $bgColor = (@$bgColor == '#F8F8F8') ? '#EFEFEF' : '#F8F8F8'; ?>
Then you can display it like this: <?php echo $bgColor ?>
and the result will be:
<table> <tr> <th>title</th> <th>name</th> <th>phone</th> <th>email</th> </tr> <?php foreach ($contact_listRecords as $record): ?> <?php $bgColor = (@$bgColor == '#F8F8F8') ? '#EFEFEF' : '#F8F8F8'; ?> <tr bgcolor="<?php echo $bgColor ?>"> <td><?php echo $record['title'] ?></td> <td><?php echo $record['name'] ?></td> <td><?php echo $record['phone'] ?></td> <td><a href="mailto:<?php echo $record['email'] ?>"><?php echo $record['email'] ?></a></td> </tr> <?php endforeach; ?> </table>
A variation on this theme might be to alternate the float of images in listings on a list page, like this:
<table width="100%" border="0" cellpadding="0"> <?php foreach ($your_tableRecords as $record): ?>
<?php $float = (@$float == 'left') ? 'right' : 'left'; ?> <?php $pad = (@$pad == 'padl') ? 'padr' : 'padl'; ?> <tr> <td > <div class="<?php echo $pad ?>" style="float:<?php echo $float ?>"><div style="float:none"> <?php foreach ($record['image_1'] as $upload): ?><img src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" alt='' /><?php endforeach ?></div></div> <div align="center" style="text-align:left"><?php echo strtoupper($record['headline']); ?><?php <?php echo $record['content'); ?></div></td> </tr>
<?php endforeach; ?> </table>
Note: the css style for the classes "padl" and "padr" creates appropriate padding around the images like this:
.padl { border-right: 20px solid transparent; border-left: 20px solid transparent; border-bottom: 10px solid transparent; } .padr { border-left: 20px solid transparent; border-bottom: 10px solid transparent; }
|
SHOW THE FULL NAME OF THE AUTHOR ON A WEB PAGE - Jul 21st, 2011
In earlier versions it used to be a pretty involved process to display the author’s name in a listing. Now it’s as simple as adding one line of code to the body of your page where you want the Full Name to appear.
For a list page, just add:
<?php echo $record['createdBy.fullname'] ?>
In the foreach loop.
And for a detail page, it’s:
<?php echo $yourtableRecord['createdBy.fullname'] ?>
According to Dave Edis:
It loads the record of the "owner" from createdByUserNum and adds all those fields with a "createdBy." prefix.
If, like me you need to have a Last Name and a First Name for sorting and display purposes, you can add the 2 fields "first_name" and" last_name" to the "User Accounts" editor and then modify the createdBy code to:
<?php echo $record['createdBy.first_name'] ?> <?php echo $record['createdBy.last_name'] ?>
or
<?php echo $yourtableRecord['createdBy.first_name'] ?> <?php echo $yourtableRecord['createdBy.last_name'] ?>
You can now display and sort your "User Account" record list by the new "last name" and "first_name" fields and even delete the "fullname" field from the "User Accounts" table if you don't feel you will ever need it for anything. Just don't forget to enter the new information before you delete the "fullname" field.
NOTE: You can also use this technique in the LisPage fields that show at the top of your records lists in a multi-record editor to show the author's name instead of the createdByUserNum
|
DISPLAY DATA FOR CURRENT USER - Dec 29th, 2010
OK,
Let's say that you want to display some information from the current user's account record in your viewer.
For example: for user Jo Jones...
Welcome Joe Jones,
It's pretty simple to accomplish using $CURRENT_USER
If you have a field called "last_name" and another called "first_name" in your user account section, (If not you might consider creating them to replace the existing "fullname" field. It's not used by CMS Builder, so you can safely delete the "fullname" field unless you're using it in a viewer)
Welcome <?php echo $CURRENT_USER['first_name']; ?> <?php echo $CURRENT_USER['first_name']; ?>,
Will display the user's first name, followed by a space and then their last name followed by a coma.
According to Jason Sauchuk from Interactive Tools:
You can display any field other then an Upload field using $CURRENT USER
To display an upload field you'll first need to use the getRecords function to select the record for that user.
You can get the userNumber like this:
$CURRENT_USER['num']
|
DISPLAY INFORMATION FROM MORE THAN ONE SECTION IN A SINGLE VIEWER - Aug 2nd, 2010
Setting up a page to display information from multiple sections is pretty easy once you get the hang of it. But it can be somewhat confusing at first.
Here’s the approach for displaying information on a home page from information that’‘s in a single record editor called “homepage” and other information from a multi record editor called “listings”.
First you’ll need to set up the top of your page with getRecords calls to the two sections. (You can copy the actual code from the code generated in the admin area of the CMSB interface)
<?php require_once "/your path/cmsAdmin/lib/viewer_functions.php";
list($homepageRecords, $homepageMetaData) = getRecords(array( 'Table name' => 'homepage', 'where' => whereRecordNumberInUrl(1), 'limit' => '1', )); $homepageRecord = @$homepageRecords[0]; // get first record
list($yourlistingsRecords, $yourlistingsMetaData) = getRecords(array( 'Table name' => 'yourlistings', ));
?>
Then in the body where you want to display the home page information
<?php echo $homepageRecord['your_first_field'] ?><br /> <?php echo $homepageRecord['your_second_field'] ?><br /> <?php echo $homepageRecord['your_third_field'] ?>
and in the body where you want to display the listings records:
<?php foreach ($yourlistingsRecords as $record): ?> <?php echo $record['your_first_field'] ?><br /> <?php echo $record['your_second_field'] ?><br /> <?php echo $record['your_third_field'] ?> <?php endforeach; ?>
There’s no formatting in the above example, but it should get you started.
This concept can be expanded to display information pulled from any number of sections.
If you find you’re getting errors when you try to display items from a single record editor on multi record detail pages, you may need to remove the:
'where' => whereRecordNumberInUrl(1),
from the get records call so that you can display them.
There are situations where you may have to remove the:
'limit' => '1',
as well.
|
FORCING CHARACTERS IN A VIEWER TO DISPLAY IN A PARTICULAR CASE - Aug 2nd, 2010
If you want to force characters entered in a field to display as UPPERCASE when rendered a viewer, here’s a quick solution.
First define a variable before it’s called. (A field called “title” in this example).
For a list page:
<?php $title = htmlspecialchars($record['title']); ?>
Or for a detail page:
<?php $title = ($your_tableRecord['title']); ?>
You can also add modifying code like:
<?php $title = htmlspecialchars($your_tableRecord['title']); ?>
Then when you display the characters AS UPPERCASE you can use this code:
<?php echo strtoupper($title); ?>
This approach will work with strtolower as well if you want to force lower case.
For many complex php functions, you can just wrap the function call around the "value". In this case, it looks like this:
<?php echo strtoupper(date("D, M jS, Y", strtotime($e_blastRecord['press_release_publish_date']))) ?>
And for cases when it's getting too complicated, you can break the components up into multiple lines and use variables so it's easier to read:
<?php $time = strtotime( $e_blastRecord['press_release_publish_date'] ); $date = date("D, M jS, Y", $time); $uppercaseDate = strtoupper( $date ); echo $uppercaseDate; ?>
The approaches will also work in an RSS feed if you insert the “display” code inside the appropriate tags (<title>, <description>, etc.).
There are other strto functions that may prove interesting. They are listed at:
http://us.php.net/manual-lookup.php?pattern=strto
There are also the functions ucwords and ucfirst that are worth checking out to force your output to display Initial Caps for each word or only the first word in a field.
After defining your variable as above, you could use something like this to force your “title” field to display Initial Caps:
<?php echo ucfirst(strtolower($title)); ?>
Or this to make each word capitalized:
<?php echo ucwords(strtolower($title)); ?>
If you’d rather implement a CSS solution, try the CSS function text-transform. It comes in 3 flavors Capitalize, which will capitalize the first letter in each word, lowercase, which forces all characters to lower case, and uppercase, which forces all characters to upper case. There’s also inherit and none, which is the default.
|
PREVIOUS/NEXT PAGE LINKS ONLY IF DESIRED IMAGES PER PAGE COUNT IS EXCEEDED - Feb 19th, 2013
IF UPLOAD FIELDS ARE IN SEPARATE RECORDS
I wanted to display previous and next links on a page but only if there were more than a user specified number of image records available.
First I created a text field called thumbnails_per_page in the single record editor that I call common_information, where the client could enter the maximum amount of images to allow per page.
Then, at the top of the viewer page I defined a variable called $maximages, and added a ‘perPage’ to the “list records” call using that variable, like this:
$maximages = ($common_informationRecord['thumbnails_per_page']); list($portfolio_imagesRecords, $portfolio_imagesMetaData) = getRecords(array( 'Table name' => 'portfolio_images', 'perPage' => $maximages, ));
NOTE: the variable definition has to be outside the list records call and there are no single or double quotes around $maximages in 'perPage' => $maximages, or the variable won’t work.
I also found it necessary to remove the:
'where' => whereRecordNumberInUrl(1),
from the “list records” call that listed the common_information records. To generate the Prevous/Next links I used this code in the body of the page:
<?php if ($portfolio_imagesMetaData['totalPages'] > 1): ?> This is Page <?php echo $portfolio_imagesMetaData['page'] ?> of <?php echo $portfolio_imagesMetaData['totalPages'] ?> <?php if ($portfolio_imagesMetaData['nextPage']): ?> <br /><a href="<?php echo $portfolio_imagesMetaData['nextPageLink'] ?>">Click Here to See More of My Work. </a> <?php endif ?> <?php if ($portfolio_imagesMetaData['prevPage']): ?> <br /><a href="<?php echo $portfolio_imagesMetaData['prevPageLink'] ?>">Click Here to See My Previous Portfolio Page.</a> <?php endif ?> <?php endif ?>
IF ALL UPLOADS ARE IN A SINGLE UPLOAD FIELD IN THE SAME RECORD If you want to use the same previous/next concept in a detail page where all of your uploads are in a single upload field, the concept changes a bit since the perPage feature only works with records, not uploads within a record. (Pointed out by Chris Waddell from Interactive Tools)
Here’s my implementation of his recommendation from http://www.interactivetools.com/forum/gforum.cgi?post=75239 on paginating the display of uploaded images:
The plain vanilla implementation described in the post, for 6 images per page from a table called your_table is:
<table> <tr> <?php $photosPerPage = 6; $photoPage = @$_REQUEST['photoPage'] ? $_REQUEST['photoPage'] - 1 : 0; $firstIndex = $photoPage * $photosPerPage; if ($firstIndex > sizeof($your_tableRecord['images'])-1 || $firstIndex < 0) { $firstIndex = 0; $photoPage = 0; } $lastIndex = min($firstIndex + $photosPerPage, sizeof($your_tableRecord['images'])) - 1; foreach (range($firstIndex, $lastIndex) as $photoIndex): $upload = $your_tableRecord['images'][$photoIndex] ?> <td align="center"><div class="pic"><a href="<?php echo $upload['urlPath'] ?>" rel="enlargeimage::click" rev="photoload"><img src="<?php echo $upload['thumbUrlPath'] ?>" alt='' width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" align="middle" class="displayed" /></a></div></td> <?php $maxCols=3; if (@++$count % $maxCols == 0): ?> </tr><tr> <?php endif ?> <?php endforeach; ?> </tr></table> <p><br /> <form action="?num=<?php echo $your_tableRecord['num'] ?>" method="post"> <?php if ($firstIndex > 0): ?> <a href="?photoPage=<?php echo $photoPage; ?>&=<?php echo $your_tableRecord['num'] ?>"><< Click/Tap for previous page</a> <?php endif ?> Page <input type="text" name="photoPage" value="<?php echo($photoPage + 1); ?>" style="width: 25px;" /><input type="submit" value="Go" /> of <?php echo(ceil(sizeof($your_tableRecord['images']) / $photosPerPage)); ?> <?php if ($lastIndex < sizeof($your_tableRecord['images']) - 1): ?> <a href="?photoPage=<?php echo $photoPage+2; ?>&=<?php echo $your_tableRecord['num'] ?>">Click/Tap for next page >></a><br /> <?php endif ?> </form>
I was implementing this on a detail page that also uses Dynamic Drive’s Thumbnail Viewer II (described in another recipe) to display a grid of thumbnail images and an enlarged image on thumbnail rollover, so it may look a bit different then the code you’ll end up with.
I also used a number of variables in a table called “common_information” to allow my client to modify the number of images per page, the number of columns and rows displayed and some of the messages required for effective operation of the pages.
At the top of the page:
<?php header('Content-type: text/html; charset=utf-8'); ?> <?php require_once "/path_to_your/cmsAdmin/lib/viewer_functions.php";
list($common_informationRecords, $common_informationMetaData) = getRecords(array( 'tableName' => 'common_information', 'allowSearch'=> false, 'limit' => '1', )); $common_informationRecord = @$common_informationRecords[0]; // get first record // load records list($bookRecords, $bookMetaData) = getRecords(array( 'tableName' => 'book', 'where' => whereRecordNumberInUrl(1), 'limit' => '1', )); $bookRecord = @$bookRecords[0]; // get first record
?>
Note the 'allowSearch'=> false, which keeps the common_information getRecords call from searching on the record number that’s appended to the URL when you go from the list page to the detail page.
And in the body:
<table width="975" border="0" align="center" cellpadding="5"> <tr> <td width="474" valign="top"><div align="center"><br /><?php if ($bookRecord['images']): ?><span class="body-text-bold-9"> <?php echo $common_informationRecord['book_image_thumbnails_instructions'] ?></span><?php endif ?> <br /> <br /> </div> </td></tr></table>
<table width="950" border="0" align="center"> <tr> <td valign="top"> <?php $photosPerPage = $common_informationRecord['images_per_book_page']; $photoPage = @$_REQUEST['photoPage'] ? $_REQUEST['photoPage'] - 1 : 0; $firstIndex = $photoPage * $photosPerPage; $lastIndex = min($firstIndex + $photosPerPage, sizeof($bookRecord['images'])) - 1; ?>
<?php if ((ceil(sizeof($bookRecord['images']) / $photosPerPage)) > 1): ?><form action="?num=<?php echo $bookRecord['num'] ?>" method="post"> <?php if ($firstIndex > 0): ?> <a href="?photoPage=<?php echo $photoPage; ?>&=<?php echo $bookRecord['num'] ?>"><?php echo $common_informationRecord['previous_message'] ?></a> <?php endif ?>
<span class="body-text-bold-9">Page <input type="text" name="photoPage" value="<?php echo($photoPage + 1); ?>" style="width: 25px;" /> of <?php echo(ceil(sizeof($bookRecord['images']) / $photosPerPage)); ?></span>
<?php if ($lastIndex < sizeof($bookRecord['images']) - 1): ?> <input type="submit" value="Go" /> <!-- NOTE: You can use <input type="submit" value="" /> above if you want the word Go to disappear --> <a href="?photoPage=<?php echo $photoPage+2; ?>&=<?php echo $bookRecord['num'] ?>"><?php echo $common_informationRecord['next_message'] ?></a><br /> <?php endif ?> </form> <?php endif ?> <table border="0" cellspacing="3" cellpadding="3"> <tr>
<?php
if ($firstIndex > sizeof($bookRecord['images'])-1 || $firstIndex < 0) { $firstIndex = 0; $photoPage = 0; } foreach (range($firstIndex, $lastIndex) as $photoIndex): @$upload = $bookRecord['images'][$photoIndex] ?>
<td align="left" valign="bottom">
<a title="<span class="body-text-9"><?php echo $upload['info1'] ?></span>" href="<?php echo $upload['thumbUrlPath2'] ?>""
rel="enlargeimage"
rev="targetdiv:loadarea" > <img src="<?php echo $upload['thumbUrlPath'] ?>" alt="" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight']?>" border="0" style="margin-bottom: 5px" /> </a>
</td> <?php $maxCols=3; if (@++$count % $maxCols == 0): ?></tr><tr><?php endif; ?> <?php endforeach ?> </tr> </table>
<p></td> <td width="400"><table border="0" cellpadding="5" cellspacing="0" width="25%"> <tr> <td align="left" valign="top" ><div align="left"> <div align="center" id="loadarea" style="width: 400px; height: 500px;"> <?php $upload = @$bookRecord['images'][$firstIndex] ?> <img src="<?php echo $upload['thumbUrlPath2'] ?>" alt="" border="0" /> <br /> <br /> </div> </td> </tr> </table></td> </tr> </table>
NOTE: if you want the page number to be in a transparent box instead of the default white box, add this code to your css style sheet.
input, select { background-color:transparent; border:none; }
|
SHOWING A CLICKABLE PAGE COUNT ON A PAGE ALONG WITH THE PREV & NEXT LINKS - Aug 2nd, 2010
User Equinox69 noted that the default CMSB code produces this at the bottom of the pages:
<< prev - page 1 of 5 - next >>
He asked, “How can I make it offer a clickable page number, like:
<< prev - page 1 of 5 - next >> go to page #__
or
<< prev - page 1 - next >> 1, 2, 3, 4, 5
so that the end users can click to the page they want or enter in the page number they want?”
Damon from Interactive Tools answered with:
Here is some code to generate this type of pagination:
<< prev 1 2 3 4 next >>
Just change $your_table to your actual table name
<!-- START PAGINATION CODE --> <?php if ($your_tableMetaData['prevPage']): ?> <a href="<?php echo $your_tableMetaData['prevPageLink'] ?>"><< prev</a> <?php else: ?> << prev <?php endif ?> <?php if (@!$_GET['page']): $current_page = "1"; else: $current_page = $_GET['page']; endif; ?> <?php foreach (range(1,$your_tableMetaData['totalPages']) as $page): ?> <?php if ($page == $current_page): ?> <strong><?php echo $page; ?></strong> <?php else: ?> <a href="?page=<?php echo $page; ?>"><?php echo $page; ?></a> <?php endif ?> <?php endforeach; ?> <?php if ($your_tableMetaData['nextPage']): ?> <a href="<?php echo $your_tableMetaData['nextPageLink'] ?>">next >></a> <?php else: ?> next >> <?php endif ?> <!-- /END PAGINATION CODE -->
|
NAVIGATING TO A PREVIOUS BROWSER PAGE USING JAVASCRIPT - May 8th, 2011
If you have a situation where the usual previous/next buttons won't work, like where different list pages are using the same detail page, Chris Waddell from Interactive Tools suggests that you try employing this simple JavaScript link to go back to the previous page in the browser history.
<a class="your_class" href="javascript:history.go(-1)">Back</a>
To go back 2 pages in the browser history, you can change the number from -1 to -2, however it may not work in some browsers, like IE8 where it will only go back one page regardless.
If anyone has a more universal solution, let me know and I'll update this recipe.
|
DISPLAYING RECORDS STARTING FROM RECORD “N” - Aug 2nd, 2010
User zakcoop wanted to know if there was “..something that I should use on the News Archive page to (automatically) pull news records, starting at the 6th record?” ( The main news page showed the first 5 records.)
User sagentic reminded us that sometimes there are really simple solutions to seemingly difficult issues. He said, “Add 'offset' => 4, to your top of page code to get to start at the 6th record. (record numbering starts at 0)”
Something like this:
list($newsRecords, $newsMetaData) = getRecords(array( 'Table name' => 'news', 'offset' => 4,
Thanks Kenny.
|
AUTOMATICALLY CREATING ACTIVE LINKS FROM URLS IN TEXT BOX FIELDS USING THE BUILT IN HTMLPURIFY LIBRARY - Dec 29th, 2018
If you include a URL that contains http in a forum post, that URL is automatically converted to a live link.
I wanted to implement this in the recipes in my CMSB Cookbook, but couldn't figure out how until Daniel Loewe from Interactive Tools came up with an answer. According to Daniel, there's a PHP library called HTML Purifier (http://htmlpurifier.org/) built in to the CMSB code that does much of the heavy lifting.
Here are 2 basic implementations of this function. The text for these examples is pulled from a text box called $table_of_contentsRecord['recipe'].
1) for CMSB pages using the built in library.
<?php $recipe = ($table_of_contentsRecord['recipe']); ?> <?php $config = array(); $config['AutoFormat.Linkify'] = true;
$recipe = htmlPurify($recipe, $config); echo $recipe; ?>
2) for code that can be used outside of CMSB:
<?php $recipe = ($table_of_contentsRecord['recipe']); ?> <?php $recipe = preg_replace("|(https?://[\w\-@:%\+.~#?&//=]+)|", '<a href="\\1">\\1</a>', $recipe); echo $recipe; ?>
For a more complex implementation of htmlPurify have a look at http://www.thecmsbcookbook.com/recipedetail.php?324
|
CONVERTING THE CMSB COOKBOOK RECIPES TO THE ON-LINE VERSION - Jan 8th, 2023
Seems like this should be an easy task...Use a “textarea” to display all of the code snippets in the recipes as code, indent any code snippets, and I’m done. HA!
It turned out that it would have been an amazingly complex task to tag all of the code and URL snippets and when I tried, I kept running into blank walls.
I decided to use what Jason Sauchuk, a Interactive Tools programmer discovered as an approach. As part of the process, he suggested using the PHP function “highlight_string” to convert the entire recipe into text with highlighted code segments.
Note: To change the default colors for the various code types in highlight_string to black I inserted the following in the viewer code.
<?php ini_set("highlight.comment", "#000"); ini_set("highlight.default", "#000"); ini_set("highlight.html", "#000"); ini_set("highlight.keyword", "#000;"); ini_set("highlight.string", "#000"); ?>
Here’s the system I developed:
1) To identify the line breaks that I ultimately wanted to show in the recipe, I did a search and replace on my recipe code for any of the three variants of a line break z-x, z-x with a /, and z-x with a space and a /, ( no dashes) and replaced them all with the characters “z followed by x” (no spaces). I could have used any unique character group that wasn’t likely to show up in the recipe.
2) Then in the viewer I used preg_replace to strip all remaining line breaks in the recipe.
3) And a preg_replace to convert all occurrences of the characters “z followed by x” (no spaces) back to z-x (no dash)
4) I used the wordwrap function to limit the length of the lines displayed in the recipe to 120 characters.
5) The code snippet indicators q followed by z followed by l, and l followed by z followed by q, (no spaces) were all manually inserted into the recipes around any code that I wanted to display as code.
6) I created a css style called "snippet" to style the code snippets and one to style any <code> tags
7) I used str_replace to place blockquote tags around the code snippets
In December of 2018 I wanted to automatically turn any complete URLs that were outside of any code blocks in the recipe into clickable links, while leaving those inside of any code blocks alone.
For that, Daniel Loewe from interactive Tools suggested using the htmlPurify function built in to CMSB. He was also extremely helpful in working out the code to separate the code blocks from the text.
Here’s the code we finally came up with:
*** Please note, since the cookbook code uses all instances of q-z-l and l-z-q (without the dashes), and all instances of z-x (without the dash) to as replacement keys, you MUST remove the dashes between those letters below for the code to work***
For the css style sheet:
code { font-family: Verdana, sans-serif; color: #000000; font-size: 1em; font-weight:normal; } .snippet { font-family: Verdana, sans-serif; color: #000000; font-size: 1em; font-weight:normal; margin: 0px 0px 0px 15px; padding: 8px 12px; border: 1px dashed #305555; background-color: #54ccf2; display: block; overflow-x: auto; }
For the body of the full cookbook viewer:
<?php ini_set("highlight.comment", "#000"); ini_set("highlight.default", "#000"); ini_set("highlight.html", "#000"); ini_set("highlight.keyword", "#000;"); ini_set("highlight.string", "#000"); ?> <table align="center" width="75%" border="0" cellpadding="0"> <?php foreach ($table_of_contentsRecords as $record): ?> <tr> <td align="left" valign="top"><!--remove all remaining line breaks from the code not converted to <br /> in wordprocessor--> <?PHP $record['recipe'] = preg_replace("[]", "", $record['recipe'] ); // insert <b-r> (remove the dash) between [ and ] for the code to work ?> <?PHP $record['recipe'] = preg_replace("[]", "", $record['recipe'] ); // insert <b-r/> (remove the dash) between [ and ] for the code to work ?> <?PHP $record['recipe'] = preg_replace("[]", "", $record['recipe'] ); // insert <b-r /> (remove the dash) between [ and ] for the code to work ?> <!--replace the valid <br in the code segment --> <?PHP $record['recipe'] = preg_replace("[z-x]i", "", $record['recipe'] ); // insert <b-r /> (remove the dash) between " and ", and remove the dash between z and x for the code to work ?> <?PHP $newUnixTime = strtotime($record['createdDate']); // seconds since 1970 to createdDate $updateUnixTime = strtotime($record['updatedDate']); // seconds since 1970 to updatedDate $pastUnixTime = strtotime(date('Y-m-d', strtotime("-30 day"))); $newdifference = $newUnixTime - $pastUnixTime ; $updatedifference = $updateUnixTime - $pastUnixTime ; ?> <?php if (!$record['recipe'] ): ?> <h2 align="center" class="Heading-Black"> <?php $topic = htmlspecialchars($record['topic']); ?> <?php echo strtoupper($topic); ?></h2> <?php else: ?> <hr color="#000000" align="center" width="600" /> <!-- Check For New Or Revised Date --> <?php if ($record['new'] == 1 && $newdifference >= 0): ?> <span class="Medium-Text-Bold-Red">NEW</span><span class="Medium-Text-Bold"> - </span> <?php endif ?> <?php if ($record['revised'] == 1 && $updatedifference >= 0): ?> <span class="Medium-Text-Bold-Red">REVISED</span><span class="Medium-Text-Bold"> - </span> <?php endif ?> <!-- End Date Check --> <div align="center" style="width:60%; text-align:left;"><span class="Medium-Text-Bold"> <?php $topic = htmlspecialchars($record['topic']); ?> <?php echo strtoupper($topic); ?> <?PHP if ($record['heirarchy'] == "Sub Topic"): ?> - <?php echo date("M jS, Y", strtotime($record['updatedDate'])) ?> <?php endif ?> </span> <?php endif ?> <span class="Medium-Text"> <?php $recipe = $record['recipe']; $recipe = wordwrap($recipe, 120) ; $recipe = highlight_string($recipe, true);
// Added per Daniel Loewe 12/27/18 to create links from URLs $config = array(); $config['AutoFormat.Linkify'] = true; // split on opening blockquote $chunks = explode('q-z-l', $recipe); // remove the dashes between the q, z and l for the code to work
// loop through each chunk foreach ($chunks as $key => $chunk) {
// split chunk on end blockquote $tmp = explode('l-z-q', $chunk); // remove the dashes between the q, z and l for the code to work // did we find an ending blockquote? if (count( $tmp ) > 1) {
// purify content after blockquote $tmp[1] = htmlPurify($tmp[1], $config); } else {
// purify only element $tmp[0] = htmlPurify($tmp[0], $config); } // replace ending blockquote $chunks[ $key ] = implode('l-z-q', $tmp); }
// replace opening blockquote $recipe = implode('q-z-l', $chunks); // remove the dashes between the q, z and l for the code to work
// reset block quotes $recipe = str_replace('q-z-l', '<blockquote class="snippet"> ', $recipe); // remove the dashes between the q, z and l for the code to work $recipe = str_replace('l-z-q', '</blockquote> ', $recipe); // remove the dashes between the q, z and l for the code to work ?> <?php echo $recipe; ?> </div></td> </tr> <?php endforeach; ?> </table>
And here's the code for the detail pages
<?php ini_set("highlight.comment", "#000"); ini_set("highlight.default", "#000"); ini_set("highlight.html", "#000"); ini_set("highlight.keyword", "#000;"); ini_set("highlight.string", "#000"); ?> <!--remove all remaining line breaks from the code not converted to <br /> in wordprocessor--> <?php $recipe = ($table_of_contentsRecord['recipe']); ?> <?PHP $recipe = preg_replace("[]", "", $recipe ); // insert <b-r> (remove the dash) between [ and ] for the code to work ?> <?PHP $recipe = preg_replace("[]", "", $recipe // insert <b-r/> (remove the dash) between [ and ] for the code to work ?> <?PHP $recipe = preg_replace("[]", "", $recipe ); // insert <b-r /> (remove the dash) between [ and ] for the code to work ?> <!--replace the valid <br in the code segment --> <?PHP $recipe = preg_replace("[z-x]i", "", $recipe ); // insert <b-r /> (remove the dash) between " and ", and remove the dash between z and x for the code to work ?> <?php $recipe = wordwrap($recipe, 120) ; ?> <?php $recipe = highlight_string($recipe, true); ?> <?php $config = array(); $config['AutoFormat.Linkify'] = true; // split on opening blockquote $chunks = explode('q-z-l', $recipe); // remove the dashes between the q, z and l for the code to work
// loop through each chunk foreach ($chunks as $key => $chunk) {
// split chunk on end blockquote $tmp = explode('l-z-q', $chunk); // remove the dashes between the q, z and l for the code to work // did we find an ending blockquote? if (count( $tmp ) > 1) {
// purify content after blockquote $tmp[1] = htmlPurify($tmp[1], $config); } else {
// purify only element $tmp[0] = htmlPurify($tmp[0], $config); } // replace ending blockquote $chunks[ $key ] = implode('l-z-q', $tmp); // remove the dashes between the q, z and l for the code to work }
// replace opening blockquote $recipe = implode('q-z-l', $chunks); // remove the dashes between the q, z and l for the code to work
// reset block quotes $recipe = str_replace('q-z-l', '<blockquote class="snippet"> ', $recipe); // remove the dashes between the q, z and l for the code to work $recipe = str_replace('l-z-q', '</blockquote> ', $recipe); // remove the dashes between the q, z and l for the code to work ?> <table align="center" width="100%" border="0"> <tr><td> <span class="Medium-Text-Bold"><b> <?php $topic = htmlspecialchars($table_of_contentsRecord['topic']); ?> <?php echo strtoupper($topic); ?> - <?php echo date("M jS, Y", strtotime($table_of_contentsRecord['updatedDate'])) ?></span> </td></tr> <tr> <td class="Medium-Text"><?php echo $recipe; ?></td> </tr> </table>
|
USING CMSB TO POPULATE A CSS STYLESHEET - Feb 9th, 2011
It’s easy to populate a CSS stylesheet. from fields in a CMSB editor.
Here’s how:
In this example we'll modify the following CSS stylesheet to pull data from text fields called "heading_size", and "heading_color", and an image upload field with one uploaded image called "page_background_image", in a single record CMSB editor called "common_information".
You can apply this technique to any CSS element.
#header {background-image:url(../images/your_image.jpg)}; }
h1{ color: #c0c0c0; font-size = 2em; text-align: center; } __
If you've ever modified a site to treat html pages as PHP, using an .htaccess file, you might think that inserting:
Addhandler application/x-httpd-php.css
in the .htaccess file would be an adequate approach to recognizing .css files as PHP, but in many situations, this can lead to unexpected errors in how your pages are rendered.
So, to be safe, I'd use this approach.
First, add a .php the extension of your .css file (.css.php)
Then, in the head of your viewer page you’ll need to change:
<link rel="stylesheet" type="text/css" href="your_css_folder/your_css_file.css" />
to:
<link rel="stylesheet" type="text/css" href="your_css_folder/your_css_file.php" />
Now add the following PHP call before any CSS code to insure that your .css.php document is rendered correctly.
<?php
header("Content-type: text/css"); ?>
After you’ve created the necessary fields in your editor and entered some sample values, go to the code generator for your editor and copy the PHP require once and get records call to the head of your css.php file.
NOTE: DO NOT INCLUDE THIS LINE OF CODE:
<?php header('Content-type: text/html; charset=utf-8'); ?>
<?php require_once "path_to_your/cmsAdmin/lib/viewer_functions.php";
list($common_informationRecords, $common_informationMetaData) = getRecords(array( 'tableName' => 'common_information', 'where' => whereRecordNumberInUrl(1), 'limit' => '1', )); $common_informationRecord = @$common_informationRecords[0]; // get first record
// show error message if no matching record is found if (!$common_informationRecord) { print "Record not found!"; exit; }
?> <?php header("Content-type: text/css"); ?>
#header {background-image:url(<?php foreach ($common_informationRecord['page_background_image'] as $upload): ?> http://www.your_site.com/<?php echo $upload['thumbUrlPath'] ?><?php endforeach ?>)}; }
h1{ color: #<?php echo $common_informationRecord['heading_color'] ?>; font-size = <?php echo $common_informationRecord['heading_size'] ?>; text-align: center; }
That’s it, you can replace any css element with a php call and give your clients added flexibility without them needing to re-code your CSS stylesheet.
|
REMOVING THE UNWANTED 1PX BORDER AROUND LINKS IN FF & IE - Aug 28th, 2013
Here's the scenario.
Clicking on an active link brings you to the page it should.
Click the back arrow in either FF or IE and there’s a 1px dotted box around the link that was clicked on.
It seems that it involves a concept called "focus".
And thanks to Tim Forrest from Toledoh Enterprises there's a simple fix.
He said, "Add this line to your CSS styles sheet and the problem will disappear."
:focus { outline: 0; } __
You might want to Google :focus css to read some of the varying opinions regarding the use of this technique, but if you need the box to go away, this will work.
|
VALIDATING EMAIL ADDRESSES - May 29th, 2013
There are many times when the format of an email address needs to be validated.
There's a built in function in CMSB called isValidEmail that will do that for you, and might be used in the errorsandAlerts section of your viewer like this:
<?php if (!isValidEmail(@$_REQUEST['email_address'])) { $errorsAndAlerts .= "Please enter a valid E-mail address (example: user@example.com)\n"; } ?>
But to understand how it works, here's an regular expression approach that you can modify to suit your needs. They all assume that the email address field is called email_address
To list all email addresses in an existing list with invalid formats:
<?php $count = 0; ?> <?php foreach ($your_tableRecords as $record ): ? <?php // in the code \.[a-z0-9-]+)*(\.[a-z]{2,4}) 2 is the minimum and 4 is the maximum characters after the period to account for TLDs like .us and .info $email_address = $record['email_address']; if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email_address)) { echo $record['email_address'] ; $count++; } ?> <?php endforeach ?> <br /> <br /> There are <?php echo $count ?> invalid email addresses in this list.
If you want to list all email addresses with valid formats remove the ! from before eregi
You'll find many other useful regular expressions here:
http://www.virtuosimedia.com/dev/php/37-tested-php-perl-and-javascript-regular-expressions
|
KEEP "ARRAY()" FROM SHOWING ON VIEWER - Aug 17th, 2011
One of the fixes to get rid of the "Array()" at the top of the page is remove this line of code if it exists:
print_r($_FILES);
|
INCLUDING VARIABLES IN THE CONTENTS OF A TEXT BOX - May 13th, 2012
User zip222 wanted to include a variable in a text box field so that the contents of the textbox could be customized.
Here’s what Jason Sauchuk from Interactive Tools suggested:
Welcome to the Online Student Log-in for the *school_name* This section of our website provides links...
You can then replace *school_name* when you are outputting your content.
(Note: In this example, we're assuming that the values for *school name* is in an editor called "school_record" and the text field is a field called "content" in a table called" your_table".)
For a list page:
<?php echo str_replace('*school_name*',$schoolRecord['title'],$record['content']);?>
For a detail page the code would change to:
<?php echo str_replace('*school_name*',$schoolRecord['title'],$your_tableRecord['content']);?>
Jason explained:
In this code, the sub string *school_name* is replaced in the string $record['content'] with the variable $schoolRecord['title']
Another way to look at this is:
If you place a variable called *var1* in a target text box field called target_field in a table called target_table
And your source for *var1* is in a text box field called source_field in a table called source_table
Then the code in the body of the viewer where you want to display the composite would be:
<?php echo str_replace('*var1*',$source_tableRecord['source_field'],$target_tableRecord['target_field']);?>
Another scenario:
The detail page for a series of event listings contained a PayPal payment link that redirected to a thank you page after successful payment.
In my thank you page I wanted the text field to include the name of the event that was paid for.
I inserted *var1* in my thank you pages' target text field as above and inserted the above code in the body of my thank you page.
Then, I added: NOTE:
?<?php echo $source_tableRecord['num'] ?>%23
to the return URL in my PayPal button code. The %23 (URL-encoding for #) inserts a # after the record number that separates the transaction data (if any) from the record number so it will render correctly, (of course with my own source_table name inserted)
And another scenario: I had a series of variables that I wanted to insert in the thank you page above, and some of them were dependent. IE they shouldn't show unless there was data in a specific field. For example, if there was no special venue for an event, I didn't want to show the special venue name, address, or warning in the thank you page.
With some help from Jason Sauchuk from Interactive Tools, here's what I came up with. In the viewer:
<?php $event_start_date = date("l, M jS, Y", strtotime($learning_centerRecord['event_start_date'])) ; $special_location = ""; if (@$learning_centerRecord['special_event_location_name']) { $special_location = "<b>Special Location: ".$learning_centerRecord['special_event_location_name']."</b>\n"."<br />\n".$learning_centerRecord['special_event_location_address']."<br />\n"; } $placeHolders = array("*var1*", "*var2*", "*var3*", "*var4*", "*var5*", "*var6*" ); $replaceWith = array($learning_centerRecord['event_title'], $learning_centerRecord['event_fee'], $event_start_date, $learning_centerRecord['event_times'], $learning_centerRecord['event_description'], $special_location); echo str_replace($placeHolders, $replaceWith, $common_informationRecord['learning_center_thank_you_1']); ?>
And in the Text Field ('learning_center_thank_you_1)
NOTES: The the ."<br />\n" after Special Location:puts that text on its own line on the finished page. The <br /> after the special_event_location_name is because the address is a multi line entry. The extra ."<br />\n" at the end allows you to remove the blank line after *var6* below, and have it appear only when there's a "special_event_location_name"
Congratulations, you're all signed up for <b>"*var1*"</b> on <b>*var3*, from *var4*</b> *var6* We suggest that you arrive at least 15 minutes early so that you can get to know some of the other attendees. Here's a copy of the description of this event. *var5*
See you there...
Another scenario:
I used this approach to insert a link and an image called "image1" from a single record editor called "graphics" in a text box called "content" in the table "my_table" with the following code.
In the contents of the text box where I wanted the link to appear, I inserted:
<a href="my_URL.com/my_page.php"><img src="*variable*"></a>
And in the page code for my list page (in the foreach loop)
<?php $myImage = $graphicsRecords[0]['image1'][0]; ?> <?php echo str_replace('*variable*',$myImage['thumbUrlPath'],$record['content']);?>
And for my detail page.
<?php $myImage = $graphicsRecords[0]['image1'][0]; ?> <?php echo str_replace('*variable*',$myImage['thumbUrlPath'],$my_tableRecord['content']);?>
Don't forget to include load records calls for both editors at the top of your viewers
I asked Jason how to include more than one variable (text, links or images) in the same text box and he said:
str_replace is a php function (http://ca3.php.net/str_replace) that searches for one string inside another and replaces all instances of that string.
So, if you want to be able to insert more than 1 piece of text into a string, you'll need more placeholders (*var1*, *var2*, *var3*, etc). The actual name of the placeholder is irrelevant, but you should choose something that is unlikely to appear naturally in the text.
You can also use arrays with str_replace. For example:
<?php $placeHolders = array("*var1*", "*var2*", "*var3*"); $replaceWith = array($link1, $image1, $link2); echo str_replace($placeHolders, $replaceWith, $record['content']); ?>
In this example, str_replace will look in $record['content'] and replace all instances of *var1* with $link1, all instances of *var2* with $image1, and all instances of *var3* with $link2.
|
USE PLACEHOLDER VARIABLES TO INSERT IMAGES INTO TEXT BOXES - Dec 29th, 2018
My client wanted to use placeholder variables to insert images into text boxes from a master image library of 12 images.
Expanding on the recipe: http://www.thecmsbcookbook.com/recipedetail.php?407
and an old post on the Interactive Tools Forum: http://www.interactivetools.com/forum/forum-posts.php?71740 this is what I came up with.
1) Create a single record section called “Image Library” and create 12 image upload fields, limited to 1 image per field, set the size of thumbnail2 to suit your needs.
2) At the top of each viewer where you want the ability to insert images add the following code: Note, I placed the code in a file called _image_library.php and used the line, <?php include ("_image_library.php"); ?> in the head of the pages so I didn’t have to re-insert the code into each page.
<?php // Code to add images to text boxes
list($image_libraryRecords, $image_libraryMetaData) = getRecords(array( 'tableName' => 'image_library', 'where' => '', // load first record 'loadUploads' => true, 'allowSearch' => false, 'limit' => '1', ));
$image_libraryRecord = @$image_libraryRecords[0]; // get first record ?> <?php if ($image_libraryRecord['image_1']):?> <?php foreach ($image_libraryRecord['image_1'] as $index => $upload): ?> <?php $image1 = $upload['thumbUrlPath2'] ?> <?php endforeach ?> <?php endif ?> <?php if ($image_libraryRecord['image_2']):?> <?php foreach ($image_libraryRecord['image_2'] as $index => $upload): ?> <?php $image2 = $upload['thumbUrlPath2'] ?> <?php endforeach ?> <?php endif ?> <?php if ($image_libraryRecord['image_3']):?> <?php foreach ($image_libraryRecord['image_3'] as $index => $upload): ?> <?php $image3 = $upload['thumbUrlPath2'] ?> <?php endforeach ?> <?php endif ?> <?php if ($image_libraryRecord['image_4']):?> <?php foreach ($image_libraryRecord['image_4'] as $index => $upload): ?> <?php $image4 = $upload['thumbUrlPath2'] ?> <?php endforeach ?> <?php endif ?> <?php if ($image_libraryRecord['image_5']):?> <?php foreach ($image_libraryRecord['image_5'] as $index => $upload): ?> <?php $image5 = $upload['thumbUrlPath2'] ?> <?php endforeach ?> <?php endif ?> <?php if ($image_libraryRecord['image_6']):?> <?php foreach ($image_libraryRecord['image_6'] as $index => $upload): ?> <?php $image6 = $upload['thumbUrlPath2'] ?> <?php endforeach ?> <?php endif ?> <?php if ($image_libraryRecord['image_7']):?> <?php foreach ($image_libraryRecord['image_7'] as $index => $upload): ?> <?php $image7 = $upload['thumbUrlPath2'] ?> <?php endforeach ?> <?php endif ?> <?php if ($image_libraryRecord['image_8']):?> <?php foreach ($image_libraryRecord['image_8'] as $index => $upload): ?> <?php $image8 = $upload['thumbUrlPath2'] ?> <?php endforeach ?> <?php endif ?> <?php if ($image_libraryRecord['image_9']):?> <?php foreach ($image_libraryRecord['image_9'] as $index => $upload): ?> <?php $image9 = $upload['thumbUrlPath2'] ?> <?php endforeach ?> <?php endif ?> <?php if ($image_libraryRecord['image_10']):?> <?php foreach ($image_libraryRecord['image_10'] as $index => $upload): ?> <?php $image10 = $upload['thumbUrlPath2'] ?> <?php endforeach ?> <?php endif ?> <?php if ($image_libraryRecord['image_11']):?> <?php foreach ($image_libraryRecord['image_11'] as $index => $upload): ?> <?php $image11 = $upload['thumbUrlPath2'] ?> <?php endforeach ?> <?php endif ?> <?php if ($image_libraryRecord['image_12']):?> <?php foreach ($image_libraryRecord['image_12'] as $index => $upload): ?> <?php $image12 = $upload['thumbUrlPath2'] ?> <?php endforeach ?> <?php endif ?>
<?php $placeHolders = array("*img1*", "*img2*", "*img3*", "*img4*", "*img5*", "*img6*", "*img7*", "*img8*", "*img9*", "*img10*", "*img11*", "*img12*"); $replaceWith = array(@$image1, @$image2, @$image3, @$image4, @$image5, @$image6, @$image7, @$image8, @$image9, @$image10, @$image11, @$image12 ); ?>
This code creates an array called $placeHolders, containing the placeholders *img1* through *img12* and an array called $replaceWith, containing the variables $image1 through $image12
You can use any name for the placeholders and the variables. Just make sure that the names won’t appear in the text as well.
3) in the body of your page, (in this example an “about us” page, which gets it’s content from the text box field “about_content” in a single record editor called “about”) where you would normally use:
<?php echo $aboutRecord['about_content'] ?>
Insert the code:
<?php echo str_replace($placeHolders, $replaceWith, $aboutRecord['about_content']);?>
str_replace will look into the $aboutRecord['about_content'] field, and replace all instances of *img1* with $image1, all instances of *img2* with $image2, all instances of *img3* with $image3, etc.
This code will also work for a multi record section detail page. For a multi record list page, just change $aboutRecord['about_content'] to $record['about_content'].
4) Finally, in the “about_content” text box, insert the appropriate placeholder in a <div> exactly where you want the image to appear, and use CSS to style the <div> to suit your needs.
<div align="center" class=”your_class”><img src="*img4*"></div>
|
USING AN EMAIL TEMPLATE TO CREATE A NEW ACCOUNT RECORD - Apr 10th, 2019
My client needed to validate new listing requests for their on-line directory and then automatically create an account record with the information from the on-line application form.
To initiate the request, the applicant filled out an on-line form. I used a built in email template to pass the form values to an admin for approval and to facilitate creating a new account record once the admin had verified their information.
The problem was that spaces in the text would break the add record request until Dave Edis from interactive Tools came to the rescue. He suggested that what was needed was to urlencode values that are put in a link. Here’s what I came up with.
Further, you can't use php variables in an email template, but as Daniel Loewe pointed out, you can use if/else statements to create a variable to send in as the placeholder instead.
Other challenges were passing dates to the database and passing checkbox arrays that would assign values to a list of check boxes that gets its initial values from a list field. See the recipe at http://www.thecmsbcookbook.com/recipedetail.php?Pre-populating-radio-buttons-in-forms-from-a-master-list-568 for more information on this.
On the page that calls the email template: In the 'process form' section with error checking, etc., define a variable for passing a date.
$date = date("Y-m-d",mktime(0,0,0,@$_REQUEST['month_1'],@$_REQUEST['day_1'],@$_REQUEST['year_1']));
Then build the link to be passed to the email.
<?php
// add user if (!$errorsAndAlerts) { // checkbox pass through code suggested by Daniel Louwe from Interactive Tools 11/1/18 $more_than_one_location_for_practice = 0; $more_than_one_practitioner_in_practice = 0; $more_than_one_location_for_practicea = 0; $more_than_one_practitioner_in_practicea = 0; if (isset( $_REQUEST['more_than_one_location_for_practice'] )) {$more_than_one_location_for_practice = 1;} $more_than_one_practitioner_in_practice = 0; if (isset( $_REQUEST['more_than_one_practitioner_in_practice'] )) {$more_than_one_practitioner_in_practice = 1;} if ($more_than_one_location_for_practice === 0) { $more_than_one_location_for_practicea = 'there is only one location for this practice.'; } elseif ($more_than_one_location_for_practice === 1) { $more_than_one_location_for_practicea = 'there are multiple locations for this practice.'; } if ($more_than_one_practitioner_in_practice === 0) { $more_than_one_practitioner_in_practicea = 'there is only one practitioner in this practice.'; } elseif ($more_than_one_practitioner_in_practice === 1) { $more_than_one_practitioner_in_practicea = 'there are multiple practitioner in this practice.'; } $addLink = "http://my-site.com/cmsAdmin/admin.php?menu=accounts&action=add"; $addLink .= "&username=" .urlencode(@$_REQUEST['username']); $addLink .= "&email=" .urlencode(@$_REQUEST['email']); $addLink .= "&password=" .'2AX3Frb' ; $addLink .= "&first_name=" .urlencode(@$_REQUEST['first_name']); $addLink .= "&last_name=" .urlencode(@$_REQUEST['last_name']); $addLink .= "&practice_name=" .urlencode(@$_REQUEST['practice_name']); $addLink .= "&practice_date=" .urlencode($date); $addLink .= "&approved=" .'1'; $addLink .= "&practice_street_address=" .urlencode(@$_REQUEST['practice_street_address']); $addLink .= "&practice_city=" .urlencode(@$_REQUEST['practice_city']); $addLink .= "&practice_state=" .urlencode(@$_REQUEST['practice_state']); $addLink .= "&practice_zip=" .urlencode(@$_REQUEST['practice_zip']); $addLink .= "&practice_phone=" .urlencode(@$_REQUEST['practice_phone']); $addLink .= "&training_experience=" .urlencode(@$_REQUEST['training_experience']); $addLink .= "&more_than_one_location_for_practice=" .urlencode(@$more_than_one_location_for_practice); $addLink .= "&more_than_one_practitioner_in_practice=" .urlencode(@$more_than_one_practitioner_in_practice); if (!empty( $_REQUEST['dbt_training_support'] )) { foreach ($_REQUEST['dbt_training_support'] as $value) { $addLink .= '&dbt_training_support[]=' . urlencode($value); } } // send email to Admin $emailHeaders = emailTemplate_loadFromDB(array( 'template_id' => 'DIRECTORY-LISTING-REQUEST', 'placeholders' => array( 'contact.firstName' => ($_REQUEST['first_name']), 'contact.lastName' => ($_REQUEST['last_name']), 'contact.email' => ($_REQUEST['email']), 'contact.username' => ($_REQUEST['username']), 'practice' => ($_REQUEST['practice_name']), 'street' => ($_REQUEST['practice_street_address']), 'city' => ($_REQUEST['practice_city']), 'state' => ($_REQUEST['practice_state']), 'zip' => ($_REQUEST['practice_zip']), 'phone' => ($_REQUEST['practice_phone']), 'training' => ($_REQUEST['training_experience']), 'more_than_one_location_for_practice' => ($more_than_one_location_for_practicea), 'date1' => ($_REQUEST['practice_date']) 'more_than_one_practitioner_in_practice' => ($more_than_one_practitioner_in_practicea), 'addLink' => $addLink, ))); $mailErrors = sendMessage($emailHeaders); if ($mailErrors) { alert("Mail Error: $mailErrors"); } // show thanks $errorsAndAlerts = " <div class='heading_font' align='center'>THANKS FOR SUBMITTING YOUR REQUEST TO BE INCLUDED IN THE DIRECTORY </div> <div align='center'> <div class='text_font' align='left'><b>Your directory listing request has been sent successfully. You'll get an email from us after we've reviewed your request. Best, The Directory Team</b></div> </div> </div>"; $_REQUEST = array(); // clear form values $showSignupForm = false; }
?>
And in the email template I then only had to add the one #addLink# placeholder for the link:
NOTE: I used the free emailOnApproved plugin http://www.thecmsbcookbook/downloads/emailonapproved.zip to send an email with login information to the applicant if a checkbox called “approved” is checked in their account record, and the free AlertRecordSaved plugin http://www.thecmsbcookbook/downloads/alertrecordsaved.zip to alert the admin when a profile is updated.
Because of encrypted passwords, I send a temporary generic password to the approved applicant and they are forced to change their password on initial log in. See the recipe at http://www.thecmsbcookbook.com/recipedetail.php?287 for how to accomplish this. (***You must be using the website membership plugin***)
Hello,
#contact.firstName# #contact.lastName# has submitted a directory listing request for #practice#.
Their address is:#street# #city#, #state# #zip#
Their phone number is: #phone#
Their email address is: #contact.email#
They've indicated the following training/experience: #training#
After you've determined that the request is from a valid provider, AND THE PROVIDER IS NOT ALREADY LISTED IN THE DIRECTORY,
1) click on the link below to create a listing in the directory 2) Make sure that the "Approved" check box is checked in their new listing 3) "Save" the new listing record or it will not be available for updating
NOTE: After they've updated their profile (you'll get an email when they do), and you feel that the information is ready for release, you'll have to un-hide their listing and re-save the record, or it will not be available in the directory.
If you cannot click on the link below, copy it and paste it into your browser.
#addLink#
The Form that was used for data input for the application contained both text and checkbox fields. Problems with the checkbox fields were addressed by Daniel Loewe, a programmer at Interactive Tools. The DBT Training/Support field is feeding it's values as an array, to a list field that gets it's initial data from another table with just the titles of the support categories. :
<form method="post" action=""> <input type="hidden" name="save" value="1" /> <table border="0" cellspacing="0" cellpadding="2"> <tr> <td width="40%" align="left" valign="middle" class="text_font"><b>What's The Name Of the Practice </b></td> <td style="text-align:left" align="left" valign="middle"><input class="text" type="text" name="practice_name" id="practice_name" value="<?php echo htmlencode(@$_REQUEST['practice_name']); ?>" /></td> </tr> <tr> <td width="40%" align="left" valign="middle" class="text_font"><b>The Street Address Of the Practice </b></td> <td style="text-align:left" align="left" valign="middle"><input class="text" type="text" name="practice_street_address" id="practice_street_address" value="<?php echo htmlencode(@$_REQUEST['practice_street_address']); ?>" /></td> </tr> <tr> <td width="40%" align="left" valign="middle" class="text_font"><b>The Suite, Apartment, or Floor (optional) </b></td> <td style="text-align:left" align="left" valign="middle"><input class="text" type="text" name="practice_room_or_floor" id="practice_room_or_floor" value="<?php echo htmlencode(@$_REQUEST['practice_room_or_floor']); ?>" /></td> </tr> <tr> <td width="40%" align="left" valign="middle" class="text_font"><b>The City </b></td> <td style="text-align:left" align="left" valign="middle"><input class="text" type="text" name="practice_city" id="practice_city" value="<?php echo htmlencode(@$_REQUEST['practice_city']); ?>" /></td> </tr> <tr> <td width="40%" align="left" valign="middle" class="text_font"><b>The State - (2 Letters) </b></td> <td style="text-align:left" align="left" valign="middle"><input class="text" type="text"style='text-transform:uppercase' MAXLENGTH="2" name="practice_state" id="practice_state" value="<?php echo htmlencode(strtoupper(@$_REQUEST['practice_state'])); ?>" /></td> </tr> <tr> <td width="40%" align="left" valign="middle" class="text_font"><b>The Zip Code</b></td> <td style="text-align:left" align="left" valign="middle"><input class="text" type="text" name="practice_zip" id="practice_zip" value="<?php echo htmlencode(@$_REQUEST['practice_zip']); ?>" /></td> </tr> <tr> <td width="40%" align="left" valign="middle" class="text_font"><b>The Phone Number </b></td> <td style="text-align:left" align="left" valign="middle"><input class="text" type="text" name="practice_phone" placeholder="Numbers Only Please" id="practice_phone" value="<?php echo htmlencode(@$_REQUEST['practice_phone']); ?>" /></td> </tr> <tr> <td width="40%" align="left" valign="middle" class="text_font"><b>Is There More Than One Location For This Practice? (Check If Yes) </b></td> <td style="text-align:left" align="left" valign="middle"> <input type="checkbox" name="more_than_one_location_for_practice" value="1" <?php checkedIf('1', @$_REQUEST['more_than_one_location_for_practice']); ?> /> </td> </tr> <tr> <td width="40%" align="left" valign="middle" class="text_font" ><b>First Event Date <span style="color: #C00; font-weight: bold;">*</span> </b></td> <td align="left" valign="middle" class="text_font"><?php $lowestYear = date("Y"); $highestYear = date('Y', strtotime('+1 years')); ?> Month: <select name="month_1"> <?php if (@$_REQUEST['month_1']): ?> <option value="<?php echo htmlspecialchars(@$_REQUEST['month_1']) ?>"> <?php $month1a = @$_REQUEST['month_1'] ?> <?php echo date("F",strtotime("0000-$month1a"));?></option> <?php else :?> <option value=""><?php echo 'Select Month';?></option> <?php endif ?> <?php foreach(range(1,12) as $month_1): ?> <option value="<?php echo $month_1;?>"><?php echo date("F",strtotime("0000-$month_1"));?></option> <?php endforeach ?> </select> Day: <select name="day_1"> <?php if (@$_REQUEST['day_1']): ?> <option value="<?php echo htmlspecialchars(@$_REQUEST['day_1']) ?>"><?php echo htmlspecialchars(@$_REQUEST['day_1']) ?></option> <?php else :?> <option value=""><?php echo 'Select Day';?></option> <?php endif ?> <?php foreach(range(1,31)as $day_1): ?> <option value="<?php echo $day_1;?>"><?php echo $day_1;?></option> <?php endforeach ?> </select> Year: <select name="year_1"> <?php if (@$_REQUEST['year_1']): ?> <option value="<?php echo htmlspecialchars(@$_REQUEST['year_1']) ?>"><?php echo htmlspecialchars(@$_REQUEST['year_1']) ?></option> <?php else :?> <option value=""><?php echo 'Select Year';?></option> <?php endif ?> <?php foreach (range($lowestYear,$highestYear) as $year_1):?> <option value="<?php echo $year_1;?>"><?php echo $year_1;?></option> <?php endforeach?> </select> </td> </tr> <tr> <td width="40%" align="left" valign="middle" class="text_font"><b>What's Your First Name</b></td> <td style="text-align:left" align="left" valign="middle"><input class="text" type="text" name="first_name" id="first_name" value="<?php echo htmlencode(@$_REQUEST['first_name']); ?>" /></td> </tr> <tr> <td width="40%" align="left" valign="middle" class="text_font"><b>Your Last Name</b></td> <td style="text-align:left" align="left" valign="middle"><input class="text" type="text" name="last_name" id="last_name" value="<?php echo htmlencode(@$_REQUEST['last_name']); ?>" /></td> </tr> <tr> <td width="40%" align="left" valign="middle" class="text_font"><b>Enter A Temporary User Name</b></td> <td style="text-align:left" align="left" valign="middle"><input class="text" type="text" name="username" id="username" value="<?php echo htmlencode(@$_REQUEST['username']); ?>" /></td> </tr> <tr> <td width="40%" align="left" valign="middle" class="text_font"><b>Your E-mail Address</b></td> <td style="text-align:left" align="left" valign="middle"><input class="text" type="text" name="email" id="email" value="<?php echo htmlencode(@$_REQUEST['email']); ?>" /></td> </tr> <tr> <td width="40%" align="left" valign="middle" class="text_font"><b>Enter Your E-mail Again</b></td> <td style="text-align:left" align="left" valign="middle"><input class="text" type="text" name="email2" id="email2" value="<?php echo htmlencode(@$_REQUEST['email2']); ?>" /></td> </tr> <tr> <td width="40%" align="left" valign="middle" class="text_font"><b>Is There More Than One DBT Trained Practitioner In This Practice? (Check If Yes)</b></td> <td style="text-align:left" align="left" valign="middle"> <input type="checkbox" name="more_than_one_practitioner_in_practice" value="1" <?php checkedIf('1', @$_REQUEST['more_than_one_practitioner_in_practice']); ?> /> </td> </tr> <tr> <td class="text_font" valign="top"><b>DBT Training/Support</b></td> <td class="text_font"><?php $fieldname = 'dbt_training_support'; ?> <?php if(is_array(@$_REQUEST[$fieldname])){ $fieldValues = $_REQUEST[$fieldname]; } else{ $fieldValues = explode("\t",trim(@$_REQUEST[$fieldname],"\t")); } ?> <?php $idCounter = 0; ?> <?php foreach (getListOptions('accounts', $fieldname) as $value => $label): ?> <?php $id = "$fieldname." . ++$idCounter; ?> <input type="checkbox" name="<?php echo $fieldname ?>[]" id="<?php echo $id ?>" value="<?php echo htmlspecialchars($value) ?>" <?php if(in_array($value,$fieldValues)):?> checked="checked" <?php endif ?>/> <label for="<?php echo $id ?>"> <?php echo htmlspecialchars($label) ?> </label> <?php endforeach ?></td> </tr> <tr> <td width="40%" align="left" valign="middle" class="text_font"><b>Describe Your DBT Training/Experience (FOR INTERNAL USE ONLY)</b></td> <td style="text-align:left" align="left" valign="middle"><textarea name="training_experience" id="training_experience" placeholder="<?php echo $common_informationRecord['application_training_and_experience_example_text']?>" COLS=50 ROWS=6 ><?php echo htmlspecialchars(@$_REQUEST['training_experience']); ?></textarea> </td> </tr> <tr> <td colspan="2" class="text_font" style=" font-weight: bold;" valign="top"> Please check the "I'm not a robot" box below before submitting. <div class="g-recaptcha" data-theme="light" data-sitekey="6Lfd5RcTAAAAAJOxR3jJJfn7kfDDo4T8FCBGZKfD"></div></td> </tr> <tr> <td colspan="2" align="center"> <input class="button" type="submit" name="submit" value="SUBMIT YOUR LISTING REQUEST >>" /></td> </tr> </table> </form>
|
SAVE AND COPY FUNCTION FOR EMAIL TEMPLATES - Jan 30th, 2023
CMSB user Codee asked, "What's the possibility, and probability, that the Email Templates section of CMSB have the "Save and Copy" function such as the section editors have? Sometimes it would be great to be able to do a copy from an already built one and then just remove or change a few pieces, instead of starting from scratch for each one."
Daniel from Interactive Tools came up with a simple fix. He said, "Here's a patch you can add to saveAndCopy.php to enable it; on line 21 (in version 3.57) change this:
$addButton = isset($menuType) && ($menuType == 'multi' || $menuType == 'category') && ($action == 'add' || $action == 'edit');
to this:
$addButton = isset($menuType) && ($menuType == 'multi' || $menuType == 'category' || $tableName == '_email_templates') && ($action == 'add' || $action == 'edit');
|
DETECTING BROWSERS AND OPERATING SYSTEMS - Jul 4th, 2012
There are times when it's important to be able to serve up different code or messages based on either the OS or Browser being used.
There are more comprehensive solutions, but here's a simple function that you can use for that purpose.
The example can be pasted in the body of your page and is set up to test for the combination of Windows XP and Internet Explorer.
<?php function os_detection () {
if (isset ($_SERVER['HTTP_USER_AGENT'])) { if (strpos ($_SERVER['HTTP_USER_AGENT'], 'MSIE') && (strpos ($_SERVER['HTTP_USER_AGENT'], 'Windows NT 5.1') !== false) return true; if (strpos ($_SERVER['HTTP_USER_AGENT'], 'MSIE') && (strpos ($_SERVER['HTTP_USER_AGENT'], 'Windows XP' ) !== false) return true; }
return false; } ?> <?php if (os_detection()) : ?> We've determined that your computer is using a combination of Windows XP and the Internet Explorer browser.Sorry for the inconvenience, but to use this page with Windows XP, you'll need to use the another browser, like the free Firefox browser.If you need to, you can download the latest version from <a href="http://www.mozilla.org/en-US/firefox/new/">http://www.mozilla.org/en-US/firefox/new/</a>.Installation is automatic, you can leave multiple browsers on your system, and they won't interfere with using Internet Explorer at other times.Thanks,Photo Canvas Arts Webmaster <?PHP else: ?> Other Code... <?PHP endif ?>
By far not comprehensive, but here's a list of user Agent strings for some of the most common OS's and Browsers.
iPhone : iPhone Windows 3.11: Win16 Windows 95: Windows 95 and Win95 and Windows_95 Windows 98: Windows 98 and Win98 Windows 2000: Windows NT 5.0 and Windows 2000 Windows XP: Windows NT 5.1 and Windows XP Windows 2003: Windows NT 5.2 Windows Vista: Windows NT 6.0 and Windows Vista Windows 7: Windows NT 6.1 and Windows 7 Windows NT 4.0: Windows NT 4.0 and WinNT4.0 and WinNT and Windows NT Windows ME: Windows ME Open BSD: OpenBSD Sun OS: SunOS Linux: Linux and X11 Safari: Safari Macintosh: Mac_PowerPC and Macintosh QNX: QNX BeOS: BeOS OS/2: OS/2
___
Opera: Opera Mozilla Firefox: Firebird and Firefox Galeon: Galeon Mozilla: Gecko MyIE: MyIE Lynx: Lynx Netscape: Mozilla/4\.75 and Netscape6 and Mozilla/4\.08 and Mozilla/4\.5 and Mozilla/4\.6 and Mozilla/4\.79 Konqueror: Konqueror SearchBot: nuhk and Googlebot and Yammybot and Openbot and Slurp/cat and msnbot and ia_archiver Internet Explorer All: MSIE Internet Explorer 8: MSIE 8\.[0-9]+ Internet Explorer 7: MSIE 7\.[0-9]+ Internet Explorer 6: MSIE 6\.[0-9]+ Internet Explorer 5: MSIE 5\.[0-9]+ Internet Explorer 4: MSIE 4\.[0-9]+
There's also a get browser PHP function that can be used: http://php.net/manual/en/function.get-browser.php
|
USING CSS GRADIENTS AS PAGE BACKGROUNDS - Aug 11th, 2012
Gradients are pretty dicey at best, since support for them varies from browser to browser and version to version.
Here's an approach to incorporating a diagonal page background into my pages and allow admins to change the colors from the CMSB interface.
You can examine and modify the process with two tools. The Ultimate Gradient Generator at http://www.colorzilla.com/gradient-editor/ to generate any new style of gradient you want to create, and the base64 coder/decoder at http://www.base64decode.org/
There are lots of pitfalls in this concept.
IE9 doesn't support CSS Gradients and so you must use a base64 SVG to generate a background gradient image to display. Fortunately there's a php function called base64_encode that makes it possible to do this on the fly from values in your database.
If IE is in" Compatibility" mode your gradient won't display correctly and fill the entire screen . Fortunately you can add this as the first line in the head of your viewer to force IE not to enter compatibility mode.
<meta http-equiv="X-UA-Compatible" content="IE=8;IE=9" />
There's more in articles at: http://www.alistapart.com/articles/beyonddoctype and http://hsivonen.iki.fi/doctype/
Some older versions of browser/OS combinations don't work well with this code (***Still looking for identification and solutions for these.***)
I found that to get the gradients to cover the full screen, without repeats, I needed to make the following additions to my CSS style sheet:
html { height: 100%;
In order to allow clients to change the colors of my diagonal gradient I created 3 text fields in a single record editor called "Common Information" for the Upper left (darkest), Lower Left (middle) and Lower right (lightest) colors and I inserted the following code in my body CSS in place of the Gradient Generator code :
<!-- three variables to use in the svg conversion -->
<?php $lightest = $common_informationRecord['lightest_background_gradient_color']; ?> <?php $middle = $common_informationRecord['middle_background_gradient_color']; ?> <?php $darkest = $common_informationRecord['darkest_background_gradient_color']; ?>
<!-- The Ascii version of the SVG code iIncluding the variables --> <?php $str = '<?xml version="1.0" ?> <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"> <linearGradient id="grad-ucgg-generated" gradientUnits="userSpaceOnUse" x1="0%" y1="0%" x2="100%" y2="100%"> <stop offset="0%" stop-color="#'.$darkest.'" stop-opacity="1"/> <stop offset="0%" stop-color="#'.$darkest.'" stop-opacity="1"/> <stop offset="100%" stop-color="#'.$middle.'" stop-opacity="1"/> <stop offset="100%" stop-color="#'.$darkest.'" stop-opacity="1"/> </linearGradient> <rect x="0" y="0" width="1" height="1" fill="url(#grad-ucgg-generated)" /> </svg>';
?> body {
background: url(data:image/svg+xml;base64,<?php echo base64_encode($str)?>);
background: -moz-linear-gradient(-45deg, #<?php echo $common_informationRecord['middle_background_gradient_color']; ?> 0%, #<?php echo $common_informationRecord['darkest_background_gradient_color']; ?> 0%, #<?php echo $common_informationRecord['lightest_background_gradient_color']; ?> 100%); background: -webkit-gradient(linear, left top, right bottom, color-stop(0%,#<?php echo $common_informationRecord['middle_background_gradient_color']; ?>), color-stop(0%,#<?php echo $common_informationRecord['darkest_background_gradient_color']; ?>), color-stop(100%,#<?php echo $common_informationRecord['lightest_background_gradient_color']; ?>)); background: -webkit-linear-gradient(-45deg, #<?php echo $common_informationRecord['middle_background_gradient_color']; ?> 0%,#<?php echo $common_informationRecord['darkest_background_gradient_color']; ?> 0%,#<?php echo $common_informationRecord['lightest_background_gradient_color']; ?> 100%); background: -o-linear-gradient(-45deg, #bf6e4e 0%,#<?php echo $common_informationRecord['darkest_background_gradient_color']; ?> 0%,#<?php echo $common_informationRecord['lightest_background_gradient_color']; ?> 100%); background: -ms-linear-gradient(-45deg, #<?php echo $common_informationRecord['middle_background_gradient_color']; ?> 0%,#<?php echo $common_informationRecord['darkest_background_gradient_color']; ?> 0%,#<?php echo $common_informationRecord['lightest_background_gradient_color']; ?> 100%); background: linear-gradient(135deg, #<?php echo $common_informationRecord['middle_background_gradient_color']; ?> 0%,#<?php echo $common_informationRecord['darkest_background_gradient_color']; ?> 0%,#<?php echo $common_informationRecord['lightest_background_gradient_color']; ?> 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#<?php echo $common_informationRecord['darkest_background_gradient_color']; ?>', endColorstr='#<?php echo $common_informationRecord['lightest_background_gradient_color']; ?>',GradientType=1 ); -ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#<?php echo $common_informationRecord['darkest_background_gradient_color']; ?>', endColorstr='#<?php echo $common_informationRecord['lightest_background_gradient_color']; ?>')";
height: 100%; margin: 0; background-repeat: no-repeat; background-attachment: fixed; }
To accommodate IE9, I also inserted the following in the head of each of my viewers and added the class="gradient" to my body tag:
<!--[if gte IE 9]> <style type="text/css"> .gradient { filter: none; } </style> <![endif]-->
To temporarily display a solid color background in IE until the "fix" is in (***solved with the compatibility mode switch above***), I added this to each of my viewers as well:
<!--[if lte IE 8]> <style type="text/css"> body{ background: #<?php echo $common_informationRecord['ie_page_background_color'] ?>; } .gradient { filter: none; } </style> <![endif]-->
|
POPULATING A FORM FROM A MULTI RECORD DATABASE, UPDATING RECORDS, CREATING NEW RECORDS - Jul 15th, 2020
Updated 1/28/19 mysql_insert and mysql_update code
To pre-populate forms so that information about a specific record can be viewed and updated if desired, you’ll need to choose a field value that can uniquely identify that record. It can be an email address, the record number, or any other easily input unique identifier.
This recipe uses the email address field of a Publicity Contacts database.
It also uses two forms.
A short, email address submission form, and a longer form that can display all the desired information in your record and either updated or inserted into a new record.
For security purposes, access to this page should be restricted to appropriate individuals, but that’s covered elsewhere in the cookbook.
First you’ll need to cycle through all of the existing records in your table and compare the submitted email address with those found.
If a match is found, the main form needs to be populated with the existing information from the matching record, and a procedure for updating that information begun.
If there is no match, and a new record is to be created, appropriate error checking for required fields needs to take place before the record is created.
At each step, there need to be appropriate error messages to guide the user.
Here’s one approach to accomplishing this task:
At the top of the viewer, just after your normal list records calls, there are some blocks of code.
The code to pre-populate the form fields if a match is found after an email address is submitted.
<?php if (@$_REQUEST['save2'] ) :?> <?php
$email_address = $_REQUEST['email_address'] ; list($publicity_listingsRecords, $publicity_listingsMetaData) = getRecords(array( 'tableName' => 'publicity_listings', 'allowSearch' => false, 'where' => "email_address = '$email_address'", )); ?> <?php foreach ($publicity_listingsRecords as $record):?> <?php foreach ($record as $name => $value):?> <?php if (array_key_exists($name, $_REQUEST)) { continue; } $_REQUEST[$name] = $value; ?> <?php endforeach; ?> <?php endforeach; ?> <?php endif ?>
The code to set a counter ($count) if a matching email addresses is found,
<?php $count= 0 ?> <?php // check for matching email $email = mysql_escape(@$_REQUEST['email_address']); $count = mysql_count('publicity_listings', "email_address = '$email'"); ?>
Based on that count, the code to determine if the next process will be to update an existing record or insert a new record
<?php // Set a $show update variable to change the form submit name to “Save” if no duplicate emails are found?> <?php if ($count == 1):?> <?php $showupdate = 1 ?> <?php else:?> <?php $showupdate = 0 ?> <?php endif ?>
the code to check for errors if a new record is to be created,
<?php // process form if (@$_REQUEST['save']) {
// error checking $errorsAndAlerts = ""; if (!@$_REQUEST['first_name']) { $errorsAndAlerts .= "Please enter a first_name<br />\n"; } if (!@$_REQUEST['last_name']) { $errorsAndAlerts .= "Please enter a last_name<br />\n"; } // if (!@$_REQUEST['media_type']) { $errorsAndAlerts .= "Please select a media type<br />\n"; } if (!@$_REQUEST['specialty_group']) { $errorsAndAlerts .= "Please select a specialty group<br />\n"; } if (!@$_REQUEST['source']) { $errorsAndAlerts .= "Please select a source<br />\n"; } if (!@$_REQUEST['email_address']) { $errorsAndAlerts .= "Please enter an email address<br />\n"; } elseif(!isValidEmail(@$_REQUEST['email_address'])) { $errorsAndAlerts .= "Please enter a valid email address(example: user@example.com)<br />\n"; }
// turn off strict mysql error checking for: STRICT_ALL_TABLES mysqlStrictMode(false); // disable Mysql strict errors for when a field isn't defined below (can be caused when fields are added later)
?>
The code to insert a new record into the database.
<?php if ($count == 0 &&!$errorsAndAlerts ) { $tableName = 'publcity_listings'; $colsToValues = array(); $colsToValues['createdDate='] = 'NOW()'; $colsToValues['updatedDate='] = 'NOW()'; $colsToValues['createdByUserNum'] = 0; $colsToValues['updatedByUserNum'] = 0; $colsToValues['department'] = $_REQUEST['department']; $colsToValues['first_name'] = $_REQUEST['first_name']; $colsToValues['last_name'] = $_REQUEST['last_name']; $colsToValues['title'] = $_REQUEST['title']; $colsToValues['email_address'] = $_REQUEST['email_address']; $colsToValues['street_address'] = $_REQUEST['street_address']; $colsToValues['city'] = $_REQUEST['city']; $colsToValues['state'] = $_REQUEST['state']; $colsToValues['zip'] = $_REQUEST['zip']; $colsToValues['phone'] = $_REQUEST['phone']; $colsToValues['cell'] = $_REQUEST['cell']; $colsToValues['description'] = $_REQUEST['description']; $userNum = mysql_insert($tableName, $colsToValues, true); // On Success $first_name = $_REQUEST['first_name']; $last_name = $_REQUEST['last_name'] ; $_REQUEST = array(); // clear form values $errorsAndAlerts = "A record for $first_name $last_name has been successfully created.<br />You can now enter another email address."; } ?>
Some additional error checking code,
<?php if ( @$count > 0 && @$_REQUEST['save2'] && @!$_REQUEST['go']) { $errorsAndAlerts = "The email address $email already exists in the Publicity database.<br />Update the information below as required, then re-submit the form.<br /><br />Remember, before you can update a contact's information, you must check the check box above the 'Submit' button."; }
if ( @$count == 0 && @$_REQUEST['save2'] ) {
$email = @$_REQUEST['email_address']; $errorsAndAlerts = "The email $email is not currently in the Publicity database.<br /> Please fill out the form below to create a new record for this contact."; } ?>
And, the code to update an existing record,
<?php if (@$count > 0 && @$_REQUEST['go'] && @$_REQUEST['save2'] ): ?> <?php <?php $where = "email_address = '$email_address'"?> <?php $email = @$_REQUEST['email_address']; $tableName = 'publcity_listings'; $colsToValues = array(); $colsToValues['department'] = $_REQUEST['department']; $colsToValues['first_name'] = $_REQUEST['first_name']; $colsToValues['last_name'] = $_REQUEST['last_name']; $colsToValues['title'] = $_REQUEST['title']; $colsToValues['email_address'] = $_REQUEST['email_address']; $colsToValues['street_address'] = $_REQUEST['street_address']; $colsToValues['city'] = $_REQUEST['city']; $colsToValues['state'] = $_REQUEST['state']; $colsToValues['zip'] = $_REQUEST['zip']; $colsToValues['phone'] = $_REQUEST['phone']; $colsToValues['cell'] = $_REQUEST['cell']; $colsToValues['description'] = $_REQUEST['description']; mysql_update($tableName, null, $where, $colsToValues); // on success $first_name = @$_REQUEST['first_name'] ; $last_name = @$_REQUEST['last_name'] ; $_REQUEST = array(); // clear form values $errorsAndAlerts = "The contact information for $first_name $last_name has been updated.<br />You can now enter another email address."; ?> <?php endif ?>
In the body of the viewer are some identifying information
<h1 class="body-text-white-bold-11">ADD/MODIFY PUBLICITY RECORDS</h1> <span class="body-text-white-10">Enter as much information as you can.<br /> A </span><span class="body-text-bold-red-11">*</span> <span class="body-text-white-10">indicates a required field.</span> <!-- PUBLICITY RECORD FORM --> <?php if (@$errorsAndAlerts): ?> <div style="color: #C00; font-weight: bold; font-size: 14px; font-family: arial;"><br /> <?php echo $errorsAndAlerts; ?><br /> </div> <?php endif ?> <br /> <?php if (@$errorsAndAlerts ==""):?><br /><span class="body-text-white-11">Enter the contact's email address here.<br /> If it exists, the form will be populated with the existing information and can be updated.<br /> If not, you can add a new record for this contact.</span><br /> <?php endif ?>
The email address submission form
<form method="post" action="?"> <input type="hidden" name="save2" value="1" /> <table border="0" cellspacing="10" cellpadding="12"> <tr> <td class=" body-text-bold-white-10">Email Address</td> <td><input class="form" type="text" name="email_address" value="<?php echo htmlspecialchars(@$_REQUEST['email_address']); ?>" size="50" /></td> </tr> <tr> <td colspan="2" align="center"><br /> <input class="button" type="submit" name="save2" value="Click To Enter Email >>" /></td> </tr> </table> </form>
And the main information form (note the use of $showupdate variable to set the update confirmation check box and the form name attributes for either updating or inserting records and the hidden email_address field so that the user is forced to pre-populate existing records when email addresses match):
<form method="post" action="?"> <input type="hidden" <?php if ($showupdate == 0 ): ?>name="save"<?php else:?>name="save2"<?php endif ?> value="1" /> <table border="0" cellspacing="10" cellpadding="12"> <tr> <td colspan="2"><hr color="#b2b2b2" /></td> </tr> <tr> <td colspan="2"><hr color="#b2b2b2" /></td> </tr> <tr> <td colspan="2"><hr color="#b2b2b2" /></td> </tr> <tr> <td class=" body-text-bold-white-10">Organization</td> <td><input class="form" type="text" name="organization" value="<?php echo htmlspecialchars(@$_REQUEST['organization']); ?>" size="50" /></td> </tr> <tr> <td class=" body-text-bold-white-10">Department</td> <td><input class="form" type="text" name="department" value="<?php echo htmlspecialchars(@$_REQUEST['department']); ?>" size="50" /></td> </tr> <tr> <td class=" body-text-bold-white-10"><span class="body-text-bold-red-11">*</span> First Name</td> <td><input class="form" type="text" name="first_name" value="<?php echo htmlspecialchars(@$_REQUEST['first_name']); ?>" size="50" /></td> </tr> <tr> <td class=" body-text-bold-white-10"><span class="body-text-bold-red-11">*</span> Last Name</td> <td><input class="form" type="text" name="last_name" value="<?php echo htmlspecialchars(@$_REQUEST['last_name']); ?>" size="50" /></td> </tr> <tr> <td class=" body-text-bold-white-10">Title</td> <td><input class="form" type="text" name="title" value="<?php echo htmlspecialchars(@$_REQUEST['title']); ?>" size="50" /></td> </tr> <tr> <td colspan="2"><hr color="#b2b2b2" /> <input type="hidden" class="form" name="email_address" value="<?php echo htmlspecialchars(@$_REQUEST['email_address']); ?>" /></td> </tr> <tr> <td class=" body-text-bold-white-10">Street Address</td> <td><input class="form" type="text" name="street_address" value="<?php echo htmlspecialchars(@$_REQUEST['street_address']); ?>" size="50" /></td> </tr> <tr> <td class=" body-text-bold-white-10">City</td> <td><input class="form" type="text" name="city" value="<?php echo htmlspecialchars(@$_REQUEST['city']); ?>" size="50" /></td> </tr> <tr> <td class=" body-text-bold-white-10">State</td> <td><input class="form" type="text" name="state" value="<?php echo htmlspecialchars(@$_REQUEST['state']); ?>" size="50" /></td> </tr> <tr> <td class=" body-text-bold-white-10">Zip Code</td> <td><input class="form" type="text" name="zip" value="<?php echo htmlspecialchars(@$_REQUEST['zip']); ?>" size="50" /></td> </tr> <tr> <td colspan="2"><hr color="#b2b2b2" /></td> </tr> <tr> <td class=" body-text-bold-white-10">Land Phone</td> <td><input class="form" type="text" name="phone" value="<?php echo htmlspecialchars(@$_REQUEST['phone']); ?>" size="50" /></td> </tr> <tr> <td class=" body-text-bold-white-10">Cell Phone</td> <td><input class="form" type="text" name="cell" value="<?php echo htmlspecialchars(@$_REQUEST['cell']); ?>" size="50" /></td> </tr> <tr> <td colspan="2"><hr color="#b2b2b2" /></td> </tr> <tr> <td class=" body-text-bold-white-10">Additional Information</td> <!-- Note: The first preg_replace <br /> should have no slash and no spaces between the <br and the >, the second a <br with no space before the slash>, the third with a space before the slash>) --> <?PHP @$_REQUEST['description'] = preg_replace("[<br />]", "", @$_REQUEST['description'] ); // suppress in text area ?> <?PHP @$_REQUEST['description'] = preg_replace("[<br />]", "", @$_REQUEST['description'] ); ?> <?PHP @$_REQUEST['description'] = preg_replace("[<br />]", "", @$_REQUEST['description'] ); ?> <td style="text-align:left"><textarea cols="50" rows="5" name="description" ><?php echo @$_REQUEST['description']; ?></textarea></td> </tr> <tr> <td colspan="2"><hr color="#b2b2b2" /></td> </tr> <?php if ($showupdate == 1 ): ?> <tr> <td colspan="2"><input type = "checkbox" id="go" name="go" value = "1" <?php checkedIf(1, @$_REQUEST['go']);?> /> <span class=" body-text-bold-white-10">When you're ready to update, check this box and click "Submit"</span></td> </tr> <?php endif ?> <tr> <td colspan="2" align="center"><br /> <input class="button" type="submit" <?php if ($showupdate == 0 ): ?>name="submit"<?php else:?>name="submit2"<?php endif ?> value="Submit >>" /></td> </tr> </table> </form>
|
PRE-POPULATING RADIO BUTTONS IN FORMS FROM A MASTER LIST - May 28th, 2019
When used in a form, radio buttons allow only one value to be chosen from a list of values.
The trick here was to populate the list of values from the values available in separate master list, and use that list to populate a radio button list field in the accounts section (some of the functions in this example require the Website Membership plugin).
Here’s are the steps...
1) Create a multi-record section (called “my_values”) with a “hidden’ check box and a text field called “contents”
2) In the accounts section, create a radio button list field (called my_list_field) that gets its options from the MySQL query:
SELECT num, contents FROM `<?php echo $TABLE_PREFIX ?>my_values` WHERE hidden = 0 ORDER BY dragSortOrder ASC ;
3) Near the top of the viewer that contains your form, after the load records calls, add the following variable to the list of variables:
@$my_list_field = @$_REQUEST['my_list_field'] ;
4) After any error checking include the following in your $colsToValues array
@$colsToValues['my_list_field'] = $_REQUEST['my_list_field'] ;
5) to pre-populate your form from current user values in the accounts table
// pre-populate form with current user values foreach ($CURRENT_USER as $name => $value) { if (array_key_exists($name, $_REQUEST)) { continue; } $_REQUEST[$name] = $value; }
5) In your form, to show a radio button list of all values that are not hidden in the "my_values" section, use the code:
<tr> <td valign="top">My Available Values</td> <td> <?php $fieldname = 'your_list_field'; ?> <?php $idCounter = 0; ?> <?php foreach (getListOptions(accountsTable(), $fieldname) as $value => $label): ?> <?php $id = "$fieldname." . ++$idCounter; ?> <input type="radio" name="<?php echo $fieldname ?>" id="<?php echo $id ?>" value="<?php echo htmlencode($value) ?>" <?php checkedIf(@$_REQUEST[$fieldname], $value) ?> /> <label for="<?php echo $id ?>"><?php echo htmlencode($label) ?></label> <?php endforeach ?> </td> </tr>
Another Approach (shows all values):
<?php $fieldname = 'practice_country'; ?> <?php $idCounter = 0; ?> <?php foreach (getListOptions(accountsTable(), $fieldname) as $value => $label): ?> <?php $id = "$fieldname." . ++$idCounter; ?> <input id="<?php echo $id ?>" name="<?php echo $fieldname ?>" type="radio" value="<?php echo htmlencode($value) ?>" /> <label for="<?php echo $id ?>"><?php echo htmlencode($label) ?></label>
<?php endforeach ?>
<b>To show only values that are not hidden</b>: Since getListOptions() will get all available options for a list field, if you want to only show countries that have been selected by non-hidden records, here's a different approach.
<?php $fieldname = 'practice_country'; ?> <?php $tablename = accountsTable(); ?> <?php // get all table records list($tableRecords, $tableRecordsMeta) = getRecords(array( 'tableName' => $tablename, 'loadUploads' => false, 'loadCreatedBy' => false, 'allowSearch' => false, )); // group records by target field to find option keys $tableRecordsByField = array_groupBy($tableRecords, $fieldname); $keys = array_keys($tableRecordsByField); // create option list $listOptions = []; foreach($keys as $key) { if (!empty( $key )) { $listOptions[ $key ] = $tableRecordsByField[ $key ][ $fieldname.':label' ]; } } ?>
This will create the variable $listOptions that should contain all of the currently in-use list values and labels for the target table/field. This should let you then update your foreach to look like this:
<?php foreach ($listOptions as $value => $label): ?> <?php $id = "$fieldname." . ++$idCounter; ?> <input id="<?php echo $id ?>" name="<?php echo $fieldname ?>" type="radio" value="<?php echo htmlencode($value) ?>" <?php checkedIf(@$_REQUEST[$fieldname], $value) ?>/> <label for="<?php echo $id ?>"><?php echo htmlencode($label) ?></label> <?php endforeach ?>
Note that this will only work for single-value list fields, such as radio buttons or single dropdowns.
|
TESTING FOR A VARIABLE PASSED AT THE END OF A URL - Sep 30th, 2013
I needed to display some specific text on my products_page.php based on the value that was passed at the end of a URL when a user clicked a link to get to that page. In my case the link that were passed looked like this, with numbers at the end:
products_page.php?product=1 products_page.php?product = 2
but the URL could also have a text value at the end:
products_page.php?product=“product1"
Jason Sauchuk from Interactive Tools suggested defining a variable ($var1) like this:
<?php $var1=$_REQUEST['product']; ?>
With the variable defined, I could use if statements to produce the desired text.
<?php if ($var1 == 1):?> Text for value “1" <?php elseif ($var1 == 2):?>Text for value “2" <?php elseif ($var1 == “product1"):?>Text for value “product1" <?php endif ?>
|
LETTING CLIENTS CHOOSE THEIR OWN COLOR SCHEME AND OTHER PAGE PARAMETERS - Sep 17th, 2014
If you want your client to be able to set various page parameters themselves, here;s one approach:
This example is about page background colors (or any other color choices)
Create a multi record editor (I called it “Color Choices”) with only 2 text fields: Color (I.E.: Red, Blue, Green, etc.) and HEX Color( I.E. FF0000, 00FF00, 0000FF) with no # sign (if your client will have access to this editor you might want to limit input to min and max characters 6 and only allow the characters AaBbCcDdEeFf1234567890 since others are not valid in hex code. (or you can choose to not show the editor in the menu under advanced options) Create a record for each color you want to allow.
Then create a single record editor called “clients choices” and in that editor create a list field called “Page Background” that gets its options from the database “Color Choices” with the option values from the “hex_color” field and the option labels from the “color_choices” field
Last, where you want the color choice in your viewer, (I.E. body bgcolor=), insert the <body bgcolor="#<?php echo $client_choicesRecord[‘page_background'] ?>">
You can use the “Color Choices” editor values for any colors on your viewers by adding another list field in the “Client Choices” editor. Just name the list fields appropriately so you can keep track of them all.
The concept will also work for any other parameters as well (fonts, etc). Just create a new multi record editor for each set of parameters that are not colors, and add another appropriately named list field to the “client choice” single record editor.
|
ADDING FEATURED PERFORMERS FROM A MASTER DATABASE TO AN EVENT RECORD VIEWER - Jan 28th, 2021
ADDING FEATURED PERFORMERS TO AN EVENT RECORD For Jazz on J Street events, my client wanted me to create a multi record ‘musicians_listing’ section to contain images and information about each musician who had performed at their events.
I wanted to be able to access that information on my client’s events pages as well. To accomplish that, I chose to use the new ‘Pillbox’ list field format to list the featured performers for each event.
Since you can’t rearrange the current ‘pills’ in a pillbox field, I used a custom pillbox plugin available in the ‘Packaged Solutions’ section of this website at: http://thecmsbcookbook.com/templates_detail.php?4 The plugin adds the ability to drag the position of pills in the pillbox. (This is a function that may, or may not be added to a future CMSB release.)
To populate specific ‘events’ and listen_live listings with the information in the ‘musicians_listings’ section in (described below), I used the beta_lookupRelatedFields plugin, a free plugin available at http://thecmsbcookbook.com/downloads/relatedRecordLookupFunctions.zip Using the Related records plugin is covered in the recipe at http://thecmsbcookbook.com/recipedetail.php?273 but I’ll also include the required code in this recipe.
The first thing is a multi record editor which I called ‘Musicians Listings’.This editor has a record for each musician or group that’s performing. It has ‘text’ fields for the musician’s ‘first_name’, ‘middle_name’, ‘last_name’, ‘full_performer_or_group_name, ‘instruments_ played’, and ‘description’, and an upload field for a performer image. Note: Every performer must have their ‘full_performer_or_group_name’ field filled in for this scheme to work.
To set up my pillbox I added a ‘list’ field called ‘performers’ to both my ‘listen_live’ streamed event listings editor and my ‘events’ listing editor. I chose pillbox (multi value) as the ‘Display As’ type, chose ‘Get options from database (advanced)’ as the list options type and used the ‘num’ field as the option values and the ‘full_performer_or_group_name’ for the option labels.
You can display the new pillbox information in a viewer with this simple code taken from the code generator, but that will only display the values of the ‘full_performer_or_group_name field from the ‘performers’ pillbox field in the ‘listen_live’ or ‘events’records.
<?php echo join(', ', $listen_liveRecord['pills:labels']); ?>
The real magic comes in when you can show the data stored in other fields in the ‘musicians_listings’section records the in the ‘events’ or ‘listen_live’ viewers. Or create live links in those viewers to the complete musicians_listings’ record for that performer. Thanks to some help from Interactive tools programmer Carl Wuensche ,wa sable to accomplish that for both list pages and detail pages with the code below .
For a list page of your ‘listen_live records you could use the following:
At the top of your page the load records call for the ‘musucians_listings’
// load records from 'musicians_lisings' list($musicians_lisingsRecords, $musicians_lisingsMetaData) = getRecords(array( 'tableName' => 'musicians_lisings', 'loadUploads' => true, 'allowSearch' => false, ));
And in the body where you want to show the ‘listen_live’ record information with the related record pillbox information, use the code below:
NOTE: The where statement will only show events with a ‘presentation_date’ coming up in the next 31 days. You can comment that out, or change it to reflect your specific needs. If you want to show listings from another group, copy the entire code block again and change the where statement to your reflect your specific needs. Some examples are: This weeks events
'where' => '((NOW() + INTERVAL 7 DAY) >= presentation_date AND presentation_date >= TIMESTAMP(CURDATE(), "00:00:00"))',
Past Events:
'where' => 'presentation_date <= TIMESTAMP(CURDATE(), "00:00:00"),
Events more than 31 days in the future
'where' => 'presentation_date <= presentation_date > TIMESTAMP(NOW()+ INTERVAL 31 DAY)',
<!-- BEGIN PERFORMER LISTING CODE --> <?php // only retrieve records where the presentation date is within the upcoming 31 days list($listen_liveRecords, $listen_liveMetaData) = getRecords(array( 'tableName' => 'listen_live', 'where' => '((NOW() + INTERVAL 31 DAY) >= presentation_date AND presentation_date >= TIMESTAMP(CURDATE(), "00:00:00"))', 'orderBy'=> 'presentation_date ASC', )); beta_lookupRelatedFields(array( 'table' => 'listen_live', 'recordList' => &$listen_liveRecords, 'fieldList' => array( 'performers' ) )); $listen_liveRecord = @$listen_liveRecords[0]; // get first record ?> <table width="100%" border="0" align="center"> <?php foreach ($listen_liveRecords as $record): ?> <?php // Your Event Name, Date, and Time Information Goes Here ?> <?php if ( !empty($record['performers'])):?> <?php foreach ($record['performers'] as $performer):?> <tr> <td width="25%"><a href="musicians_detail.php?<?php echo $performer['num'] ?>"> <?php foreach ($performer['list_page_image'] as $upload): ?> <img style="padding-right: 10px; border:hidden" src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" alt="" /> <?php endforeach ?> </a> </td> <td><span class="sub_heading_font">Featuring: </span><a href=”musicians_detail.php?<?php echo $performer['num'] ?>"><span class="sub_heading_font" style="text-decoration:underline"> <?php $full_performer_or_group_name = strtolower($performer['full_performer_or_group_name']); echo ucwords($full_performer_or_group_name) ?> - <?php echo $performer['medium'] ?></span> </a> </td> </tr> <tr> <td colspan="2"><hr /> </td> </tr> <?php endforeach ?> <?php endif ?> <!-- END PERFORMER LISTING CODE --> <?php endforeach ?> </table>
For an ‘events’ detail page where you’re getting the record number from the end of the URL, the code is a bit different:
At the top of the page:
// load record from 'listen_live' list($listen_liveRecords, $listen_liveMetaData) = getRecords(array( 'tableName' => 'listen_live', 'where' => whereRecordNumberInUrl(0), 'loadUploads' => true, 'allowSearch' => false, 'limit' => '1', )); $listen_liveRecord = @$listen_liveRecords[0]; // get first record // load records from 'musicians_lisings' list($musicians_lisingsRecords, $musicians_lisingsMetaData) = getRecords(array( 'tableName' => 'musicians_lisings', 'loadUploads' => true, 'allowSearch' => false, // 'orderBy' => 'concert_lineup_order DESC', )); beta_lookupRelatedFields(array( 'table' => 'listen_live', 'recordList' => &$listen_liveRecords, 'fieldList' => array( 'performers' ) )); $listen_liveRecord = @$listen_liveRecords[0]; // get first record ?>
And in the body of the page where you want to show the event information:
<?php // Your Expanded Event Name, Date, Time and Event Description Information Goes Here ?> <!-- BEGIN PERFORMER LISTING CODE --> <?php if (!empty($listen_liveRecord['performers'])): ?> <table> <tr> <td><span class="heading_font"> Learn More About This Month's Featured Performers:</span></td> </tr> <tr> <td ><hr /></td> </tr> <?php foreach ($listen_liveRecord['performers'] as $performer): ?> <tr> <td width="25%"><a href="musicians_detail.php?<?php echo $performer['num'] ?>"> <?php foreach ($performer['list_page_image'] as $upload): ?> <img style="padding-right: 10px; border:hidden" src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" alt="" /> <?php endforeach ?></a> <a href="musicians_detail.php?<?php echo $performer['num'] ?>"><span style="text-decoration:underline"> <?php echo $performer['full_performer_or_group_name'] ?> - <?php echo $performer['instruments'] ?></span> </a></td> </tr> <tr> <td > <hr /> </td> </tr> <?php endforeach ?> </table> <?php endif ?> <!-- END PERFORMER LISTING CODE -->
|
AUTOMATIC EVENT RECORD CREATION - Jan 28th, 2021
I needed to automatically create the event records for 2 monthly events on a site for my client, Jazz on J Street. JOJS Presents! Events, (in a multi record ‘events’ section) and JOJS Live Jam Sessions (in a multi record ‘listen_live’ section.)
I had also created a multi record ‘musicians_listing’ section earlier and wanted to access that information on the events page using the new ‘Pillbox’ list field format to list the featured performers for each event. Both had a number of additional criteria that needed to be met. All that’s in another recipe at: http://thecmsbcookbook.com/recipedetail.php?620
Here’s how to automatically create event records every month:
There were a number of client required variables: 1) The events almost always occurred on the same day and time every month (second Monday, Third Saturday, etc.), but that could change. 2) JOJS Presents! events were normally only listed on the site’s special events page, and JOJS JAM Sessions were only normally listed on their live streamed events page., but that could change. 3) JOJS Presents! Events normally had featured performers listed but the Jam Sessions normally didn’t, but that could change. 4) Their live streaming event page has a next event count down timer that needed to reflect the actual start time for each event.
To deal with the required variables, I set up a single record editor called ‘Event Parameters’ with the following fields with field descriptions about the required textual formats:
6 Text fields JOJS Jam Day (of the month) - This should be entered as Third Tuesday, Last Friday, 1st Monday, etc. JOJS Presents Day (of the month) - This should be entered as Third Tuesday, Last Friday, 1st JOJS Jam Start Time - This should be entered as 7:00 PM or 8:30 PM, etc. JOJS Presents Start time - This should be entered as 7:00 PM or 8:30 PM, etc. JOJS Jam Countdown Start time -This should be entered in an hh:mm:ss format, so 7 PM would be 19:00:00 and 8:30 PM would be 20:30:00. JOJS Presents Countdown Start time - This should be entered in an hh:mm:ss format, so 7 PM would be 19:00:00 and 8:30 PM would be 20:30:00.
2 Check Boxes Streaming JOJS Presents - Check if JOJS Presents is going to be streamed going forward Create JOJS Jam Event Listing - Check if JOJS Jams should have an event listing going forward
I sorted these under the separator headers: 'START TIMES FOR COUNTDOWN TIMER' 'JOJS WEEK, DAY AND TIMES':
HELP PAGE ENTRY The help page entry for ‘Automatic creation of JOJS JAM and JOJS Presents! records’ is as follows: There is a new editor called called ‘Event Parameters’ that control the parameters for automatic creation of JOJS Jam and JOJS Presents! records. They are: Under 'START TIMES FOR COUNTDOWN TIMER': 'JOJS JAM Countdown Start time' and 'JOJS Presents Countdown Start time'. These should be entered in an hh:mm:ss format, so 7 PM would be 19:00:00 and 8:30 PM would be 20:30:00.
Under 'JOJS WEEK, DAY AND TIMES': 'JOJS JAM Day' and 'JOJS Presents Day'. These should be entered as Third Tuesday, Last Friday, 1st Monday, etc. 'JOJS JAM Start Time' and 'JOJS Presents Start Time'. These should be entered as 7:00 PM or 8:30 PM, etc.
It is assumed that JOJS Presents! events will not be streamed for the time being. If that changes going forward, check the 'Streaming JOJS Presents' check box It is assumed that JOJS Jam Sessions are listed only as 'listen-live' events. If that changes going forward, check the 'Create JOJS Jam Event Listing' check box
Then, I created 2 record creation pages that are triggered by cron jobs on my cPanel once a month. If you're using the Auto Backup plugin, you can get the basic command line format for the cron jobs from your 'Admin' > 'Background Tasks' page, or from the cron tab on your cPanel.
Just an aside, If you're not using the official Auto Backup plugin on all of your sites, I strongly suggest that you get it (only $59.95 for a single site and $89.95 for unlimited use) and use it. https://www.interactivetools.com/plugins/auto-backup/
I’ve combine the code for the 2 separate pages, so make 2 copies of the code below and comment out the 2 appropriate lines for each of the pages. You can add any $colsToValues entries that you need for your specific application.
<?php list($event_parametersRecords, $event_parametersMetaData) = getRecords(array( 'tableName' => 'event_parameters', 'where' => '', // load first record 'limit' => '1', 'allowSearch' => false, )); $event_parametersRecord = @$event_parametersRecords[0]; // get first record ?> <?php // IMPORTANT! Comment out the next line for the 'Create Jam Event' page $presentsEventDay = strtolower($event_parametersRecord['jojs_presents_day']); // IMPORTANT! Comment out the next line for the 'Create Presents Event' page $presentsEventDay = strtolower($event_parametersRecord['jojs_jam_day']); ?> <?php $this1 = 'of this month'; $next1 = 'of next month'; $resultThis = $presentsEventDay . ' ' . $this1; $resultNext = $presentsEventDay . ' ' .$next1; ?> <?php $eventDate = new DateTime($resultThis); ?> <?php $currentEventDate = new DateTime($resultThis); ?> <?php $currentEventDate1 = new DateTime($resultThis); ?> <?php $nextEventDate = new DateTime($resultNext); ?> <?php if ($eventDate < new DateTime()) { $eventDate->modify($resultNext); } ?> <?php $date2 = ($currentEventDate); ?> <?php $date2->modify('+2 day'); ?>
<?php $currentEventDate2 = $date2->format('F d, Y'); ?> <?php $date4 = ($currentEventDate1); ?> <?php $date4->modify('+4 day'); ?>
<?php $currentEventDate4 = $date4->format('F d, Y'); ?> <?php $today = date('F d, Y'); ?> <?php if(($today > $currentEventDate2) && ($today < $currentEventDate4)): ?> <?php // turn off strict mysql error checking for: STRICT_ALL_TABLES mysqlStrictMode(false); // disable Mysql strict errors for when a field isn't defined below (can be caused when fields are added later)
// add record to listen_live streaming editor
$tablename = 'listen_live'; $colsToValues = array(); $colsToValues['hidden'] = 0; $colsToValues['createdDate='] = 'NOW()'; $colsToValues['updatedDate='] = 'NOW()'; $colsToValues['createdByUserNum'] = 0; $colsToValues['upcoming_event_status'] = 0; $colsToValues['updatedByUserNum'] = 0; $colsToValues['neverRemove'] = 1; $colsToValues['is_this_a_jojs_presents_event'] = 1; $colsToValues['publishDate='] = 'NOW()'; $colsToValues['presentation_date'] = $eventDate->format('Y-m-d 00:00:00'); $colsToValues['travel_directions'] = 1; $colsToValues['time'] = "7:00 to 10:00 PM"; $colsToValues['youtube_streaming_shortcode'] = 'your youtube channel id here (not the complete url)'; $colsToValues['travel_directions'] = "your travel directions here"; $colsToValues['attendance_fee'] = '10 at the door'; $colsToValues['instructions'] = 'Listen live records are created automatically a few days after the current event is over. A default image will be shown if there is no special image uploaded. If any information that is unique to this Jam Session, it must be changed manually.'; $colsToValues['announcement_lead'] = 'New talented and innovative Professional Jazz musicians are featured LIVE every month'; // Remove any $colsToValues that don't apply anda dd your own $colsToValues entries here // IMPORTANT! Comment out the next line for 'Create Presents' Event page if($event_parametersRecord['streaming_jojs_presents'] == 1){ $newRecordNum = mysql_insert($tablename, $colsToValues, true);} // add record to the events editor
$tablename2 = 'events'; $colsToValues = array(); $colsToValues['hidden'] = 0; $colsToValues['createdDate='] = 'NOW()'; $colsToValues['updatedDate='] = 'NOW()'; $colsToValues['createdByUserNum'] = 0; $colsToValues['updatedByUserNum'] = 0; $colsToValues['neverRemove'] = 1; $colsToValues['publishDate='] = 'NOW()'; $colsToValues['presentation_date'] = $eventDate->format('Y-m-d 00:00:00'); $colsToValues['event_title'] = 'Jazz on J Street Presents!'; $colsToValues['performance_times'] = "8:00 to 9:30 PM"; $colsToValues['travel_directions'] = "Your Travel Directions Go Here (Don\'t forget to escape all \' and \" and any other forbidden characters"; $colsToValues['attendance_fee'] = '10 at the door'; $colsToValues['instructions'] = 'Listen live records are created automatically a few days after the current event is over. A default image will be shown if there is no special image uploaded. If any information that is unique to this Jam Session, it must be changed manually.'; $colsToValues['event_description'] = 'Your Even Description Here'; // Remove any $colsToValues that don't apply anda dd your own $colsToValues entries here // IMPORTANT! Uncomment the next linefor Auto Create Jams Event Page // if($common_informationRecord['create_jojs_jam_event_listing'] == 1){ $newRecordNum = mysql_insert($tablename2, $colsToValues, true); } ?> <?php endif ?> </body> </html>
|
ELIMINATING ERROR MESSAGES WHEN RECORD NUMBER IS NOT PASSED IN A DETAIL PAGE URL (BOTS) - Dec 25th, 2022
If you're using detail pages that pass a record number at the end of their URLs, bots can cause your Developer log to fill up with hundreds of useless errors in a very short period.
Thanks to Jenna Cooke from Interactive Tools suggested the following solution. She said: Try putting the following near the top of the page, after your getRecords call:
<?php if (!$your_sectionRecord) { dieWith404("Record not found!"); } // show error message if no record found ?>
Jenna's suggestion was very helpful, and solved the error log issue, but shows a blank white page with the words "Record not found!".
Since there's a slim possibility that a live visitor is receiving the message and not a bot, I used a variation on the theme that that redirects the visitor to a custom 404 page instead if a record is not found, using the following code in the same location: (You'll have to create your own appropriate page for this purpose)
<?php if (!$your_sectionRecord) { header('Location: http://your_site.com/your_new_page.php'); die;} // show error page if no record found ?>
Just remember that since you're setting an HTTP-header : you must not have sent any kind of output before (not even a blank space at the end of an included file) or you'll throw a "Warning: Cannot modify header information - headers already sent" error. Test your page after the modification to make sure that it works as planned, and proceed accordingly.
The rub is that those blank spaces may not show up in your particular code editor.
When I encounter pages that throw a 'header' error, I find it easier to find a similar detail page and copy those load viewer library and get records calls to the top of the faulty page. That usually solves the problem.
|
ORDERBY WITH MULTIPLE CRITERIA - Dec 18th, 2022
To display an image carousel on my home page I needed to pull up a limited number of the most recently created records in a section and then to randomize the resulting records so the images would appear in random order each time the page was accessed.
After a number of tries, here's what worked for me:
<?php // load records from 'books $order1= "RAND(),`createdDate` DESC" ; list($booksRecords, $booksMetaData) = getRecords(array( 'tableName' => 'books', 'loadUploads' => true, 'allowSearch' => true, 'orderBy' => $order1, 'limit' => 75, )); ?>
|
VIEWERS - LISTING PAGES
|
CHOOSING WHICH RECORDS TO DISPLAY USING OFFSET AND LIMIT COMMANDS - Sep 26th, 2020
Nigel Gordijk from Common Sense Design needed to be able to differentiate between groups of records so that some of their associated images could be used in an image carousel and others could be presented in a list format.
It seemed complicated until CMSB user KennyH offered this simple suggestion using a combination of the limit and offset command in his list records calls.
Here’ his elegant solution:
Here we load the first 5 articles
list($article_postsRecords, $article_postsMetaData) = getRecords(array( 'tableName' => 'article_posts', 'limit' => '5', 'loadUploads' => true, 'allowSearch' => false, ));
Now, we can create add this again for the next five records, but with a few modifications:
list($article_postsSideListRecords, $article_postsSideListMetaData) = getRecords(array( 'tableName' => 'article_posts', 'limit' => '5', 'offset' => '4', 'loadUploads' => true, 'allowSearch' => false, ));
$article_postsRecords, $article_postsMetaData becomes $article_postsSideListRecords, $article_postsSideListMetaData
Add 'offset' => '4', to skip the first 5 records (numbering starts at zero)
Then you would display the first 5 images on the page like this
<?php foreach ($article_postsRecords as $record): ?>
<?php foreach ($record['images'] as $index => $upload): ?> <img src="<?php echo htmlencode($upload['urlPath']) ?>" width="<?php echo $upload['width'] ?>" height="<?php echo $upload['height'] ?>" alt=""> <?php endforeach ?>
<?php endforeach ?>
The next 5 images pull from $article_postsSideListRecords
<?php foreach ($article_postsSideListRecords as $record): ?>
<?php foreach ($record['images'] as $index => $upload): ?> <img src="<?php echo htmlencode($upload['urlPath']) ?>" width="<?php echo $upload['width'] ?>" height="<?php echo $upload['height'] ?>" alt=""> <?php endforeach ?>
<?php endforeach ?>
|
USING GROUPBY TO CREATE A LIST OF RECORDS THAT HAVE THE SAME VALUES AND ONLY RETURN ONE RECORD PER GROUP - May 28th, 2019
I had created a service provider directory for a client who wanted to create a list of the countries and states/provinces that had provider listing records (accounts). They also wanted to show a count of how many listings there were for each country and each state/province, eliminating any hidden listings.
With a great deal of help from Daniel Loewe and Greg Thomas, here’s what we came up with.
You can see the result at https://dbtproviders.com/maplist.php
Daniel first suggested using the groupBy function to create a list of records that have the same values and only return one record per group.
list($accountsRecords, $accountsMetaData) = getRecords(array( 'tableName' => 'accounts', 'orderBy' => 'practice_country ASC , practice_state ASC ', 'groupBy' => 'practice_country, practice_state', ));
Then to display the list, he suggested the following (Greg added the code for counting):
<?php $old_group = ''; // init blank var.
foreach ($accountsRecords as $record): ?> <?php if (!$record['practice_country:label'] == '' ):?> <?php $group = $record['practice_country:label']; // load sub-group value from record. ?> <?php else : ?> <?php $group = $record['other_practice_country']; ?> <?php endif ?> <?php $stateCount = mysql_count('accounts', mysql_escapef("`practice_state` = ? AND `hidden` = '0' ",$record['practice_state'])); ?> <?php $countryCount = mysql_count('accounts', mysql_escapef("`practice_country` = ? AND `hidden` = '0' ",$record['practice_country'])); ?> <div class="rTableRow"> <div class="rTableCell text_font"> <?PHP if ($group !== $old_group) {echo "<h3>$group ($countryCount Listings)</h3>";} ?> <?php $state = ($record['practice_state']); ?> <?php $country = ($record['practice_country:label']); ?> <?php $recnum = ($record['num']); ?> <a href="maps.php?state=<?php echo $state ?>&country=<?php echo $country ?>"><?php echo ucwords($state); ?> (<?php echo $stateCount ?>) </a></div> </div> <?PHP $old_group = $group; // retain sub-group name before moving to new record. ?> <?php endforeach; ?>
|
THE CODE FOR A 2 COLUMN LISTING PAGE WITH A LINKED IMAGE - Aug 2nd, 2010
Here’s an example of a 2 column list page that lists events in rows with a list page image in one column and a short description of the event and the date(s) for the event in another. Note that “if” statements are used to eliminate extra spaces and special text if there is no information in particular fields. The “list_page_image” is a field that holds a specific image that’s uploaded for display on the list page.
<table width="90%" border="0" cellpadding="5"><?php foreach ($happeningsRecords as $record): ?> <tr> <td align="center"> </td> <td align="left" valign="top"><hr align="left" width="300" color="#99945e"/></td> </tr> <tr> <td align="center"> <?php foreach ($record['list_page_image'] as $upload): ?><a href="<?php echo $record['_link'] ?>"><img src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" alt="" /></a> <div class="body-text-bold"> <?php if ($upload['info1']): ?><?php echo $upload['info1']; ?><?php endif; ?><br /> <?php if ($upload['info2']): ?><?php echo $upload['info2']; ?> <?php endif; ?></div> <?php endforeach; ?> </td><td align="left" valign="top"><a href="<?php echo $record['_link'] ?>"><span class="heading-text-bold"><?php echo $record['title'] ?></span> <?php if ($record['short_description']): ?><br /><span class="body-text-bold"><?php echo $record['short_description'] ?></span><?php endif ?><br /> <span class="body-text"><?php echo date("D, M jS, Y g:i", strtotime($record['starting_date'])) ?> <?php if ($record['ending_date']): ?> through <?php echo $record['ending_date'] ?></span> <?php endif; ?> <br /> </a><?php endforeach; ?> </td> </tr> </table>
|
WORKING WITH CATEGORY FILTERS - LISTINGS PAGE ISSUES - Aug 2nd, 2010
chassa2556 was concerned that links on a listings page that were filtered by category were always going to the first record detail page. Here’s what he said:
I have my 'see more' link going to:
<a href="involvedDetail.php?<?PHP echo $involvedRecord['num'] ?>"> see more </a>
I have set it up so it all goes to one section with a category filter. The trouble is it keeps going to the first record. This is even though I am on the second or third record and am expecting it to go to the relating detail page.
This was his header code:
list($involvedRecords, $involvedDetails) = getRecords(array( 'Table name' => 'involved', 'where' => ' category = "Join Us" ', ));
Mr.Jim from WebCamp One was able to shed some light on the problem. He said:
I'm assuming that you have two pages: a list page and then a detail page. The detail page would be the one that pops up when you click on 'read more'. I'm also assuming that you are restricting anything listed on your list page to items that fall within the category "Join Us".
If I'm correct, try this:
1. In your list page, add the following line to your header code:
'where' => 'category = "Join Us"',
After you add that code, that 'where' statement should be the only 'where' statement in the list page's header code.
2. Remove that same line from the header on your existing detail page and replace it with the following lines:
'where' => whereRecordNumberInUrl(1), 'limit' => '1',
3. Finally, change the code in your list page to read:
<a href="involvedDetail.php?<?PHP echo $involvedRecord['_link'] ?>"> see more </a>
That seemed to do the trick for chassa2556.
|
ADD A HORIZONTAL LINE TO SEPARATE LETTER GROUPS IN A LIST - Aug 2nd, 2010
Rconring wanted to know how to add an <hr> between the letter groups in an alphabetized list of links. Ross Fairbairn - Product Specialist at Interactive tools had the solution. He said, Just add the indicated code to your page and you’re good to go.
<?php foreach ($linksRecords as $record): ?> <a target="_blank" title="<?php echo $record['screen_tip'] ?>" href="<?php echo $record['web_address'] ?>"><?php echo $record['title'] ?></a><br /> <!-- Insert This Code --> <?php $letter = substr($record['title'], 0,1); if ($letter != @$lastLetter) { print '<hr width="50%" size="1">'; } $lastLetter = $letter; ?> <!-- End of Insert--> <?php endforeach ?>
|
GROUPING SUBTOPICS IN YOUR LIST VIEW - Aug 2nd, 2010
InHouse offered this simple way of grouping the contents of List Views. I thought it might be useful for someone. Share and enjoy.
In the Editor, create a field to hold the group names. Use the “List” option with either a pull down or check box format to limit user mistakes and make this field mandatory as well. In this example the field is called "type". There are also fields called “title” and “content”.
<?PHP $old_group = ''; // init blank var. foreach ($yourtableRecord as $record): $group = $record['type']; // load sub-group value from record. if ($group != $old_group) { // If different from the last sub-group value, print the sub-group name. echo "<h5>$group</h5>"; }?>
<a href="<?PHP echo $record['_link'] ?>"><?PHP echo $record['title'] ?></a> <?PHP echo $record['content'] ?>
<?PHP $old_group = $group; // retain sub-group name before moving to new record. ?> <?PHP endforeach ?>
If you want to only show a single sub group then use an IF statement within the FOREACH loop:
<?PHP $desired_group = 'yourgroupname'; // init target var. foreach ($yourtableRecord as $record): if ($record['type'] == $desired_group ) { // Examine the current Type and see if it matches the desired group type. ?>
<a href="<?PHP echo $record['_link']; ?>"><?PHP echo $record['title']; ?></a> <?PHP echo $record['content'] ?>
}// End If ?> <?PHP endforeach ?>
Thanks InHouse!!!
Here’s how I used this idea on the CMSBuilder Cookbook Links page with a table called “resources” and fields called “category”, url, and link_text”. The line
<table width="800" border="0" cellpadding="0">
<?php $old_group = ''; // init blank var. foreach ($resourcesRecords as $record): $group = $record['category']; // load sub-group value from record. ?>
<tr> <td align="left" class="Medium-Text"> <?PHP if ($group != $old_group) {echo "<h2>$group</h2>";}?>
<a href="<?php echo $record['url'] ?>" target="_blank"><?php echo $record['link_text'] ?></a> <br /><?php echo $record['content'] ?><hr align="center" color="#999999" /></td> </tr>
<?PHP $old_group = $group; // retain sub-group name before moving to new record. ?> <?php endforeach; ?>
</table>
|
CREATING A LIST PAGE WITH NESTED INFORMATION FROM 2 MULTI RECORD EDITORS - Aug 2nd, 2010
The goal is to create a list page using information from 2 multi record editors. “Exhibitions”, and “Opening Receptions”.
The “Exhibitions” editor has all of the permanent event information and the Opening Receptions” contains only the opening reception information for each exhibition. (I’m using 2 editors so that the “Opening Reception” information can automatically be hidden after the reception date has passed)
Here’s the code I thought would work, but it didn’t. Then you’ll see what did work, and understand why:
Since I was going to access 2 section editors, I put both my getRecords() calls In the head of the document:
<?php require_once "/yourpathto/cmsAdmin/lib/viewer_functions.php";
list($exhibitionsRecords, $exhibitions metadata) = getRecords(array( 'Table name' => 'exhibitions', )); list($opening_receptionsRecords, $opening_receptionsMetaData) = getRecords(array( 'Table name' => 'opening_receptions', 'where' => "exhibition LIKE '%" .mysql_real_escape_string(@$_REQUEST['sort_exhibition']). "%'", )); ?>
And then in the body:
<table> <?php foreach ($exhibitionsRecords as $record): ?> <tr> <td><a href="<?php echo $record['_link'] ?>">"<?php echo $record['exhibition'] ?>"</a> Show Dates: <?php echo date("D, M jS", strtotime($record['opening_date'])) ?> - <?php echo date("D, M jS, Y ", strtotime($record['closing_date'])) ?> <hr color="#C70000" width="300" />
Opening Reception: <?php foreach ($opening_receptionsRecords as $record): ?><?php echo date("D, M jS", strtotime($record['reception_date'])) ?><?php endforeach; ?> </td> </tr> <?php endforeach; ?> </table>
Using this approach, no matter how I adjusted the code, all of the “Opening Reception” dates were showing in each event listing.
I was out of ideas, when Dave suggested that my initial approach didn’t work because you can't look up all the opening dates without knowing all the exhibition titles in advance. So one way to do it is to load the opening date as you display each exhibition.
Instead of putting both getRecords() calls in the head of the document, set up one getRecords() in the document head that loads the exhibitions records. Then create the foreach loop to display them.
Then, inside that foreach loop, insert the other getRecords() call that loads the opening dates for each particular exhibition and a foreach loop displays those. Like this:
In the head:
<?php require_once "/yourpathto/cmsAdmin/lib/viewer_functions.php";
list($exhibitionsRecords, $exhibitions metadata) = getRecords(array( 'Table name' => 'exhibitions', ));
?>
Then in the Body:
<table> <?php foreach ($exhibitionsRecords as $record): ?> <tr> <td> <a href="<?php echo $record['_link'] ?>"> <class="style2">"<?php echo $record['exhibition'] ?>"</a> <br /> Show Dates: <?php echo date("D, M jS", strtotime($record['opening_date'])) ?> - <?php echo date("D, M jS, Y ", strtotime($record['closing_date'])) ?><br /> <?php echo $record['days_and_times'] ?></p><hr color="#C70000" width="300" />
Opening Reception: <?php list($opening_receptionsRecords, $opening_receptionsMetaData) = getRecords(array( 'Table name' => 'opening_receptions', 'where' => "exhibition = '" .mysql_real_escape_string(@$record['exhibition']). "'", )); ?>
<?php foreach ($opening_receptionsRecords as $reception): ?> <?php echo date("D, M jS", strtotime($reception['reception_date'])) ?> <?php endforeach; ?>
</td> </tr> <?php endforeach; ?> </table>
Dave’s approach worked like a charm, however, he pointed out that this adds MySQL queries, so if you’re displaying lots and lots of records this might not be a very efficient approach.
|
USING DIFFERENT STYLES TO DISPLAY GROUPS OF RECORDS ON A LIST PAGE - Aug 2nd, 2010
NigelGordijk had a number of articles that he wanted to display on his list page in the following format:
- The latest article with a large photo and a intro description - The next two articles with smaller photos and intro descriptions - The next five articles as links only, without photos or intro descriptions
Damon from Interactive Tools offered this solution.
He said, “The code consists of three IF statements:
The first: Top Story - if the counter is 1 then output top story code.
The second: Next Two Stories - if the stories are number 2 or number 3, use the code to output the small images etc.
The third: Last Five Articles - if the story number is greater than 3, use the code that outputs only the title (with link) and date, no images.”
You can see how this works by setting up a multi-record editor called “News” with at least a “Title” field, a “Content” field, and one Upload field called “Uploads” and then adding some test records.
Here are the settings Damon used for the thumbnails for this example:
Thumb 1 - 235px wide x 999px high Thumb 2 - 480px wide x 999px high
Now create a list viewer with the following code before the <head>
<?php header('Content-type: text/html; charset=utf-8'); ?> <?php require_once "/your_path_to/lib/viewer_functions.php";
list($newsRecords, $newsMetaData) = getRecords(array( 'tableName' => 'news', ));
?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">
And in the body of your list viewer insert the following code:
<?php $counter = 1; ?> <?php foreach ($newsRecords as $record): ?>
<?php if(($counter == 1) || ($newsMetaData['page'] > 1)) : ?> <!-- TOP STORY --> <?php foreach ($record['uploads'] as $upload): ?> <?php if ($upload['hasThumbnail']): ?> <img src="<?php echo $upload['thumbUrlPath2'] ?>" width="<?php echo $upload['thumbWidth2'] ?>" height="<?php echo $upload['thumbHeight2'] ?>" alt="" /><br /> <?php endif ?> <strong><a href="<?php echo $record['_link'] ?>"><?php echo $record['title'] ?></a></strong><br /> <?php echo date("D, M jS, Y", strtotime($record['date'])) ?><br /> <?php echo $record['content'] ?><br /> <?php endforeach ?> <hr /> <!-- END TOP STORY -->
<?php elseif(($counter > 1) && ($counter < 4)) : ?> <!-- NEXT TWO STORIES --> <a href="<?php echo $record['_link'] ?>"><?php echo $record['title'] ?></a><br /> <?php foreach ($record['uploads'] as $upload): ?> <?php if ($upload['hasThumbnail']): ?> <img src="<?php echo $upload['thumbUrlPath'] ?>" width="<?php echo $upload['thumbWidth'] ?>" height="<?php echo $upload['thumbHeight'] ?>" alt="" align="left" /><br /> <?php endif ?> <?php endforeach ?> Date: <?php echo date("D, M jS, Y", strtotime($record['date'])) ?><br /> <?php echo $record['content'] ?> <br clear="left" /> <hr /> <br clear="left" /> <!-- END NEXT TWO STORIES -->
<?php elseif($counter > 3): ?> <!-- REMAINING ARTICLES --> <a href="<?php echo $record['_link'] ?>"><?php echo $record['title'] ?></a><br /> Date: <?php echo date("D, M jS, Y", strtotime($record['date'])) ?><br /><br /> <!-- END REMAINING ARTICLES -->
<?php endif; ?> <?php $counter++ ?> <?php endforeach; ?>
If you want to limit the number of words displayed for the “Content” and link to a detail page, you can place the following code before the code in the <body> of your page to define a “maxWords function:
<?PHP function maxWords($textOrHtml, $maxWords) { $text = strip_tags($textOrHtml); $words = preg_split("/\s+/", $text, $maxWords+1); if (count($words) > $maxWords) { unset($words[$maxWords]); } $output = join(' ', $words); return $output; } ?>
And replace the
<?php echo $record['content'] ?>
code, with something like this to utilize the “maxWords” function you inserted:
<?PHP echo maxWords($record['content'], 25); ?>...<a href="<?php echo $record['_link']; ?>">Read More</a>
The 25 can be any number and will define the number of words you want to display. Dragging the record to new positions on the record list will change the way they are displayed on your list page. The record at the top of the list is #1, and the second is # 2, etc. Note: the <br clear”left”/> makes sure that no floating elements are allowed on the left side of the text.
|
PASSING VARIABLES AT THE END OF A URL FROM A DETAIL PAGE TO A LISTING PAGE - Mar 12th, 2017
Creating a link on a detail page that would show all off the records created by the author of that record on a new list page.
ON THE DETAIL PAGE First, create a variable from the createdByUserNum value on the detail page
<?php $member1 = $my_tableRecord['createdByUserNum'] ?>
Then append that variable's value, and the new variable to be passed along to the end of the Link URL
<a href="show-all-records-test1.php?member=<?php echo $member1 ?>">Show All records</a>
ON THE LISTING PAGE Add this code before the list records call to define the value of the passed $member variable
<?php $member = $_REQUEST['member']; ?>
Then in the list records call, add a 'where' to filter the results to only those records that were created by that author:
<?php // load records from 'my_table'
list($my_tableRecords, $my_tableMetaData) = getRecords(array( 'tableName' => 'my_table', 'loadUploads' => true, 'allowSearch' => true, 'orderBy' => 'createdDate DESC', 'where' => 'createdByUserNum = "'. $member .'"' , )); ?>
The 'orderBy' => 'createdDate DESC', sorts the results with the newest at the top
|
UPDATING A TABLE VALUE WITHOUT RELOADING A WEB PAGE USING AN AJAXURL - Dec 12th, 2018
I needed to accept or reject submitted entries into an art exhibition so that exhibition managers could see which entries were going to be in the show and which were not. I also needed to send acceptance/rejection emails to the entrants automatically.
The problem was that there were a great many submissions and I didn't want to re-load the page each time, the way it seemed to work when submitting a form to update the entrant's record. This would have made it extremely hard for a manager to keep track of which submission they were working on.
One more piece of background and then on to the code.
I'm using info5 to indicate which submission images are accepted/rejected. Since I'm also using info5 for price values, there's some code that strips out any existing alphabetical characters from the existing info5 value, and appends either 'keep' or 'remove' to the remaining numbers in the field.
To follow this recipe you'll need a milti-record editor (exhibition_submissions) with at least one multi-image upload field (submission_images) with all 5 info fields.
Your application will probably be different but the concepts should translate easily.
First, on the page that displays all of the submitted images there are 2 small Ajax scripts that pass 2 variables 'recNum' and 'newValue'. One to mark a submission as 'keep' and the other to mark it as 'remove':
<script type = "text/javascript"> function keepSubmission(recNum, newValue ){ ajaxUrl = "keep2017.php?submit=1&recNum=" + escape(recNum)+"&newValue=" + escape(newValue); $.ajax({ url: ajaxUrl, }).done(function() { //add code here if anything needs to happen after the ajax call alert("Submission accepted"); }); } </script> <script type = "text/javascript"> function removeSubmission(recNum, newValueR ){ ajaxUrl = "remove2017.php?submit=1&recNum=" + escape(recNum)+"&newValueR=" + escape(newValueR); $.ajax({ url: ajaxUrl, }).done(function() { //add code here if anything needs to happen after the ajax call alert("Submission removed"); }); } </script>
Then, in the foreach loop that dis[plays each submitted image, the code to remove any existing text in the info5 field:
<?php foreach($exhibition_submissionsRecords as $record) : ?> <?php foreach ($record['submission_images'] as $upload): ?> <?php // keep the price but replace any text with 'keep' ?> <?php $keep = 'keep' ?> <?php $oldValue = $upload['info5'] ?> <?php $newValue = preg_replace('/[^0-9 .]/','', $oldValue) ?> <?php $newValue = ($newValue. $keep) ?> <?php // keep the price but replace any text with 'remove' ?> <?php $remove = 'remove' ?> <?php $oldValue = $upload['info5'] ?> <?php $newValueR = preg_replace('/[^0-9 .]/','', $oldValue) ?> <?php $newValueR = ($newValueR. $remove) ?> <?php $recNum = $upload['num'] ?>
<a href="<?php echo $upload['urlPath'] ?>"><img src="<?php echo $upload['thumbUrlPath2'] ?>" width="<?php echo ($upload['thumbWidth2']/2) ?>" height="<?php echo ($upload['thumbHeight2']/2 )?>" alt="" /></a> <div id='ajaxlink' onclick="keepSubmission(<?php echo "'$recNum', '$newValue'" ?>)">CLICK TO ACCEPT THIS SUBMISSION</div> <div id='ajaxlink' onclick="removeSubmission(<?php echo "'$recNum', '$newValueR'" ?>)">CLICK TO REMOVE THIS SUBMISSION</div> <?php if($upload['info1']):?>Title: <?php echo $upload['info1']?><?php else :?><span style="color:#C30">No Title</span><?php endif ?> <?php if($upload['info2']):?>Medium: <?php echo $upload['info2']?><?php else :?><span style="color:#C30">No Medium</span><?php endif ?> <?php if($upload['info3']):?>Dimensions: <?php echo $upload['info3']?><?php else :?><span style="color:#C30">No Dimensions</span><?php endif ?> <?php if($upload['info4']):?>Price: <?php echo $upload['info4']?><?php else :?><span style="color:#C30">No Price</span><?php endif ?>
<?php endforeach ?> <?php endforeach ?>
You may have noticed that the Ajax scripts have a url attached to each. These pages are where the actual database updating occurs. Here's the code for those.
A page with the update code for 'keep' called keep2017.php:
<?php // load viewer library $libraryPath = 'cmsAdmin/lib/viewer_functions.php'; $dirsToCheck = array('/your_servre_path/','','../','../../','../../../'); foreach ($dirsToCheck as $dir) { if (@include_once("$dir$libraryPath")) { break; }} if (!function_exists('getRecords')) { die("Couldn't load viewer library, check filepath in sourcecode."); }
$newValue = mysql_escape($_REQUEST['newValue']); mysqlStrictMode(false); $query = "UPDATE `{$TABLE_PREFIX}uploads` SET info5 = '$newValue' WHERE num = '".mysql_escape( $_REQUEST['recNum'] )."'"; mysql_query($query) or die("MySQL Error:\n". htmlspecialchars(mysql_error()) . "\n"); $userNum = mysql_insert_id(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta name="robots" content="noindex,nofollow" /> </head> </body> </html>
And a page with the update code for 'remove' called remove2017.php:
<?php // load viewer library $libraryPath = 'cmsAdmin/lib/viewer_functions.php'; $dirsToCheck = array('/your_servre_path/','','../','../../','../../../'); foreach ($dirsToCheck as $dir) { if (@include_once("$dir$libraryPath")) { break; }} if (!function_exists('getRecords')) { die("Couldn't load viewer library, check filepath in sourcecode."); }
$newValueR = mysql_escape($_REQUEST['newValueR']); mysqlStrictMode(false); $query = "UPDATE `{$TABLE_PREFIX}uploads` SET info5 = '$newValueR' WHERE num = '".mysql_escape( $_REQUEST['recNum'] )."'"; mysql_query($query) or die("MySQL Error:\n". htmlspecialchars(mysql_error()) . "\n"); $userNum = mysql_insert_id(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta name="robots" content="noindex,nofollow" /> </head> </body> </html>
To allow the exhibition manager to see just those images that were accepted I set up keepviewer.php
With the following active code:
In the head:
<script type = "text/javascript"> function removeSubmission(recNum, newValue ){ ajaxUrl = "remove2017.php?submit=1&recNum=" + escape(recNum)+"&newValue=" + escape(newValue); $.ajax({ url: ajaxUrl, }).done(function() { //add code here if anything needs to happen after the ajax call alert("Submission Removed"); }); } </script>
And in the body:
<?php foreach($exhibition_submissionsRecords as $record) : ?> <?php foreach ($record['submission images'] as $upload): ?> <?php if (strpos($upload['info5'], 'eep')) : ?> <?php // keep the price but replace any text with 'remove' ?> <?php $remove = 'remove' ?> <?php $oldValue = $upload['info5'] ?> <?php $newValueR = preg_replace('/[^0-9 .]/','', $oldValue) ?> <?php $newValueR = ($newValueR. $remove) ?> <?php $recNum = $upload['num'] ?>
followed by the code to display the images and info values
I also included ajax scripting on that page to allow for removal of the submission. <div id='ajaxlink' onclick="removeSubmission(<?php echo "'$recNum', '$newValue'" ?>)">CLICK TO REMOVE SUBMISSION</div>
A few small changes will convert that to a remove viewer with scripting to allow the supmission to be re-accepted
*****************************************
Just for completeness, here's the code for remove.php with only one variable 'recNum' (I was not using info5 for anything so I could just change it from '0' to '1' and back again.)
<?php mysqlStrictMode(false); $query = "UPDATE `{$TABLE_PREFIX}uploads` SET info5 = '1' WHERE num = '".mysql_escape( $_REQUEST['recNum'] )."'"; mysql_query($query) or die("MySQL Error:\n". htmlspecialchars(mysql_error()) . "\n"); $userNum = mysql_insert_id(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta name="robots" content="noindex,nofollow" /> </head> </body> </html>
And the changed code in the ajax script:
<script type = "text/javascript"> function removeSubmission( recordNum ) { ajaxUrl = "remove.php?submit=1&recNum=" + escape(recordNum); $.ajax({ url: ajaxUrl, }).done(function() { //add code here if anything needs to happen after the ajax call alert("Submission Removed"); }); } </script>
Finally, to allow displaying the alert on the page, add the following to the head:
<script type="text/javascript"> <!-- function MM_nbGroup(event, grpName) { //v6.0 var i,img,nbArr,args=MM_nbGroup.arguments; if (event == "init" && args.length > 2) { if ((img = MM_findObj(args[2])) != null && !img.MM_init) { img.MM_init = true; img.MM_up = args[3]; img.MM_dn = img.src; if ((nbArr = document[grpName]) == null) nbArr = document[grpName] = new Array(); nbArr[nbArr.length] = img; for (i=4; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) { if (!img.MM_up) img.MM_up = img.src; img.src = img.MM_dn = args[i+1]; nbArr[nbArr.length] = img; } } } else if (event == "over") { document.MM_nbOver = nbArr = new Array(); for (i=1; i < args.length-1; i+=3) if ((img = MM_findObj(args[i])) != null) { if (!img.MM_up) img.MM_up = img.src; img.src = (img.MM_dn && args[i+2]) ? args[i+2] : ((args[i+1])? args[i+1] : img.MM_up); nbArr[nbArr.length] = img; } } else if (event == "out" ) { for (i=0; i < document.MM_nbOver.length; i++) { img = document.MM_nbOver[i]; img.src = (img.MM_dn) ? img.MM_dn : img.MM_up; } } else if (event == "down") { nbArr = document[grpName]; if (nbArr) for (i=0; i < nbArr.length; i++) { img=nbArr[i]; img.src = img.MM_up; img.MM_dn = 0; } document[grpName] = nbArr = new Array(); for (i=2; i < args.length-1; i+=2) if ((img = MM_findObj(args[i])) != null) { if (!img.MM_up) img.MM_up = img.src; img.src = img.MM_dn = (args[i+1])? args[i+1] : img.MM_up; nbArr[nbArr.length] = img; } } } //--> </script>
|
PRE-CHECKING ALL ENTRIES MARKED AS ‘DEFAULT’ IN A MULTI VALUE CHECK BOX LIST - Dec 11th, 2015
With a lot of help from Ross Fairbairn, Interactive Tools’ consulting Guru, we came up with this method, based on the following assumptions.
1. You have a multi-record section with one text field for each check box entry. For this example I’ve called the section “entries”. It has at least one text field. For this example the text field is called “list_entry”.
2. You have a another multi-record section with a multi-value check box list field. For this example I’ve called the section “listings” and the list field “my_list”.
3) the “my_list” field gets it’s options and values from the “entries” section using the Get Options From Database (advanced) method, with: Section Table Name > entries Option Values > num Option Labels > list_entry
The first step is to go to your "entries" section and make note of the records numbers for the list_entry records you want to set as default in the multi-value"my_list” check box field when you create a new “listings” section record.
Let's say you pick list_entry 1, 7 and 16.
The second step is to go to section editors under the admin menu and modify the “listings” Section Editor.
Choose the “my_list” field and enter the record numbers you chose (1,7, and 16) into the "Default Values" field, separated by tab characters.
The only method that worked for me was to open my notepad text editor, entering a tab character in a blank text document by pressing the tab key on my keyboard, then highlighting and copying (CTL-C) the tab character to my clipboard. I could then paste (CTL-V) that character after entering each record number.
The result was:
1(tab)7(tab)16(tab) NOTE:(you won’t actually see the (tab), but there should be a multi-character long space between the record numbers.
Save this field and the section details. When you create a new record in the “Listings” editor, the “my_list” entries that you entered as defaults will be pre-checked. (You can still uncheck those entries and/or check other entries in the list as required.)
Note that this will only affect new records, it will not change existing records.
|
BLOGS
|
CREATING A BLOG (UPDATED FOR MYSQLI) - Jul 22nd, 2019
I recently put together a blog on one of my client’s sites and I thought I’d put the recipe up just in case someone could benefit from it.
BACKGROUND: The blog editor (called ‘blog’) has a title, date, contents and an image upload field. Image thumbnail2 is set for a max width of 200 px and a max height of 300 px
The client didn’t want to allow comments from others so that’s not included in the code. If they had, I would have used either the Website Comments plugin or a 3rd party solution like http://www.gentlesource.com/comment-script/ , http://www.phpjabbers.com/post-comment/ , http://www.adriantnt.com/products/comments_script/ , or http://js-kit.com/comments/
The images are padded and wrapped in the contents by the following css:
.pad { border-right: 20px solid transparent; border-bottom: 10px solid transparent; border-top: 5px solid transparent;} img { border:hidden;} img.floatLeft {float: left; margin: 10px;} img.floatRight {float: right; margin: 4px; }
I’ve allowed the visitor to decide if they want to view the earliest or most current posts first and retaining their choice for subsequent searches.
The use of the letters a and b in the form for added security are explained in the post called: ALLOWING VISITORS TO SET VIEWER ORDERBY OPTIONS
The number of records shown on the main viewer page is set in a single record editor called ‘common_information’.
A major key to creating the blog is the code that produces a listing of unique months and years for existing articles to act as an archive of blog posts.
Another was being able to display the archive month and year once at the top of the page, next to the word Archives
Here’s the code for the main blog page (blog1.php):
<span class="heading_font">Have It Your Way</span> <form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<select name="order"> <option value="b">earliest date at the top</option> <option value="a">most recent date at the top</option> </select> <input type="submit" name="submit" value="Click/Tap To Choose Display Order"> </form> <?php $orderBy = "date"; if (@$FORM['order'] == 'b') { $orderBy = "date"; } if (@$FORM['order'] == 'a') { $orderBy = "date DESC"; }
?> <?php $record_limit = $common_informationRecord['record_limit'] ?> <?php if (@!$record_limit ) { $record_limit1 = ""; } ?> <?php if (@$record_limit >=1 ) { $record_limit1 = $common_informationRecord['record_limit']; } ?>
<?php // load records from 'blog' list($blogRecords, $blogMetaData) = getRecords(array( 'tableName' => 'blog', 'loadUploads' => true, 'allowSearch' => false, 'orderBy' => $orderBy, 'limit' => $record_limit1, )); ?> <table width="50%" border="0" align="center" cellpadding="10"> <tr> <td width="75%" align="left" valign="top"><table width="100%" border="0" align="left" cellpadding="2"> <?php foreach ($blogRecords as $record): ?> <tr> <td align="left" ><hr /> <span class="text_font_bold"><?php echo date("D, M jS, Y ", strtotime($record['date'])) ?> <?php echo strtoupper($record['title']) ?></span> <div class=" pad" style="float:left"> <div style="float:none"> <?php foreach ($record['image'] as $upload): ?> <a target="_blank" href="<?php echo $upload['urlPath'] ?>"> <img src="<?php echo $upload['thumbUrlPath2'] ?>" width="<?php echo $upload['thumbWidth2'] ?>" height="<?php echo $upload['thumbHeight2'] ?>" alt="" /></a> <?php endforeach ?> </div> </div> <span class="text_font"><?php echo $record['content'] ?></span></td> </tr> <?php endforeach ?> </table></td> <td width="25%" align="left" valign="top"><p><span class="page_title_font"> Or Select An Archive</span> <?php // get list of unique months and years with articles $query = "SELECT DATE_FORMAT(date, '%M %Y') as dateAndYear, YEAR(date) as year, MONTH(date) as month FROM cms_blog GROUP BY dateAndYear ORDER BY date"; $result = mysqli()->query($query) or die("MySQL Error: ". htmlspecialchars(mysqli()->error) . "\n"); while ($record = $result->fetch_assoc()): ?> <a href="blog2.php?date_year=<?php echo $record['year'] ?>&date_month=<?php echo $record['month'] ?>&orderBy=<?php echo $orderBy ?>"><?php echo $record['dateAndYear']; ?> </a> <?php endwhile ?> </td> </tr> </table>
And here’s the code for the archive page (blog2.php)
<span class="heading_font">Have It Your Way</span> <form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>"> <input type="hidden" name="date_year" value="<?php echo @$_REQUEST['date_year']; ?>"> <input type="hidden" name="date_month" value="<?php echo @$_REQUEST['date_month']; ?>"> <input type="hidden" name="orderBy" value="<?php echo @$_REQUEST['orderBy']; ?>"> <select name="order"> <option value="b">earliest date at the top</option> <option value="a">most recent date at the top</option> </select> <input type="submit" name="submit" value="Click/Tap To Choose Display Order"> </form> <?php $orderBy =$_REQUEST['orderBy']; ?> <?php if (@$FORM['order'] == 'b') { $orderBy = "date"; } if (@$FORM['order'] == 'a') { $orderBy = "date DESC"; }
?>
<?php // load records from 'blog' list($blogRecords, $blogMetaData) = getRecords(array( 'tableName' => 'blog', 'loadUploads' => true, 'allowSearch' => false, 'orderBy' => $orderBy, )); ?> <table width="50%" border="0" align="center" cellpadding="10"> <tr> <td width="75%" align="left" valign="top"><table width="100%" border="0" align="left" cellpadding="2"> <tr> <td align="center"><?php $date_year = $_REQUEST['date_year']; ?> <?php $date_month = $_REQUEST['date_month']; ?> <?php $date = @$_REQUEST['date_year']."-".@$_REQUEST['date_month']."-28"; $formattedDate = date("F Y", strtotime($date)); ?> <span class="page_title_font"><?php echo $formattedDate ?> Blog Posts</span> </td> </tr> <?php foreach ($blogRecords as $record): ?> <?php $record_year = date("Y", strtotime($record['date'])) ?> <?php $record_month = date("n", strtotime($record['date'])) ?> <?php if (($date_year == $record_year) && ($date_month == $record_month) ):?> <tr> <td align="left" ><hr /> <span class="text_font_bold"><?php echo date("D, M jS, Y ", strtotime($record['date'])) ?> <?php echo strtoupper($record['title']) ?></span> <?php if($record['image'] ):?> <div class=" pad" style="float:left"> <div style="float:none"> <?php foreach ($record['image'] as $upload): ?> <a target="_blank" href="<?php echo $upload['urlPath'] ?>"> <img src="<?php echo $upload['thumbUrlPath2'] ?>" width="<?php echo $upload['thumbWidth2'] ?>" height="<?php echo $upload['thumbHeight2'] ?>" alt="" /></a> <?php endforeach ?> </div> </div> <?php endif ?> <span class="text_font"><?php echo $record['content'] ?></span></td> </tr> <?php endif ?> <?php endforeach ?> </table></td> <td width="25%" align="left" valign="top"><span class="page_title_font"> Or Select An Archive</span> <?php // get list of unique months and years with articles $query = "SELECT DATE_FORMAT(date, '%M %Y') as dateAndYear, YEAR(date) as year, MONTH(date) as month FROM cms_blog GROUP BY dateAndYear ORDER BY date"; $result = mysqli()->query($query) or die("MySQL Error: ". htmlspecialchars(mysqli()->error) . "\n"); while ($record = $result->fetch_assoc()): ?> <a href="blog3.php?date_year=<?php echo $record['year'] ?>&date_month=<?php echo $record['month'] ?>&orderBy=<?php echo $orderBy ?>"><?php echo $record['dateAndYear']; ?></a> <?php endwhile ?></td> </tr> </table>
|
USING A PULL DOWN FORM FIELD TO SHOW AVAILABLE DATES - Jun 7th, 2014
Showing available dates issue got a bit more complicated when I wanted to use a pull down form field instead of a list to show the available date options.
I've made this a separate example to keep the code as simple as possible.
For this example you’ll need to create a multi-record section with at least a Date field called ‘publication_date’ and a text field called ‘title’ and a checkbox field called ‘hidden’.
Note: change ‘your_table_name’ to the name of the table that you’ve created (in 2 places). Put a viewer_functions.php call at the top of both viewers, and a list records call for your table at the top of your available_date_test2.php viewer.
With a bit of help from Chris Waddell from Interactive Tools, I came up with the following code for my available_date_test.php viewer (the one with the form):
<?php // get list of unique months and years with records $query = "SELECT DATE_FORMAT(publication_date, '%M %Y') as dateAndYear, YEAR(publication_date) as year, MONTH(publication_date) as month FROM cms_your_table_name WHERE `hidden` = 0 GROUP BY dateAndYear ORDER BY publication_date DESC"; $result = mysql_query($query) or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n"); ?>
<form method="POST" action="available_date_test2.php"> <select name="dateAndYear" style="width:350px;" > <option value="">Choose A Date</option> <?php while ($record = mysql_fetch_assoc($result)):?> <option class="body-text" value="<?php echo $record['dateAndYear'] ?>"><?php echo $record['dateAndYear']; ?></option><?php endwhile ?></select> <input type="submit" name="submit" value="Go To Records" style="width:200px; "></form>
And this code for the available_date_test2.php page that show records filtered by the date chosen:
<?php @list($date_month, $date_year) = explode(' ', @$_REQUEST['dateAndYear']); // create the variables $date_month and $date_year split on space ?> <?php $date = @$date_year."-".@$date_month."-28";
// According to Jason Sauchuk - This creates a "date" variable based on the 2 variables in the string (we use 28 for the "day" since all months will have at least 28 days. This number isn't important, but it helps php decipher which variables are months, days, and years).;
$formattedDate = date("F Y", strtotime($date));
// This formats that date into the form Month Year. You can then output $formattedDate where ever you want to. ?> Records with a date field of <?php echo $formattedDate ?> <?php foreach ($your_tableRecords as $record): ?> <?php $record_year = date("Y", strtotime($record['publication_date'])) // format the $record_year variable to show only the 4 digit year ?> <?php $record_month = date("F", strtotime($record['publication_date'])) // format the $record_month variable to show the full name of the month ?> <?php if (($date_year == $record_year) && ($date_month == $record_month) ):?> <?php echo $record['title'] ?><hr> <?php endif ?> <?php endforeach; ?>
|
SORTING BLOG POSTS BY KEYWORDS IN MULTIPLE FIELDS AND AN AVAILABLE DATE FILTER ON ONE VIEWER - Jan 7th, 2019
The previous recipes addressed a basic approach to creating a Blog or Articles editor (really the same thing unless you are allowing user posts on your blog).
Here’s an approach that puts the pieces together.
It uses a single viewer, and allows visitors to search by multiple field keyword criteria, or to filter their results from a list that only contains available dates (Month and Year), and put all of this in a neat set of pull down form fields.
The approach uses 2 forms (one for the keyword searches and one for the available date filters) and sets a variable called $archive depending on which one is used (I’m sure that there’s a more elegant way to do this, and welcome anyone’s input).
The 2 fields that are set for keyword searches in this example are ‘article_type’ and ‘publication’, and the date filter uses month and year.
You’ll need to set up 3 multi-record tables to follow this example:
A table called article_types with one text field called ‘title’ A table called publication_names with one text field called ‘title’ A table called Articles with the following minimum set of fields
A date field called publication_date A text field called article_title 2 list fields, one called ‘article_type and the other called ‘publication’ (these get their option values and option labels from the other 2 tables)
Here’s the code:
At the top of your page
<?php require_once "/path_to_your_server/html/cmsAdmin/lib/viewer_functions.php";
list($article_typesRecords, $article_typesMetaData) = getRecords(array( 'tableName' => 'article_types', ));
list($publication_namesRecords, $publication_namesMetaData) = getRecords(array( 'tableName' => 'publication_names', ));
?>
And in the body:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>"> <input type="hidden" name="archive" value="0"> <table > <tr> <td><select name="article_type_keyword" style="width:350px; "> <option value="">Choose An Article Type To Display</option> <?php foreach ($article_typesRecords as $record): ?> <option value="<?php echo $record['num'] ?>"><?php echo $record['type'] ?></option> <?php endforeach ?> </select></td> <td><input type="submit" name="submit" value="Filter Your Page" style="width:200px; "></td> </tr> <tr> <td><select name="publication_keyword" style="width:350px; " > <option value="">And/Or Choose A Publication To Display</option> <?php foreach ($publication_namesRecords as $record): ?> <option value="<?php echo $record['num'] ?>"><?php echo $record['publication_name'] ?></option> <?php endforeach ?> </select></td> <td><INPUT TYPE="submit" VALUE="Cancel Search Filters" style="width:200px; "></td> </tr> </table> </FORM> <br /> <?php // insert block 1 (Form) for displaying only current year's articles here ?> <?php list($articles_by_ericaRecords, $articles_by_ericaMetaData) = getRecords(array( 'tableName' => 'articles_by_erica', 'loadUploads' => true, //'allowSearch' => false, 'orderBy' => 'publication_date DESC', ));
?> <?php // get list of unique months and years with articles ?> <?php // remove this code for years only: %M and , MONTH(publication_date in the $query ?> <?php $query = "SELECT DATE_FORMAT(publication_date, '%M %Y') as dateAndYear, YEAR(publication_date) as year, MONTH(publication_date) as month FROM cms_articles_by_erica WHERE `hidden` = 0 GROUP BY dateAndYear ORDER BY publication_date DESC"; $result = mysql_query($query) or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n"); ?> <form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>"> <table > <tr> <td ><input type="hidden" name="archive" value="1"> <select name="dateAndYear" style="width:350px;" > <option value="">Or, Display Articles By Publication Date</option> <?php while ($record = mysql_fetch_assoc($result)):?> <option value="<?php echo $record['dateAndYear'] ?>"><?php echo $record['dateAndYear']; ?></option> <?php endwhile ?> </select></td> <td><input type="submit" name="submit" value="Filter By Date" style="width:200px; "></td> </tr> </table> </form> <?php @$archive = $_REQUEST['archive']; ?> <?php if(@$archive== 0 || @$archive==""):?> <?php // beginning of replaced code block 2 for displaying only current year's articles ?> <br /> <table > <?php foreach ($articles_by_ericaRecords as $record): ?> <tr> <td ><?php echo $record['article_title'] ?> <?php if (($record['publication'] && !$record['publication'] =="") ||($record['publication_date'] && !$record['publication_date'] =="") ||($record['article_type'] && !$record['article_type'] =="")):?> <br /> ( <?php endif ?> <?php // end of replaced code block 2 for displaying only current year's articles ?> <?php if ($record['publication'] && !$record['publication'] ==""):?> <?php echo $record['publication:label'] ?> - <?php endif ?> <?php if ($record['publication_date'] && !$record['publication_date'] ==""):?> <?php echo date("F Y ", strtotime($record['publication_date'])) ?> - <?php endif ?> <?php if ($record['article_type'] && !$record['article_type'] ==""):?> <?php echo $record['article_type:label'] ?> <?php endif?> <?php if (($record['publication'] && !$record['publication'] =="") ||($record['publication_date'] && !$record['publication_date'] =="") ||($record['article_type'] && !$record['article_type'] =="")):?> ) <?php endif ?> <br /><hr /></td> </tr> <?php endforeach; ?> </table> <?php endif ?> <?php if(@$archive== 1):?> <br /> <h3>Articles by Publication Date</h3> <?php // remove this code for years only: $date_month, ?> <?php @list($date_month, $date_year) = explode(' ', @$_REQUEST['dateAndYear']); // split on space ?> <hr /> <table > <?php foreach ($articles_by_ericaRecords as $record): ?> <?php $record_year = date("Y", strtotime($record['publication_date'])) ?> <?php // remove this code for years only: <?php $record_month = date("F", strtotime($record['publication_date'])) ?>
<?php $record_month = date("F", strtotime($record['publication_date'])) ?> <?php // remove this code for years only: && ($date_month == $record_month) ?> <?php if ((@$_REQUEST && $archive == 1) && ($date_year == $record_year) && ($date_month == $record_month) ):?> <tr> <td ><?php echo $record['article_title'] ?> <?php if (($record['publication'] && !$record['publication'] =="")||($record['publication_date'] && !$record['publication_date'] =="") ||($record['article_type'] && !$record['article_type'] =="")):?> <br /> ( <?php endif ?> <?php if ($record['publication'] && !$record['publication'] ==""):?> <?php echo $record['publication:label'] ?> - <?php endif ?> <?php if ($record['publication_date'] && !$record['publication_date'] ==""):?> <?php echo date("F Y ", strtotime($record['publication_date'])) ?> - <?php endif ?> <?php if ($record['article_type'] && !$record['article_type'] ==""):?> <?php echo $record['article_type:label'] ?> <?php endif?> <?php if (($record['publication'] && !$record['publication'] =="")||($record['publication_date'] && !$record['publication_date'] =="") ||($record['article_type'] && !$record['article_type'] =="")):?> ) <?php endif ?> <br /> <hr /></td> </tr> <?php endif?> <?php endforeach; ?> </table> <?php endif?>
Two permutations of this approach is to show only the current years articles as default and to list 'sort by date' archives by year instead of month and year.
A) To show only the current year's articles as default: 1) Search for <?php // insert block 1 (Form) for displaying only current year's articles here ?> above and insert the following code:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>"> <input type="hidden" name="submitted" value="0"> <table align="center" width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="left"><INPUT TYPE="submit" VALUE="Clear Other Filters And Show All <?php echo date("Y")?> Articles" style="width:92%; background-color:#7F0000;"></td> </tr> </table> </FORM> <br />
2) Search for <?php // beginning of replaced code block 2 for displaying only current year's articles ?> and <?php // end of replaced code block 2 for displaying only current year's articles ?> above and replace that code with the code below:
<?php // begin show this year's articles only code ?> <?php if(@$submitted == '' || @$submitted == "0"):?> <br /> <h3>All <?php echo date("Y")?> Articles Only</h3> <table align="center" width="100%"> <?php $curYearCount = '0' ?> <?php foreach ($articles_by_ericaRecords as $record): ?> <?php $pubYear1 = date("Y", strtotime($record['publication_date']))?> <?php $curYear1 = date("Y")?> <?php if ($pubYear1 == $curYear1):?> <?php $curYearCount++ ; ?> <?php endif ?> <?php endforeach ?> <?php foreach ($articles_by_ericaRecords as $record): ?> <?php $pubYear = date("Y", strtotime($record['publication_date']) )?> <?php $curYear = date("Y")?> <?php if(($pubYear == $curYear) && $curYearCount >= 1 ):?> <tr> <td colspan="2"><span class="Medium-Text-Bold"><?php echo $record['article_title'] ?></span><span class="Medium-Text"> <?php if (($record['publication'] && !$record['publication'] =="") ||($record['publication_date'] && !$record['publication_date'] =="") ||($record['article_type'] && !$record['article_type'] =="")):?> <br /> ( <?php endif ?> <?php if ($record['publication'] && !$record['publication'] ==""):?> <?php echo $record['publication:label'] ?> - <?php endif ?> <?php if ($record['publication_date'] && !$record['publication_date'] ==""):?> <?php echo date("F Y ", strtotime($record['publication_date'])) ?> - <?php endif ?> <?php if ($record['article_type'] && !$record['article_type'] ==""):?> <?php echo $record['article_type:label'] ?> <?php endif?> <?php if (($record['publication'] && !$record['publication'] =="") ||($record['publication_date'] && !$record['publication_date'] =="") ||($record['article_type'] && !$record['article_type'] =="")):?> ) <?php endif ?> </span><br /></td> </tr> <tr> <?php if ($record['article_url']): ?> <?php if(!preg_match("/^https:\/\//i", $record['article_url'] )):?> <?PHP if (!preg_match("/^http:\/\//i", $record['article_url'])) { $record['article_url'] = "http://" . $record['article_url']; } ?> <?php endif ?> <?php endif ?> <?php if ($record['image']):?> <td style="padding-left:10px; padding-top:10px; text-align:left;" align="center" ><?php $article_url = $record['article_url'] ?> <?php foreach ($record['image'] as $index => $upload): ?> <a target="_blank" href="<?php echo $record['article_url'] ?>"><img style=" padding-right:10px; border:hidden;" src="<?php echo $upload['thumbUrlPath2'] ?>" width="<?php echo $upload['thumbWidth2'] ?>" height="<?php echo $upload['thumbHeight2'] ?>" alt="" /></a><br /> <?php if($upload['info1'] ):?> <span class="Small-Text">Photo by:<<br /> <?php echo htmlencode($upload['info1']) ?></span> <?php endif ?> <?php endforeach ?></td> <?php else :?> <td> </td> <?php endif ?> <td <?php if(!$record['image'] ):?>colspan="2" <?php endif?> valign="top" class="Medium-Text"><?php echo $record['article_description'] ?><br /> <a target="_blank" href="<?php echo $record['article_url'] ?>"><?php echo $record['article_link_text'] ?>... (read more)</a> <?php $the_article = $record['article_url'] ?> <br /> <?php foreach ($on_line_article_commentsRecords as $record): ?> <?php if ($record['link_url'] == $the_article ) :?> <br /> <?php if(!preg_match("/^https:\/\//i", $record['link_url'] )):?> <?PHP if (!preg_match("/^http:\/\//i", $record['link_url'])) { $record['link_url'] = "http://" . $record['link_url']; } ?> <?php endif ?> <a href="http://www.ericaminer.com/comments.php?match_url=<?php echo $record['link_url'] ?>"><?php echo $common_informationRecord['comments_link_text'] ?></a> <?php break ?> <?php endif ?> <?php endforeach ?> </td> </tr> <tr> <td colspan="2"><hr /></td> </tr> <?php endif ?> <?php endforeach; ?> </table> <?php endif?> <?php if (@$curYearCount == 0 && (@$submitted == '' || @$submitted == "0") ): ?> <h3>So far, there are no articles published for <?php echo ($curYear) ?>.<br /> <br /> Please use the pulldown above to select <?php echo ($curYear-1) ?> and earlier articles.</h3><?php endif ?> <?php // end show this year's articles only code?>
B) To modify the 'Search by Date' archive to display by year instead of month and date you'll need to remove all references to 'month' in the code above. (There are 4 ) Search for the 4 occurrences of remove this code for years only: in the code above and remove the indicated code. You can also change any notes to reflect your changes.
|
IF STATEMENTS
|
UNDERSTANDING AND USING IF STATEMENTS - Jun 19th, 2011
The if statement is one of the most powerful and valuable operators that you can use when designing your pages. You can test for many different scenarios and have your page output (or not output) specific code, depending on the outcome of your tests.
The problem is that many times, if you’ve made a mistake in your coding, you’ll get a blank page displayed in your browser and have no idea what your mistake was.
So here’s a short primer on the correct way to use this powerful tool.
The first rule to remember is that every (series of) if statement(s) must be closed with an <?php endif ?> in order for them to work correctly.
The second rule is that if you’re using a series of if statements, then the first one is always an “if”, the last is always “else” and any in the middle are “elseif”.
So, if you’re using only one if statement to test for a particular condition. Say to test whether the field “your_field” is empty, then you’d use:
In a single record viewer:
<?php if ($your_tableRecord['your_field']): ?> ...your code... <?php endif ?>
Or in a multi record viewer:
<?php foreach ($your_tableRecords as $record): ?> <?php if ($record['your_field']): ?> ...your code... <?php endif ?> <?php endforeach; ?>
YOU CAN ALSO PUT AN IF STATEMENT AROUND A BLOCK OF TEXT TO KEEP IT FROM BEING RUN IF THERE ARE NO RECORDS AVAILABLE.
<?php if ($your_tableRecord['your_field']): ?> <?php foreach ($your_tableRecord['your_field'] as $upload): ?>
... code to be run...
<?php endforeach ?> <?php endif ?>
IF YOU WANTED TO TEST FOR PARTICULAR CONTENTS IN “YOUR_FIELD”.
Say, if the contents of “your_field” equaled “apples” then, you’d use the exactly equal to “==” operator:
In a single record viewer:
<?php if ($your_tableRecord['your_field'] == 'apples'): ?> ...your code... <?php endif ?>
Or in a multi record viewer:
<?php foreach ($your_tableRecords as $record): ?> <?php if ($record['your_field'] == 'apples'): ?> ...your code... <?php endif ?> <?php endforeach; ?>
IF YOU WANTED TO TEST FOR THE ABSENCE OF PARTICULAR CONTENTS IN “YOUR_FIELD”.
Say, if the contents of “your_field” was anything other than “apples” then, you can use the not operator “!” :
In a single record viewer:
<?php if (!$your_tableRecord['your_field'] == 'apples'): ?> ...your code... <?php endif ?>
Or in a multi record viewer:
<?php foreach ($your_tableRecords as $record): ?> <?php if (!$record['your_field'] == 'apples'): ?> ...your code... <?php endif ?> <?php endforeach; ?>
TO USE A SERIES OF IF STATEMENTS TO TEST FOR A SERIES OF CONDITION, THEN YOU’D USE:
in a detail viewer:
<?php if ($your_tableRecord['your_field'] == 'apples'): ?> ...your field contains apples... <?php elseif ($your_tableRecord['your_field'] == 'bananas'): ?> ...your field contains bananas... <?php else: ?> ...your code... <?php endif ?>
And in a list viewer:
<?php foreach ($your_tableRecords as $record): ?> <?php if ($record['your_field'] == 'apples'): ?> ...your field contains apples... <?php elseif ($record['your_field'] == 'bananas'): ?> ...your field contains bananas... <?php else: ?> ...your code... <?php endif ?> <?php endforeach; ?>
YOU’RE NOT LIMITED TO A SINGLE OR A SINGLE FIELD CONDITION.
To test for multiple conditions, you can use:
(Note: The “!” works in this too)
<?php if ($your_tableRecord['field_a'] == 'apples' && $your_tableRecord['field_b'] == 'bananas' && $your_tableRecord['field_c'] == 'pears'): ?> ...Your record has all three... <?php endif ?>
Or
<?php foreach ($testRecords as $record): ?> <?php if ($record['field_a'] == 'apples' && $record['field_b'] == 'bananas' && $record['field_c'] == 'pears'): ?> ...Your record has all three... <?php endif ?> <?php endforeach; ?>
IF YOU WANTED TO TEST FOR THREE CONDITIONS IN A LIST VIEWER RECORD.
Say, “field_a” empty, “field_b” empty and “field_c” not empty, you could use:
<?php if (!$record['field_a'] && !$record['field_b'] && $record['field_c']): ?> ...your code... <?php endif ?>
IF YOU WANTED TO TEST FOR ANY OF A SERIES OF CONDITIONS.
Say a or b or c, you could use:
<?php if ($your_table Record['your_field'] == "apples" || $your_tableRecord['your_field'] == "bananas" || $your_tableRecord['your_other_field'] == "pears"): ?> Your code... <?php else: ?> Your code... <?php endif ?>
Or
<?php if ($record['your_field'] == "apples" || $record['your_field'] == "bananas" || $record['your_other_field'] == "pears"): ?> Your code... <?php else: ?> Your code... <?php endif ?>
IF YOU WANT TO TEST TO SEE IF A FIELD CONTAINS A PARTICULAR ALPHANUMERIC PATTERN
Like seeing if apples is included in a multi item list, you can use the strpos function. Theoretically the strpos function returns the numeric position of the first occurrence of the pattern that you’re searching for, however, before it can do that it has to decide if the pattern exists in the string.
To test for the pattern “apples” in the string “bananas, apples, pears, raisins” you could use something like:
<?php if (strpos($your_table['your_field'], 'apples')): ?> Your code... <?php endif ?>
This is by far not a comprehensive list of the possibilities for using if statements, but it should be enough to get you started.
Before leaving this topic, I was curious as to the rules for requiring an <?php endif; ?> to close an "if" statement.
Jason Sauchuk, a programmer with Interactive Tools cleared up the question:
"You only need <?php endif ?> if your "if" statement covers more than 1 <?php?> block.
Example:
<?php if($x==1?> ----some code--- <?php endif ?>
This could also be put into 1 <?php ?> block with no <?php endif ?>, as in:
<?php if($x==1){ ---some code-- } ?>
|
IF STATEMENTS THAT MEET MORE THAN ONE CONDITION - Aug 3rd, 2010
If you’ve got a table called “people and two fields “price” and “description” and you need a specific result depending on whether there’s information in one, the other or both fields, you can approach it this way. Remember that the operator “!” means not so !$record['price'] means that there’s no information in the price field.
<!-- If there’s no price and no description, just show the title. –> <?PHP foreach ($peopleRecords as $record): ?> <?PHP if (!$record['price'] && !$record['l_description']): ?><?PHP echo $record['title'] ?><?PHP endif ?>
<!-- If there’s no price, just a description , offer information only. –> <?PHP if (!$record['print_price'] && $record['full_description']): ?><a href=”<?PHP echo $record['_link'] ?>”><?PHP echo $record['title'] ?></a>Click the title for more information.<?PHP endif ?>">
<!-- If there’s a price and no description, ask for the sale. –> <?PHP if ($record['price'] && !$record['description']): ?><a href=”<?PHP echo $record['_link'] ?>”><?PHP echo $record['title'] ?></a>Click the title to buy.<?PHP endif ?>
<!-- If there’s a price and a description, offer information and ask for the sale. –> <?PHP if ($record['price'] && $record[description']): ?><a href=”<?PHP echo $record['_link'] ?>”><?PHP echo $record['title'] ?></a>Click the title the for more information or to buy.<?PHP endif ?> <?PHP endforeach ?>
|
USING IF STATEMENTS TO DEFINE OUTPUT BASED ON A FILE EXTENSION - Aug 16th, 2011
If you need to publish specific code that’s based on the type of file that you’ve uploaded into an upload field, like a .swf flash file, here’s the trick. Just use:
<?php if ($upload['extension'] == 'swf'): ?>
or for the second through next to last if parameter in the list (the last one gets an <?php else: ?> instead of a <?php elseif...)
<?php elseif ($upload['extension'] == 'swf'): ?>
You can use this for non upload fields as well:
<?php if ($your_fieldRecord['extension'] == 'doc'): ?>
or
<?php elseif ($your_fieldRecord['extension'] == 'doc'): ?>
Don’t forget that every if statement must be closed with an <?php endif ?>
|
SETTING UP "IF" STATEMENTS FOR NO RECORDS MATCHING A CRITERIA - Apr 1st, 2012
This one plagued me for a while until Jason Sauchuk, a programmer with Interactive Tools came to the rescue.
I had a checkbox field in a multi-record editor and I wanted to be able to output a “no records found with the checkbox checked” message if there were no records with the checkbox checked.
Here’s what he offered:
<?php $ischeck= 0; ?> <?php foreach ($e_blast_events_noticeRecords as $record): ?> <?php if($record['apbc_event']==1) $ischeck=1; ?> <?php endforeach ?> <?php if ($ischeck==0) echo "no records found."; ?>
I could have also added:
<?php if ($ischeck==1) echo "records were found."; ?>
In the previous recipe, I was using a "where" statement to restrict which dates are displayed in a group. The code I used to show only events that had a start date or a reception date in the next 7 days was:
<?php list($my_tableRecords, $my_tableMetaData) = getRecords(array( 'Table name' => 'my_table', 'where' => '(NOW() + INTERVAL 7 DAY) >= event_reception_date AND event_reception_date >= TIMESTAMP(CURDATE(), "00:00:00") OR (NOW() + INTERVAL 7 DAY) >= event_start_date AND event_start_date >= TIMESTAMP(CURDATE(), "00:00:00")', )); ?>
If there were no records that met the criteria, I wanted to output the same kind of “no records found” notice.
This was one I should have been able to figure out but I just couldn’t come up with a solution. Again, Jason came to the rescue. He suggested a simple solution:
<?php if(!$e_blast_events_noticeRecords) echo "No events are opening or have a reception during the next 7 days."; ?>
And
<?php if($e_blast_events_noticeRecords) echo "These events are opening or have a re | |