text:
GettingStarted:first_application,74,"Creating your First Application","==Creating Your First Application==
Build a simple Xataface application.
For our first Xataface application we will try to build a web site for Faculty of Widgetry (From the example in the ""Why Use Xataface"" page). The web site needs to store information about programs and courses. An entity-relationship diagram (ERD) for this website is included below:
As the ERD shows, our database will need 2 tables (Course and Program). Our next step is to build this database. You can use any MySQL database administration tool to builld the database. My personal tool of choice is PHPMyAdmin.
===Step 1: Creating the database using PHPMyAdmin===
The following steps describe the procedure for creating this database using PHPMyAdmin.
# At the main menu of PHPMyAdmin, type 'FacultyOfWidgetry' into the 'Create new database field' as follows: OK, I guess some explanations are in order.
The first line imports the all of the public functions for dataface from the dataface-public-api.php file.
The second line initializes the application for the current directory and specifies the URL to the dataface installation.
The third line obtains an instance to the Application object - the core of your Dataface application.
The fourth line simply displays the application. Explanations: There are 2 sections in this INI file: '_database', and '_tables'.
The '_database' section specifies the database connection information for the MySQL database.
The '_tables' section specifies which tables will be included in the navigation menu for the application.
Note, however, that there is also an .htaccess file that is hidden from this image. You may be wondering why there is no 'tables' directory like the directory structure that was generated by the makesite script. The 'tables' directory is not required for the application to be functional. It will be required later on when we start to decorate the database. Note that it is important for ALL of your tables to have Primary keys. If a table is missing its primary keys, some strange behavior may occur with relationships involving that table.
The above defined table will serve as a join table between 'Program' and 'Course'
And now we can remove the 'ProgramID' field from the 'Course' table.
ALTER TABLE Course DROP ProgramID
This means that all courses for which a (ProgramID, CourseID) pair matches the CourseID of the course and the ProgramID of the source Program record are included in the relationship.
This looks almost the same as before. Notice, however that now there is an ""Add Existing Courses Record"" button at the top. This is because with a many-to-many relationship, you are able to add related records in 2 ways: In this case it is probably more appropriate to define the afterInsert trigger because we really only want to send the notification email after the insert has successfully taken place. Therefore, we will define the afterInsert() method in our delegate class as follows:
CREATE TABLE `Course` (
`CourseID` int(11) NOT NULL auto_increment,
`ProgramID` int(11),
`CourseTitle` varchar(64) NOT NULL default '',
`CourseDescription` text NOT NULL,
`HTMLOutline` text NOT NULL,
`PDFOutline` longblob NOT NULL,
`PDFOutline_mimetype` varchar(64),
`Subject` varchar(128) NOT NULL default '',
`CourseNumber` varchar(10) NOT NULL default '',
`Credits` int(5) NOT NULL default '0',
`LastModified` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`CourseID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='Store courses' AUTO_INCREMENT=1 ;
#In a similar fashion, create the Program table. The resulting SQL for this table is:
CREATE TABLE `Program` (
`ProgramID` int(11) NOT NULL auto_increment,
`ProgramName` varchar(64) NOT NULL default '',
`ProgramDescription` text NOT NULL,
`HTMLOutline` text NOT NULL,
`PDFOutline` longblob NOT NULL,
`PDFOutline_mimetype` varchar(32),
`AdmissionDeadline` date NOT NULL default '0000-00-00',
`LastModified` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`ProgramID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='Academic Program' AUTO_INCREMENT=1 ;
# The database has been created with 2 tables: Program and Course. We can now move on to building the Xataface application.
===Step 2: Create Xataface Application===
Our Xataface application will provide a user-friendly front-end to our database. A basic application consists of a directory with a configuration file and an entry page (PHP file). Xataface comes with a PHP setup script (called makesite) to create the skeleton for your application. Alternatively you can set up the application manually.
Note: For the following instructions and examples, my Daface installation is located at /Users/shannah/Sites/dataface and the URL for the installation is http://localhost/~shannah/dataface.
====Method 1: Setting up application with the 'makesite' script====
# From the command prompt, navigate to the dataface directory. (in my case ''/Users/shannah/Sites/dataface'').
# This directory contains a file named 'makesite'. It is a PHP script that can be used to build a website powered by Xataface. To find out the usage options for this script you can simply call the script with no parameters. E.g.,
stevepbook:~/Sites/dataface shannah$ ./makesite
# This will give you usage instructions for the script as follows:
makesite: invalid options entered.
Usage: makesite
# We create our FacultyOfWidgetry site using the following command:
./makesite ../FacultyOfWidgetry \
root@localhost/FacultyOfWidgetry \
# This will create our application in the FacultyOfWidgetry folder if everything worked ok. The contents of the folder will look like:
mkdir FacultyOfWidgetry
# Create a PHP file to serve as the access point for the application. Generally we will name this file 'index.php', but you can name it anything. Place the following contents in the index.php file:
require_once '/path/to/dataface/dataface-public-api.php';
df_init(__FILE__, 'http://yourdomain.com/dataface');
$app =& Dataface_Application::getInstance();
host = ""localhost""
user = ""dbuser""
password = ""secret""
name = ""FacultyOfWidgetry""
Course = ""Course""
Program = ""Program""
# The directory structure of your application will now look like:
Course.ProgramID = ""$ProgramID""
This little snippet defines a relationship named 'Courses' on the 'Program' table. 'Program' is the source table. 'Course' is the destination table. There are no join tables because this is only a one-to-many relationship. You may be wondering what the $ProgramID means. This is a variable that represents the value of the 'ProgramID' field in the source record. This relationship specifies that courses whose 'ProgramID' field matches the value of the 'ProgramID' field in the source record, are related to the source record. The english language makes this seem more difficult and complex than it really is.
Let's check out our changes. Since we have defined the relationship on the 'Program' table, we will click on the 'Program' link in the navigation menu:
Notice that there is now a 'course' tab at the top of the page. Click on this tab to see the courses that are related to this Program (as defined by our 'Courses' relationship). If it says that ""No records matched the request"" or something to that effect, then you don't have any Course records in the relationship yet. Just click the ""Add New Courses Record"" button in the upper left to add a course. If there are courses in the relationship, then the Courses tab will look something like:
Currently there is only one course in the program, but we can add more. If you click on the ""Add New Courses"" button in the upper left, you will be presented with a new course form that will allow you to add a new course in this Program.
===Example 2: Making the 'Courses' relationship a Many-to-Many relationship===
Example 1 shows how Xataface can handle a one-to-many relationship. Now we will alter the database a little bit and turn this into a many-to-many relationship.
# Add a table named 'ProgramCourses' to the database. The SQL table definition for this table should be something like:
CREATE TABLE `ProgramCourses` (
`ProgramID` INT( 11 ) NOT NULL ,
`CourseID` INT( 11 ) NOT NULL ,
PRIMARY KEY ( `ProgramID` , `CourseID` )
INSERT INTO ProgramCourses( ProgramID, CourseID )
SELECT ProgramID, CourseID
FROM Course
Course.CourseID = ProgramCourses.CourseID
ProgramCourses.ProgramID = ""$ProgramID""
Course.ProgramID = ""$ProgramID""
This also could have been defined as follows:
__sql__ = ""SELECT * FROM Course WHERE ProgramID='$ProgramID'""
'''Note: Make sure you use two underscores on either side of 'sql' in the above example. It should be '__sql__' not '_sql_'.'''
The two syntaxes are equivalent. In fact, the former will be converted into the later by Xataface behind the scenes.
Now let's look at example 2's relationships.ini file:
Course.CourseID = ProgramCourses.CourseID
ProgramCourses.ProgramID = ""$ProgramID""
This could have been written as:
__sql__ = ""SELECT *
FROM ProgramCourses, Course
WHERE Course.CourseID = ProgramCourses.CourseID
AND ProgramCourses.ProgramID = '$ProgramID'""
The two are equivalent. This example, however, shows how defining a relationship using SQL can be beneficial. The above SQL query will work but it can be done better using Joins as follows:
__sql__ = ""SELECT *
FROM ProgramCourses pc
INNER JOIN Course c ON pc.CourseID = c.CourseID
WHERE pc.ProgramID = '$ProgramID'""
All of these 3 methods will produce the same results, but the last one will probably give a little bit better performance.
===Relationship Restrictions===
Xataface has built-in logic to figure out how to add new and existing records to relationships that you define, as long as your relationships obey a few guidelines.
# All tables must have a Primary key
# The WHERE clause of your SQL definition for the relationship must contain only '=' comparisons, and 'AND' conjunctions. i.e., it cannot receive an 'OR' conjunction, nor can comparisons be done using '>', or '<'. This is because given 'AND' and '=' conjunctions it is easy for Xataface to be able to add records that will satisfy the relationship. If an 'OR' conjunction is used, it makes it ambiguous (though this will probably be corrected in future Xataface releases.
===Download Source Files===
[http://xataface.com/documentation/tutorial/getting_started/facultyofwidgetry-8-tar.gz Download the source files for this application as a tar.gz archive]",relationships,en,
Triggers are methods that can be defined to carry out custom behaviors when certain events occur in the application (e.g., when records are saved, inserted, or deleted).
Triggers are generally regarded as one of the more advanced features of database applications. Despite the ""advanced"" status of triggers, however, they are very simple to use and can be leveraged by Xataface developers to add powerful functionality to their applications.
So what can you do with a trigger?
* Send a confirmation email every time a new record is inserted into a table.
* Delete records related to a record that is being deleted (to maintain the consistency of the database).
* Add custom logging functionality.
* Add extra permissions or validation rules (although these are probably better handled with the validation framework).
You can really do just about anything you want with a trigger. A trigger is essentially just a custom PHP method that is called by Xataface when certain events occur.
===What triggers are available?===
As of version 0.5.3 Xataface supports the following triggers:
* '''beforeSave''' : called just before a record is saved (either inserted or updated).
* '''afterSave''' : called just after a record is saved (either inserted or updated).
* '''beforeInsert''' : called just before a record is inserted.
* '''afterInsert''' : called just after a record is inserted.
* '''beforeUpdate''' : called just before a record is updated.
* '''afterUpdate''' : called just after a record is updated.
* '''beforeDelete''' : called just before a record is deleted.
* '''afterDelete''' : called just after a record is deleted.
* '''beforeAddRelatedRecord''' : called just before a related record (new or existing) is added to a relationship.
* '''afterAddRelatedRecord''' : called just after a related record (new or existing) is added to a relationship.
* '''beforeAddNewRelatedRecord''' : called just before a new related record is added.
* '''afterAddNewRelatedRecord''' : called just after a new related record is added.
* '''beforeAddExistingRelatedRecord''' : called just before an existing related record is added.
* '''afterAddExistingRelatedRecord''' : called just after an existing related record is added.
===How do you define a trigger?===
Triggers are always defined as methods of the delegate class for a table. As an example, suppose we wanted to add a trigger to send a the administrator a notification email every time a new record is inserted into the 'Course' table. The steps would be as follows:
# Create a delegate class for the 'Course' table (if one does not already exist) by creating a file named 'Course.php' inside the 'tables/Course' directory.
# Add the following to the Delegate class file to make it a valid delegate class:
class tables_Course {}
# Okay, we want our trigger to be called every time a record is inserted. There are 2 possible triggers that can be defined, then:
class tables_Course {
* Trigger that is called after Course record is inserted.
* @param $record Dataface_Record object that has just been inserted.
function afterInsert(&$record){
mail('email@example.com','Subject Line', 'Message body');
# That's all for now. The afterInsert() method defined above will automatically be called every time a record is inserted into the Course table. This method, as we have defined it, will send a notification email to the administrator email.
===Sending feedback to the user===
The above example sends the email without any feedback to the application's user of whether the email succeeded or not. When the user inserts a new Course he will only see that the record was succesfully saved, but no mention is made of the email. The following example does the same thing as the previous one, except that it sends a confirmation to the user when the email has been successfully sent:
function afterInsert(&$record){
$response =& Dataface_Application::getResponse();
// get reference to response array
if ( mail('firstname.lastname@example.com', 'Subject Line', 'Message Body') ){
$response['--msg'] .= ""\nEmail sent to firstname.lastname@example.com successfully."";
} else {
$response['--msg'] .= ""\nMail could not be sent at this time."";
Now, when the user inserts a new record he will see a confirmation as follows:
Notice that we used the Dataface_Application::getResponse() function to obtain a reference to the application's response array. The response array is just a global array that is shared by the entire application that allows you to pass information easily from one part of the application to another. The '--msg' index of array is where you can place text that you wish to have displayed to the user as a confirmation.
'''Note''': It is important to use '=&' to assign the result of Dataface::getResponse() and not just '='. e.g.:
$response =& Dataface_Application::getResponse(); // correct!
$response = Dataface_Application::getResponse(); // WRONG!!
This is because we need a reference to the response array, not a copy. That way when we assign a value to the '--msg' index it is applied to the actual response array and not a copy of it.
===Handling Errors===
The above method of sending messages to the user is useful for notifications and confirmations. However, in some cases you want to inform the user that an error occurred and cancel further operations. For example you may want to disallow a record to be inserted if a confirmation email cannot be sent. In this case we define the beforeInsert() trigger and return a PEAR_Error object if the email fails as follows:
class tables_Course {
function beforeInsert(&$record){
$response =& Dataface_Application::getResponse();
if ( mail('email@example.com', 'Notification', 'Your record was created')){
$response['--msg'] .= ""\nEmail sent successfully to firstname.lastname@example.com"";
} else {
return PEAR::raiseError(
""Errors occurred while sending email. Record could not be inserted"",
This trigger is called just before a course record is inserted into the database. If the mail succeeds, then the user sees a success message. If it fails, on the other hand, the insert is cancelled, and the user will see a message as follows:
'''Note''': Notice the use of the DATAFACE_E_NOTICE constant as a second parameter for PEAR::raiseError(). This is important as without it Xataface will display a less user-friendly error message complete with stack trace. If the error is such that you want a complete stack trace, you can use the DATAFACE_E_ERROR constant instead.","triggers, beforeSave, afterSave, beforeInsert, afterInsert,sending email",en,
GettingStarted:using_first_app,75,"Using Your First Application","==Using Your First Application==
A Web Lite application, at its core, provides 4 standard operations: Add new records, edit existing records, delete records, and find records. This section gives a brief overview of how to use your first Dataface application.
When you first create your Xataface application and there are no records in the database, the application will look quite plain. If you point your web browser to your newly created application it will look something like:
You may be wondering why it says ""No records matched your request"" when you haven't even really made a request. This is because the 'default' request that is performed if no other request is specified is to show the first record from the first table in the navigation menu. Since there are no records, it is true that there are NO records matching the default request.
So what can you do with this application anyways? Essentially there are 4 operations you will want to perform:
# Create new records
# Edit Existing records
# Find records
# Delete records
==Basic Navigation==
The navigation tabs (aka Navigation menu) at the top left represent the tables in your database. You can navigate to any of the tables in this list by clicking on that table:
There are 3 ""views"" associated with tables in the database:
* '''Details''' - Shows the details of a single record in the table
* '''List''' - Shows the records in the current ""found set"" as a list. (in a table).
* '''Find''' - Allows users to find records matching certain criteria.
You can toggle between these 3 views using the tabs at the top of the page:
===The ""Found Set""===
Throughout this tutorial you will see the phrase ""found set"" an awful lot, so it is important to understand just what this means. A ""found set"" is the set of all records in the current table that match the current ""find criteria"". This begs the question, ""what is 'find criteria'?"". By default there is no find criteria. When you perform a search or a find on the current table, you add ""find criteria"" so that only the records satisfying these criteria will be included in the ""found set"".
For example, if you click on the ""find"" tab, you will get a search form that allows you to search for records that match certain criteria. The ""find"" tab for the ""Course"" table in our application looks like:
If you type in ""English"" in the ""Subject"" field and click ""Find"", then the ""found set"" will consist of only records that contain the word ""English"" in their subject fields.
On the top left of the application window there will always be a ""Found"" line that indicates how many records are currently in the found set. e.g.,
This indicates that there are 256 records in the current table (which is the 'Groups' table). There are currently only 225 records in the current ""found set"" (meaning that we have performed a ""find"" operation and it matched 225 of the records). It also indicates that the currently displayed record is record number 1 out of the 225 found records.
===The Actions Menu===
Just below the view tabs ('details', 'list', and 'find') there are a few buttons that allow you to perform actions such as create new records, clear find parameters (i.e. Show All), and delete records.
* '''new record''' - Creates a new record in the current table.
* '''show all''' - Clears all find criteria on current table so that all records are shown.
* '''delete''' - Deletes the current record in the table.
* '''delete found records''' - Deletes all records in the current ""found set"". If no find criteria is specified this will delete all records in the table.
===Creating new records===
The basic FacultyOfWidgetry application that we created in the previous section isn't very interesting when it doesn't contain any records, so let's create some Program records.
# Select the ""Program"" table by clicking on the ""Program"" option of the navigation menu.
# Click ""new record"" in the actions menu (top left).
# This will bring up a form to insert a new record that looks like:
validators:required = true
validators:required:message = ""Username is required""
Placing the above inside the fields.ini file will cause the Username field to be a required field.
===Example 2: Username must be between 6 and 16 characters long===
For this rule we will use a regular expression.
validators:regex = ""/^.{6,16}$/""
validators:regex:message = ""Username must be between 6 and 16 characters long""
===Example 3: Email field must contain a valid email address===
validators:email = true
validators:regex:message = ""Email must contain a valid email address""
===Available validation rules===
Xataface uses the PEAR library HTML_Quickform for validation, so any of the validators available in this package will be available in Xataface. Some of the available validation rules include:
* required
* maxlength
* rangelength
* regex
* email
* emailorblank
* lettersonly
* alphanumeric
* numeric
* nopunctuation
* nonzero
===Default validation rules===
There are certain validation rules that are automatically applied to fields of with certain characteristics. For example, any field designated NOT NULL in the SQL table definition will automatically be a 'required' field. At the time of this writing, that is the only 'default' validation rule applied, but more may be added in the future if their addition makes sense.
","form validation,required field,validation rules",en,
GettingStarted:valuelists,77,"Using Valuelists","==Using Value-lists==
Value-lists serve as vocabularies that can be used for fields such as select lists, checkbox groups, and auto-complete fields.
So far we have not used any enumerated fields such as select lists, checkbox groups, or auto-completion fields in our examples. This is because we are missing a key ingredient that is required by all of these widget types: a vocabulary. We need a way to define options for these fields.
This is where 'valuelists' come into play. A valuelists is essentially a list of key-value pairs that can be used as a vocabulary in enumerated fields like checkbox groups, select lists, and auto-completion fields. Valuelists are defined in the valuelists.ini file in each table's configuration directory.
===Example 1: Use a select list for the Subject field in the Course table===
The ""Subject"" field in the ""Course"" table really shouldn't be a free-form field that will accept any value. The user should just be able to pick from a finite list of subjects in a select list. To make these changes we will follow these steps:
# Create the configuration directory for the ""Course"" table if it does not exist yet.
# Create a file named 'fields.ini' inside the Course table's configuration directory (i.e., tables/Course/fields.ini), if it does not already exist.
# Create a file named 'valuelists.ini' inside the Course table's configuration directory (i.e., tables/Course/valuelists.ini) if it does not already exist.
Your application directory structure should now look like:
ENGL = English
MATH = Math
PHYS = Physics
CHEM = Chemistry
This defines a valuelist named 'Subjects' with values {ENGL, MATH, PHYS, CHEM} and associated labels {English, Math, Physics, Chemistry}. The values (i.e., ENGL, MATH, etc..) represent what will be stored in the database, and the values is a user-friendly representation that will be displayed on the screen.
# Now we edit the fields.ini file so that it looks like:
widget:type = select
vocabulary = Subjects
This tells Xataface that we want to use a select widget to edit the ""Subject"" field, and its values should be drawn from the ""Subjects"" valuelist.
#Navigate to the ""Course"" table in our application and select ""new record"" from the ""Actions to be performed menu"" in the top left.
===Example 2: Using a checkbox group for the 'Subject' field===
In Example 1, we showed how to use a select list for the 'Subject' field in the 'Course' table. This is great if each course can only be one subject. But what if a course can be categorized in 2 subject areas. Then we will need a widget the allows you to select multiple items. Checkbox groups work well for this.
Make a change to the 'fields.ini' file for the 'Course' table to change the widget:type attribute of the 'Subject' field to 'checkbox' as follows:
widget:type = checkbox
vocabulary = Subjects
Now load the form again and notice that the 'Subject' field is now represented by checkboxes.
You may be wondering how we store multiple values in a single field. In this case Subject is treated as a 'repeat' field where each value is on a separate line. I.e., with the form above, if we clicked 'save' and checked the values stored in the database we would see:
As the value in the 'Subject' field. Please note that if you are going to use a repeating field like this, you should make sure that the field is 'big' enough to store all of the values. E.g., I think my Subject field was a VARCHAR(64) (64 characters long), so the sum of the lengths of all of the values 'checked' for 'Subject' should be less than 64.
===Example 3: Dynamic Valuelists based on the results of SQL queries===
Example 1 & 2 demonstrated the basic idea of valuelists and how they can be used as values for select lists and checkbox groups. However defining valuelists ""statically"" inside the valuelists.ini file doesn't really seem to offer anything over using and ENUM or SET field in the MySQL database. In many cases we want the user to be able to choose from a number of options that are pulled from the database. For example, we may want the user to be able to specify the Program that a Course belongs to, using a pull-down list.
Recall that when we created the 'Course' table we included a field named 'ProgramID' to store the ID number of the Program that this course belongs to. It would be unreasonable to expect the users of your application to remember the ID number of the Program to which the course belongs when they are filling in the 'Course' form. It would be much better if the user could choose the program from a list of available programs. Fortunately, this functionality is simple to add:
# Add a valuelist named 'Programs' to the valuelists.ini file for the 'Course' table as follows:
__sql__ = ""SELECT ProgramID, ProgramName FROM Program ORDER BY ProgramName""
'''Note: Make sure you use two underscores on either side of 'sql' in the above example. It should be '__sql__' not '_sql_'.'''
widget:type = select
vocabulary = Programs
Now we can load up our form and see what it looks like:
We can see that the ProgramID field now appears with a select list of all of the programs in the database. The HTML code for the select list is:
===Download Source Files===
[http://xataface.com/documentation/tutorial/getting_started/facultyofwidgetry-7-tar.gz Download application source files as tar.gz archive]
These source files reflect the application's state at this point in the tutorial. As changes are made to the application in later sections, modified source archives will be available to be downloaded.
In this section, we have learned how to use valuelists to add selection lists and checkbox groups to our web forms. We also shows how valuelists can be dynamically defined using SQL. Using valuelists in this way is like defining a many-to-one relationship to our database (in example 3, it was many 'Course' records to one 'Program' record). In the next section we will learn how to add many-to-many and one-to-many relationships to our database in such a way that records can be easily added and removed from relationships using Xataface.","valuelists, __sql__, select lists, checkbox options,checkbox groups,vocabularies",en,
GettingStarted:Why_Use_Xataface,72,"Why Use Xataface","==Why Use Xataface?==
Some simple examples similar to those that are frequently encountered by web developers, and how dataface can be used to acheive a solution.
As a web services developer in the Faculty of Applied Sciences at Simon Fraser University, I am frequently getting requests to build websites that are manageable by the site owner. Most of these requests also specify certain types of content that must be stored on the website, and much of this content needs to be n-ary (i.e., there will be multiple instances of each type of content). Let me give you an example.
===Example 1: Website for Faculty of Widgetry===
The Faculty of Widgetry needs a website to publish information about its undergraduate programs. It is important for them to be able to publish admission requirements, and program overviews for each program. It is also important to have course outlines and timetables for each course. The Faculty of Widgetry has 12 undergraduate programs and over 100 courses offered.
====Solution 1: Static HTML====
To build this web site using only static HTML pages using Dreamweaver or some other HTML editor would require at least 112 pages to be created (one for each course and program). However, once we recognize that there are only 2 types of pages required (one for courses and one for programs), we can reduce the task down to creating 2 templates and filling in the main content for each program and course individually. Most HTML editors have some templating ability so you can make changes to the template and have the changes propogated to all pages that use that template with the click of a button.
This works great, but courses are added frequently, and outlines are changed. Do you really want to receive requests to update all of these pages every time there are changes to make? (If your answer is 'yes', then you probably won't be interested in reading the rest of this tutorial). Whether the Dean of the faculty knows it or not, it is very important for the program assistants to be able to update these web pages on their own. To acheive these goals you can:
* Install Dreamweaver on the Program Assistants' computers, teach them how to use it, and allow them to perform updates.
* Install Contribute, which is a scaled down version of Dreamweaver to make it easier for the Program Assistants to edit the content.
* Use another solution that is equivalent to one of the above 2 solutions.
Installing Dreamweaver for each Program Assistant is a little overkill, and since it has the ability to do much more than just update content. In addition, Dreamweaver is really a developer's tool - not a secretary's tool, so it can be difficult to learn at first. The best reason NOT to install Dreamweaver on the Program Assistant's computer, however, is that it enables him/her to muck things up by accident (believe me, I has happened to me more times than I care to count).
Admittedly, Contribute is a viable option as it controls access to only certain portions of web pages to be edited, and it is targetted at secretaries (not developers) so it is easier to use. In fact, given the requirements for this web site (as stated above), this is a perfectly good solution. However you better hope that none of the following requirements are added:
* Each program web page should contain an up-to-date list of all of the courses required for the program, along with a link to the course outline for that course.
* Course outlines should be available in PDF format as well as HTML format.
* An index page showing all of the courses available should be added. This page must allow courses to be organized by program, course subject, or course number.
* Any other requirement that would have information formatted in more than one way.
If any of these requirements are likely to be added (EVER) then you would be well-advised to look into solutions that use a database back-end.
====Solution 2: Use a Content Management System (CMS)====
There are hundreds of content management systems available that will allow you to store and update content through the web (TTW). Some of them even have an assortment of add-ons that will allow you to store more specific types of information. Some good CMS's include Plone, Drupal, and Xoops. Suppose we want to develop the Faculty of Widgetry website using one of these CMS's. Any good CMS will allow you to create and edit HTML documents easily (without having to write any custom products). However, it is often the case that our documents require the content to be structured. For example, each program has some common data associated with it: Program Name, Admission Deadline, Program Description, Outline, Courses, etc... If we want to properly separate data from presentation, we would need to build a special content-type to store our programs. Most CMS's allow you to develop custom content-types using the underlying programming language and an API (Application Programming Interface). Some API's are easier to use than others and some are documented better than others. The common element is that each has its own proprietary interface for writing these add-ons.
If you are using a CMS and you are proficient in the creation of add-on content-types, then you will be able to build the Faculty of Widgetry website without great difficulty. However there are a number of reasons why you may choose NOT to use a CMS:
* Steep learning curve: Depending on the CMS it can be very time consuming and difficult to learn how to use and modify the CMS to suit you purposes.
* It is over-kill: Most CMS's are filled with features and modules that you will never need. In fact it can even be a pain to turn them off if you don't want them.
* You can get tied into the CMS: When you are using a CMS, you will start developing for the CMS. With all of your content in the CMS it may be difficult to migrate to a different solution later on. (The truth of this statement will vary for different CMS's). Choose your CMS carefully.
====Solution 3: Use an existing Application====
OK, OK, let's not get too carried away with trying to develop the website until we have checked the market to see if someone else has already done it better. Maybe there is already a PHP application that makes websites for Faculties easy. I mean, I can't be the first person that needed to build a website for a Faculty. In fact if you do a search or go to Hotscripts.com, you will probably find a handful of applications or scripts that almost do what you need. If you're lucky, maybe you can find an application that does exactly what you need (but frankly, I've never been that lucky). If you find one, maybe it's worth taking it for a test drive. But beware. Using a system that almost does what you need but is difficult to modify to your needs can be worse than building it by scratch. Make sure that you are able to modify the application to suit your needs exactly.
====Solution 4: Use PHP and MySQL====
If all we want to do is separate the data from the presentation and allow the Program Assistants to update data on the website, why not just design a MySQL database with the appropriate tables and fields to store the required data. In our case we will need 2 tables:
* Fields:
** ProgramID : int
** ProgramName : varchar
** ProgramDescription: text
** AdmissionDeadline: date
** Outline_HTML : text
** Outline_PDF : blob
* Fields:
** CourseID : int
** CourseSubject : varchar
** CourseTitle : varchar
** CourseNumber : int
** ProgramID : int
** CourseDescription : text
** Outline_HTML : text
** Outline_PDF : blob
Now it's easy to create a few web pages that extract data from the database and displays it as HTML. In fact if there is an existing page template that you can use for the header and footer, you can develop the entire Faculty website in under an hour (you just have to create 3 pages).
'''Question''': How will the Program Assistants update the information in the database?
'''Answer''': OK, let's assume that you're not going to teach them SQL and that a DB Admin tool will also be too difficult to learn. Then you have to create HTML forms to update records in the database.
Ouch! What was easy just became hard. Making HTML forms is a real pain, because you have to validate the input, deal with file uploads, and also make sure that everything is stored to the database OK without losing any information. Such a basic task, but it can be very difficult. This is when it is time to use Xataface.
====Solution 5: Use Xataface====
OK, this isn't really its own solution. It is more like ""Solution 4 Part II"", because Xataface is intended to complement your custom application you built with solution 4, by providing an easy-to-use, configurable user interface that is targeted at secretaries and normal users (as opposed to database administrators). A Xataface application takes only seconds to set up and it will provide you with a full user interface for your users to edit information in the database.","introduction motivation why",en,
Grafted_fields,158,"Grafted fields","==Grafted Fields==
When there are numerous tables, it is difficult for the user to see get an information that will help one to enter the right data in the right field. So instead of navigating in the relative tables and lose some time, it is more convenient to add a grafted field from that relative table in the table. To be able to sort a column by the content displayed when this content is extracted form a relative table, a grafted field is necessary because the real content is just an id, not the most convenient to sort in human-readable way.
Two ways to add a grafted filed
* The first one is to add a __sql__ statement at the beginning of fields.ini, including the grafted field through a join.
__sql__ = ""select p.*, d.total from programmation p left join dev d on p.id_programmation=d.id_programmation""
* The second one is to create the function __sql__ in the delegate class
function __sql__(){
return ""select p.*, d.total from programmation p left join dev d on p.id_programmation=d.id_programmation"";
===Sorting order based on relationship===
The solution is to hide the field with the id and to add the grafted field with the name in the fields.ini
A couple of things to check for:
*1. If you have set blanket default permissions for your fields using the __field__permissions() method you could be disallowing access to the field.
*2. If you have set default field visibility in the fields.ini file via the [__global__] section....
*3. Check to make sure that your __sql__ directive is at the beginning of the file and that it is __sql__ and not _sql_
*4. Try to enter an obviously invalid SQL query for the __sql__ directive to see if you get an error (to confirm that it is picking up the __sql__ directive at all).
","grafted fields, grafted, sorting columns, sort, relative records, relative tables",en,
grid,67,grid,"==widget:type = grid==
Suppose we have two tables, tbl_organisation and tbl_individuals, in the edit view for a record in the organisations table (tbl_organisations) we also want to be able to view and edit the individuals within this organisation we can use widget:type=grid
In the /tables/tbl_organisation/fields.ini we create a transient field by adding:
widget:label = ""Individuals""
The above assumes we have a relationship entry in our /tables/tbl_organisation/relationships.ini that looks like this:
__sql__ = ""SELECT * FROM tbl_individual WHERE org_id='$org_id'""
The fields.ini will show the three columns shown in widget:columns from the table tbl_individual
Correct permissions need to be set to enable editing and deletion etc of these records.",,en,0
group,28,group,"==group directive in [[fields.ini file]]==
The group directive allows you to declare that certain fields of your table should be grouped together on the edit form and the view tab (and other logical places). For example, fields like address, city, state, country, postal_code would likely be grouped together as address_info. Grouping the fields together will make the fields appear in a section of their own in the view tab and the edit form.
E.g. In your fields.ini file:
===Configuring the Group as a Whole===
You can also configure your group in the fields.ini file by adding a '''fieldgroup:NAME''' section, where '''NAME''' is the name of the group. E.g.
label=""Address Information""
description = ""Please enter your address information below""
====See also:====
* [[fields.ini file]] - Scroll down to the '''Field Groups''' section.",,en,0
How_to_Add_Custom_Sections_to_View_Tab,52,How_to_Add_Custom_Sections_to_View_Tab,"==How to Add Custom Sections to the View tab==
The ''View'' tab is intended to give the user a detailed view of the contents of a record. By default it shows the values of each non-empty field grouped into their appropriate field groups. It also shows the most recent 5 related records from each relationship in the record. You can also add your own sections by implementing the [[section__xxx]] method of the delegate class.
==Example 1: A ""Hello World"" Section==
We'll start by adding a simple section that simply displays ""Hello World"" to the user. In the delegate class for your table, add the following method:
function section__hello(&$record){
return array(
'content' => 'Hello World!!!',
'class' => 'main'
Now if you reload our application and click on the ""View"" tab for any of the records in the database, you'll notice a section labelled ''hello'' with the text ''Hello World!!!'' in it.
Let's dissect the above code so that we can better understand what is going on here.
# The function ''section__hello()'' defines a section named ''hello''. If you wanted to define a section named ''foo'' you would call the function ''section__foo()''
# This function returns an array with the keys ''content'', and ''class''.
# The ''content'' key points to the actual HTML content of the section. In this case it is simply the text ''Hello World!!!''.
# The ''class'' key defines where the section should be displayed. It accepts values of ''left'' and ''main'' only. If it is set to ''left'', then the section will be displayed in the left column. A value of ''main'' indicates that it should be displayed in the main column.
===Customizing the Section Label===
''hello'' is a boring label, so let's add our own custom label by adding the ''label'' key to the array returned by our method:
function section__hello(&$record){
return array(
'content' => 'Hello World!!!',
'class' => 'main',
'label' => 'Message of the Day'
Now if you load the view tab of your application, you'll notice that the section has a heading ""Message of the Day"".
===Customizing the Section Order===
A section can also specify an ''order'' attribute to define the order in which this section should appear. It defaults to 0 which may cause the section to appear at the top of the view tab. You can push it to the bottom of the view tab by assiging a higher number to the ''order'' attribute:
function section__hello(&$record){
return array(
'content' => 'Hello World!!!',
'class' => 'main',
'label' => 'Message of the Day',
'order' => 10
Now if you reload the view tab you'll notice that the section has moved to the bottom of the page.",,en,0
How_to_authenticate_users_with_LDAP_or_Active_Directory,64,How_to_authenticate_users_with_LDAP_or_Active_Directory,"==How to authenticate users with LDAP or Active Directory==
How_to_build_a_PHP_MySQL_Application_with_4_lines_of_code,38,"How to build a PHP MySQL Application with 4 lines of code","'''The [http://xataface.com Xataface Application Framework] allows you to convert your existing MySQL database into a full-fledged with as little as 4 lines of code. And it's Not a code generator.'''
This article is intended to spark interest in the [http://xataface.com Xataface Application Framework] amongst PHP developers by showing how easy it is to set up a full-featured front-end for your MySQL database. If you are a PHP developer, surly you can identify with the situation where you've built a snazzy website with PHP and MySQL but you need to create some way the website users to administer it. I.e., you need to make an administrative back-end for your users.
You need to do this because PHP admin is too technical for your users, and it is an aweful lot of tedious work to create all of the necessary forms and lists for your users to edit the data themselves.
===Features for our Application===
* Create, edit and delete records using simple web forms.
* Browse through database and find records without any SQL.
* Lots of great widgets for editing records including html editors, select lists, grids, checkboxes, calendars and more.
* Sort records.
* Export result sets as CSV or XML.
* Fully configurable and extendable by you to implement more [[about|features]].
===Creating the Application===
Here are 6 steps to a full-featured front-end for your database:
# Create a directory for your application on your webserver. Call it ''myapp''.
# Download the latest version of [http://xataface.com Xataface] and copy it into your application directory that we just created. (i.e. ''myapp/xataface''.
# Create a configuration file named ''conf.ini'' inside your application directory (i.e. ''myapp/conf.ini'') to store your database connection info:
;; This section lists the tables to include in your application menu
table1=Label for table 1
table2=Label for table 2
# Create an .htaccess (i.e. ''myapp/.htaccess'') file to prevent Apache from serving your ''conf.ini'' file:
Deny from all
'''Note: If you are not using Apache as your web server you'll need to block access to the .ini files using a different mechanism. E.g. On IIS you can create a Web.config file to block this access and place it inside your application's directory.''' Download a sample Web.config file [http://weblite.ca/svn/dataface/core/trunk/site_skeleton/Web.config here].
# Create an index.php file (i.e. ''myapp/index.php'') to serve as an access point for your application:
// first parameter is always the same (path to the current script)
// 2nd parameter is relative URL to xataface directory (used for CSS files and javascripts)
# Create a ''templates_c'' directory to store cached smarty templates or your application (i.e. ''myapp/templates_c'', and make sure that it is writable by the webserver:
$ mkdir templates_c
$ chmod 777 templates_c
That's all there is to it! Point your web browser to the index.php file we just made, and check out your new app!
===Screenshots of Our App===
====Find Form====
====New Record Form====
====List View====
===Where to go now===
# Sign up for the Xataface mailing list to receive exclusive development tips (see the left column for a signup form).
# Check out the [[about|About Xataface]] page for more information about features and requirements.
# Use the [http://xataface.com/documentation/getting_started Getting Started Tutorial] to get started making your own application.
# [http://xataface.com/videos Watch screencasts] showing Xataface in action.
","tutorial, getting started, installation, first app, 4 lines of code",en,0
How_to_granulate_permissions_on_each_field,63,How_to_granulate_permissions_on_each_field,"==How to granulate permissions on each field==
To reach this aim, there is the method fieldname__permissions to place into the delegate class of the table.
===Getting the role===
First it is necessary to know the user's role. For this, the method getUser() is added in the class :
function getUser(&$record){
$auth =& Dataface_AuthenticationTool::getInstance();
$user =& $auth->getLoggedInUser();
return $user;
===Setting up the permissions for each field===
Next, the permissions are built for each column or field where they are needed, like in this example where the method name is formed with the field name, followed by 2 underscores then by ''permissions'' :
function fieldname__permissions(&$record){
$the_user =$this->getUser($record);
if ( !$user) return Dataface_PermissionsTool::NO_ACCESS();
if ( $user=='demande' ){
return Dataface_PermissionsTool::ALL();
} elseif ($user=='admin'){
return Dataface_PermissionsTool::ALL();
else {
return Dataface_PermissionsTool::READ_ONLY();
=== Also See ===
* [[viewable_editable_fields]] - How to make a field editable for some users and only viewable for some other users
* [[no_access_text]] - Replace the default NO ACCESS permission text with another text.
* [[__field__permissions]] - Returns the default permissions for a field of a given record.
* [[Delegate_class_methods#toc5|Permissions]] - other Delegate class methods",,en,0
http://xataface.com/documentation/how-to/site_with_backoffice,85,"How to build a site with an optional login form","==How to build a site with an optional login form==
To publish a public site with data without any need to login to access, here is the code :
function getPermissions(&$record){
if ( isAdmin() ) return Dataface_PermissionsTool::ALL();
else return Dataface_PermissionsTool::READ_ONLY();
In this way, you still can login to administrate your data.",,en,
http://xataface.com/documentation/how-to/site_with_backoffice_How_to_build_a_site_with_a_backoffice_,84,"A site with a backoffice","==A site with a backoffice==
To create a site with a backoffice for the administrator, so that the visitors do not have to log in to read the pages, you add this code in the ApplicationDelegate.php file in the conf directory :
function getPermissions(&$record){
if ( isAdmin() ) return Dataface_PermissionsTool::ALL();
else return Dataface_PermissionsTool::READ_ONLY();
* [[about|About Xataface]]
* [http://xataface.com/documentation/tutorial/getting_started Getting Started Tutorial]
* [[How to build a PHP MySQL Application with 4 lines of code]]
* [[Troubleshooting]]
* [http://dataface.weblite.ca API Docs]
* [[conf.ini file]] directives
* [[fields.ini file]] directives
* [[valuelists.ini file]] directives
* [[relationships.ini file]] directives
* [[Delegate class methods]]
* [[Application Delegate Class]]
* [[permissions.ini file]] directives
* [[actions.ini file]] directives
* [[preferences|User Preferences]] - options for customizing the application further via the getPreferences() method.
* [[xataface templates|templates]]
* '''[[URL Conventions]]''' - Learn how to use Xataface's URL conventions to form URLs that return exactly the result set that you want.
* '''[[Roadmap]]''' - What is planned for the next releases of Xataface
===Cook Book===
* [[Customizing Theme Based on IP Address]] - An article on storing IP addresses in the database and showing users a different theme depending on which range of IP addresses they are connecting from.
===By Topic===
* '''[http://xataface.com/documentation/tutorial/getting_started/installation Xataface Installation Instructions]''' - This document explains how to install Xataface on your system. It does not describe how to create an application with Xataface.
* '''[http://xataface.com/documentation/tutorial/getting_started/first_application Creating your first App]''' - How to create an application using Xataface (from the Getting Started Tutorial)
* '''[[about|About Xataface]]''' - Quick overview of Xataface. Includes a 6 step example of creating an application with Xataface.
* '''[http://xataface.com/documentation/tutorial/getting_started/customizing Customizing field labels, descriptions, and widgets]''' - This document explains how to customize some basic aspects of your application's edit forms. (From the Getting Started tutorial).
* '''[http://xataface.com/documentation/tutorial/getting_started/valuelists Using Valuelists]''' - How to use valuelists to set up options for your select lists and checkbox groups.
* '''[http://xataface.com/documentation/how-to/list_tab Configuring and customizing the list tab]''' - This document explains how to customize the display of the list tab using INI files, templates, and delegate classes.
* '''[[Contribute to Xataface Translation Project]]''' - We need translators to help us keep the Xataface translations up to date. This page shows how you can help.
* '''[http://xataface.com/documentation/tutorial/internationalization-with-dataface-0.6 Internationalization with Xataface]''' (tutorial)
* '''[http://xataface.com/documentation/how-to/how-to-internationalize-your-application How to internationalize your application]''' (how to) - Xataface 0.6 contains a LanguageTool class that allows your applications to be presented in multiple languages
* '''[http://xataface.com/documentation/how-to/use-translations How to use other translations]''' - Xataface 0.7 includes German and French translations. This document explains how to allow your application to use these and other translations, rather than the default English translation.
* '''[http://xataface.com/documentation/how-to/unicode How to enable unicode support]''' - As of Xataface 0.6, unicode is fully supported so that your dataface application will work with any and multiple languages simultaneously.
* '''[http://weblite.ca/svn/dataface/core/trunk/lang Download latest language files out of SVN]''' - If you want to make sure that you have the latest translations, you can download them from SVN and place them into your xataface lang directory.
====User Interface Customization====
* '''[[preferences|User Preferences]]''' - You can hide, show, enable, and disable features of the application selectively.
* '''[http://xataface.com/documentation/tutorial/getting_started/changing-look-and-feel Changing the Look and Feel]''' - Change the way your application looks by adding custom headers, footers, and sections, and by overriding the default templates with your own custom templates. (From the Getting Started tutorial).
* [[xataface templates|templates]]
* '''[http://xataface.com/documentation/tutorial/customizing-the-dataface-look-and-feel Customizing the Xataface look and feel]''' tutorial
* '''[[Customizing the look and feel of a row or a cell| Customizing the look and feel of an element in the list view]]''' - Personnalize the aspect of each part of your list according to its content.
* '''[http://xataface.com/documentation/how-to/custom_javascripts How to include custom javascripts and stylesheets]''' - Use the custom_javascripts and custom_stylesheets blocks to include your own custom javascript and CSS files in your application.
* '''[http://xataface.com/documentation/how-to/hide_search How to hide the search box]''' - The full-text search box that appears in the upper right can easily be removed.
* '''[http://xataface.com/documentation/how-to/list_tab Configuring and customizing the list tab]''' - This document explains how to customize the display of the list tab using INI files, templates, and delegate classes.
* '''[[How to Add Custom Sections to View Tab]]''' - The ''View'' tab in a Xataface application can be configured in many ways. This tutorial shows you how to add your own custom sections to the view tab.
* '''[[Creating a Dashboard]]''' - Create a dashboard action for your users to so that they have a logical starting point in your application.
* '''[[Grafted fields]]''' - Add a grafted field to your table for user convenience. You can use it also to be able to sort columns with relative tables content.
* '''[[Clean the html for the export]]''' - Clean the HTML tags and entities for the export in CSV or XML.
====Using the API====
* '''[[Introduction to the Xataface API]]''' - A short introduction to the classes, methods, and functions available in the Xataface API.
* '''[http://xataface.com/documentation/how-to/how-to-define-custom-serialization-for-fields How to define custom serialization for fields]'''
* '''[[authentication]]''' - Overview of Xataface Authentication
* '''[[registration form]]''' - Enabling User Registration in Xataface
* '''[[permissions.ini file]]''' - Reference of the permissions.ini file directives.
* '''[http://xataface.com/documentation/tutorial/getting_started/permissions Permissions]''' - Use sessions and delegate classes to define permissions at the record and field level. (From the Getting Started tutorial).
* '''[[Cached permissions]]''' - Use cached perms for complex queries inside getPermissions()
* '''[[Delegate_class_methods#toc5|Delegate class methods]]''' - Permissions-related functions
* '''[[Relationship Permissions]]''' - Guide to permissions on related records.
* '''[http://xataface.com/documentation/how-to/disallow_tables How to disallow access to tables]'''
* '''[[site_with_backoffice]]''' - A site with a backoffice without obligation to log in
* '''[http://xataface.com/documentation/how-to/security_filters Security Filters]''' - Use security filters to block users from seeing certain records.
* '''[[How to granulate permissions on each field]]''' - Decide for each field who can edit, read...
** '''[[no_access_text]]''' - Replace the default NO ACCESS permission text with another text.
* '''[[LDAP or Active Directory]]''' - How to authenticate users with LDAP or Active Directory...
* '''[http://xataface.blogspot.com/2009/06/using-query-caching-in-xataface.html Using Query Caching]''' - Query caching can drastically improve performance of busy applications with large databases. This article explains how to enable this caching in your Xataface application.
* '''[[_output_cache]]''' - Xataface does quite a bit of heavy lifting on each page request. If your application is getting a lot of traffic that is slowing your server down, you may want to look at enabling the Xataface output cache.
* [[modules]] - Available Xataface Modules. This includes such things as CAPTCHA validation, editable javascript grids, and more.
* [[Module Developers Guide]] - A guide / Tutorial on how to develop your own Xataface modules.
* '''[http://xataface.com/documentation/tutorial/getting_started/relationships Relationships]''' - Xataface allows you to define relationships between tables using the relationships.ini file. (From the Getting Started Tutorial)
* '''[http://xataface.com/documentation/how-to/how-to-assign-order-to-related-records How to assign order to related records]''' - Sometimes it is desirable for the records in a relationship to take on a particular default order. Dataface 0.6 makes this easy if you follow a few conventions.
* '''[[Drag and Drop Reordering of Relationships]]''' - A more in-depth tutorial about adding ordering to relationships.
* '''[[relationships.ini file]] reference
* '''[[Relationship Permissions]]
* '''[http://xataface.com/documentation/how-to/DisableEnterKeyInFields How to disable the enter key in forms]'''
* '''[http://xataface.com/documentation/tutorial/getting_started/customizing Customizing field labels, descriptions, and widgets]''' - This document explains how to customize some basic aspects of your application's edit forms. (From the Getting Started tutorial).
* '''[http://xataface.com/documentation/tutorial/getting_started/valuelists Using Valuelists]''' - How to use valuelists to set up options for your select lists and checkbox groups. (From the Getting Started tutorial)
* '''[http://xataface.com/documentation/tutorial/getting_started/validation Form Validation]''' - Xataface allows you to add validation rules to fields using the fields.ini file. (From the Getting Started tutorial).
* '''[http://xataface.com/documentation/how-to/how-to-handle-file-uploads How to handle file uploads]''' - Xataface allows you to store file uploads in BLOB fields or on the file system.
* '''[http://xataface.com/documentation/how-to/custom_validation How to add custom validation with delegate classes]''' - If the standard validators (e.g., required, email, regex, etc..) don't quite cut it for your validation rules, Xataface allows you to define custom validation methods in the delegate class.
* '''[http://xataface.com/documentation/how-to/regex_validation Validating with regular expressions]''' - How to validate input into a field using regular expressions.
* '''[[Dynamic select boxes]]''' - How to create two dynamic javascript select boxes from the valuelists.
* '''[http://xataface.com/documentation/how-to/import_filters Import Filters]''' - It is common to need to import records en masse into a database. This is what import filters are for. (Since 0.7).
* '''[http://xataface.com/documentation/tutorial/getting_started/dataface_actions Actions I: The Basics]''' - Web Lite's actions framework allows you to customize existing actions (e.g. new, edit, find) and create your own new actions. (From the Getting Started Tutorial).
* '''[http://xataface.com/documentation/how-to/after_action_triggers Adding triggers to actions]''' - Xataface 0.6.1 adds some triggers to actions so that the developer can define custom functionality to be performed after an action has successfullly taken place.
* '''[[Calendar Action]]''' - Using the built-in calendar action to add a full-fledged event calendar to your application.
* '''[[Creating a Dashboard]]''' - Create a dashboard action for your users to so that they have a logical starting point in your application.
* '''[[Selected Records Actions]]''' - Create custom actions that are performed on records that have been selected in the list tab.
* '''[[Creating Printable Reports]]''' - Create a custom printable report using a custom action.
* '''[[Using RecordGrid]]''' - Using Dataface_RecordGrid to print data in tabular form.
* '''[http://xataface.com/documentation/how-to/history-howto How to activate history logging]''' - Xataface 0.6.9 comes with support for managing the history of your records. This how-to shows you how to enable and use this feature.
====RSS Feeds====
* '''[[Introduction to RSS Feeds in Xataface]]''' - Xataface provides RSS feeds to any found set in your application. This tutorial shows how it works and how you can configure these feeds to get your desired results.
====Event Calendar====
* '''[[Calendar Action]]''' - Introduction to the Xataface calendar action which can be used to convert your application into a full-fledged event calendar.
init,140,"init() Delegate Class Method","== Synopsis ==
This method is called once, just after the table is loaded for the first time. It allows you to specify initialization details, such as [[setSecurityFilters|security filters]].
Note that it takes a single parameter: a Dataface_Table object of the table that is being initialized.
== Example ==
function init(&$table){
Internet_Media_Manager,8,"Internet Media Manager","'''Manage your videos and photos all in one place'''
===Watch the Guided Tour (6 minutes)===
The Internet Media Manager is a web-based database application that allows webmasters to centrally store their images and videos to be served on their website(s). It provides a Youtube-like interface whereby users can simply copy and paste code snippets to embed images and videos into their web pages. It also provides a photo gallery component that allows users to easily embed a gallery of images into their web pages by simply copying and pasting a snippet of javascript code.
I created this application because:
# I didn't want to have to resize images in Photoshop anymore before uploading them to the web.
# I wanted to be able to embed videos, images, and photo galleries into my web pages without having to muck around with HTML code.
IMM (Internet Media Manager) allows you to resize your photos to any size you want, and embed these resized images in your web pages by copying and pasting a snippet of HTML. Similarly it makes embedding videos and photo galleries into your website a snap.
* Add/Edit/Delete/Categorize images and videos in a searchable database.
* Import multiple images or videos at once by uploading a ZIP file.
* Large file imports via FTP/SSH.
* Embed video and images directly into other web pages by copying and pasting HTML snippets (like Youtube).
* Resize images and videos.
* FLV video support (like Youtube).
* Search media by content type, category, keyword, etc..
* Includes javascript photo gallery component that can be embedded into any web page.
* Amazon Simple Storage Service (S3) integration.
* [http://www.php.net|PHP] 5.2+
* [http://www.mysql.com|MySQL] 4.1+
* [http://ca.php.net/gd|GD_Image_Processing_Library]
* [http://ffmpeg.mplayerhq.hu/|FFMPEG] (optional - if you want to automatically generate poster images for videos).
* [https://sourceforge.net/projects/immgr/files/|Internet Media Manager 0.3]
# Download the latest version from Sourceforge.
# Extract the files and copy to your web server.
# Point your web browser to the install.php and follow the instructions.
How to import multiple images at once in a ZIP archive.
Visit the [http://xataface.com/forum/viewforum.php?f=12|Support_forum].
","Internet Media Manager,resize photos,image gallery,photo gallery,video gallery",en,0
Introduction_to_RSS_Feeds_in_Xataface,40,Introduction_to_RSS_Feeds_in_Xataface,"==Introduction to RSS Feeds in Xataface==
A default Xataface application provides RSS feeds to any found set in your application. This article explains a little bit about RSS and how you can configure Xataface to give you the desired results for your RSS feed.
===What is RSS?===
From [http://en.wikipedia.org/wiki/RSS_(file_format) Wikipedia's RSS article]:
""RSS is a family of Web feed formats used to publish frequently updated works such as blog entries, news headlines, audio, and videoin a standardized format.[2] An RSS document (which is called a ""feed"", ""web feed"",[3] or ""channel"") includes full or summarized text, plus metadata such as publishing dates and authorship. Web feeds benefit publishers by letting them syndicate content automatically. They benefit readers who want to subscribe to timely updates from favored websites or to aggregate feeds from many sites into one place. RSS feeds can be read using software called an ""RSS reader"", ""feed reader"", or ""aggregator"", which can be web-based or desktop-based. A standardized XML file format allows the information to be published once and viewed by many different programs. The user subscribes to a feed by entering the feed's URI (often referred to informally as a ""URL"", although technically, those two terms are not exactly synonymous) into the reader or by clicking an RSS icon in a browser that initiates the subscription process. The RSS reader checks the user's subscribed feeds regularly for new work, downloads any updates that it finds, and provides a user interface to monitor and read the feeds.""
In a way RSS replaces email subscriptions so that you can subscribe to receive updates when content is added or changed on websites that you monitory. This way you can monitory these changes in your RSS reader so that your email box doesn't get clogged up.
===Using RSS in Xataface===
Xataface allows you to subscribe to:
# Entire tables
# Any found set
# Changes to a particular record
# Related record lists
====Example 1: Subscribing to receive news updates====
A user wants to be alerted whenever a new item is inserted into the ''news'' table, so he navigates to the ''list'' tab of the ''news'' table, and clicks the RSS Feed icon in the upper right. If he has an RSS reader application set up, this is all he has to do to subscribe to the RSS feed for the ''news'' table. When new records are inserted, he'll receive alerts in his RSS reader.
====Example 2: Subscribing to receive found set updates====
A user wants to be alerted whenever a new item is inserted into the ''news'' table that contains the phrase ""Buffalo Bills"", because he is a Buffalo Bills fan. So he navigates to the ''news'' table, and does a search for the phrase ""Buffalo Bills"". Then he clicks on the ""RSS Feed"" icon in the upper right of the result set list. If he has an RSS reader application set up, this is all he has to do to subscribe to the RSS feed for ''news'' items containing the phrase ""Buffalo Bills"". Whenever a new item is posted with this phrase, he will be notified via RSS of the new record.
====Example 3: Subscribing to a related list====
Suppose you want to receive updates whenever a particular author adds a book to his list of published works. Further suppose this is represented by a relationship between the ''authors'' table and the ''books'' table named ''publications''. You can subscribe to the RSS feed for his publications by navigating to the ''publications'' tab for that author, then clicking on the ""RSS Feed"" icon in the upper right. Now whenever this author adds a new book to his publications list, you'll be notified via RSS.
===Example usage in Xataface===
# A user wants to be alerted whenever a new item is inserted into the ''news'' table, so he navigates to the ''list'' tab of the ''news'' table, and clicks the RSS Feed icon in the upper right. If he has an RSS reader application set up, this is all he has to do to subscribe to the RSS feed for the ''news'' table. When new records are inserted, he'll receive alerts in his RSS reader.
# A user wants to be alerted whenever a new record about ""Wayne Gretzky"" is inserted in to the ''news'' table. He navigates to the ''news'' table, then performs a search for ""Wayne Gretzky"" using the top right search box. Then, he clicks on the ""RSS Feed"" icon in the upper right of the result list. Now, whenever a new item is inserted with the phrase ""Wayne Gretzky"", the user will be notified via RSS.
===Configuring RSS Feeds===
As with everything else in Xataface, you can configure your RSS feeds to appear just as you want them to. The following delegate class methods are available to be defined in the table delegate class for your feed:
{| class=""listing listing2""
! Name
! Description
! Version
| [[getFeedItem]]
| For RSS Feeds, overrides the defaults and returns an associative array with feed elements for a particular record
| 1.0
| [[getFeed]]
| For RSS feeds, overrides the default feed for a query, returning an array of feed items.
| 1.0
| getFeedSource
| Overrides the default feed source parameter for an RSS feed.
| 1.0
| getRSSDescription
| Overrides the default generated RSS description for a record.
| 1.0
| [[getSingleRecordSearchFeed]]
| Overrides the default feed for a subsearch within a record. This works identically to the [[getFeed]] method except that it takes 2 parameters: one for the current record, and a second parameter for the query.
| 1.2.3
==Example Configuration==
There are 2 parts to configuring your RSS feeds.
# Configuring the feed as a whole
# Configuring the feed items (that is each record that will appear in your RSS feed).
===Configuring the Feed as a whole===
For configuring the feed as a whole, we have 2 options. We can specify the title, description, and link for the feed in the ''[_feed]'' section of your [[conf.ini file]]. This is sort of a ""one size fits all"" approach where all feeds generated from your application will share the same title.
title=""My Site News""
description=""News updates from my site""
However, if we want our feed's information to depend on the user's query (e.g. what the user was searching for, or which table the feed is generated on, we have more flexibility if we define the [[getFeed]] method in either the [[Application Delegate Class|application delegate class]] or the [[Delegate class methods|table delegate class]]. E.g.
function getFeed($query=array()){
$params = array();
if ( @$query['-search'] ) $params['title'] = '""'.$query['-search'].'"" results';
else $params['title'] = 'All records from my table';
return $params;
Notice that I don't need to define all possible parameters. Any parameters that I don't define will be provided automatically by Xataface, or it will simply use the values specified in your ''[_feed]'' section of the [[conf.ini file]].
===Configuring Feed Items===
Configuring the feed items is quite important for ensuring that subscribers are seeing what you want them to see in the RSS feed. Xataface tries to guess appropriate content for your feed items if you don't specify it explicitly, but you'll likely want to tweak it a little bit to make the feed look more polished for your purposes.
Use the [[getFeedItem]] [[Delegate class methods|delegate class method]] to specify how a feed item behaves (e.g. the title, content, date, author, link).
function getFeedItem(&$record)){
return array(
'description' => $record->val('body')
Once again, notice that we don't need to specify all available options. Only those options that we want to override. In this case we want the description of the feed item to simply display the body of our news item. The description of an RSS feed item is effectively the body text that the user sees why they click on an item in their news reader, so this is quite important.
","RSS Feeds",en,0
Introduction_to_the_Xataface_API,101,"Introduction to the Xataface API","Back to [http://xataface.com/wiki the wiki]
Xataface is provides an API to help in developing your own custom actions. This API includes objects and functions to more easily interact with the database (i.e. search, edit, delete, and save records), build forms, use templates, and more. This section of the wiki endeavors to highlight some of the more useful and commonly used aspects of the API.
===The dataface-public-api.php Facade===
Much of the functionality provided by the Xataface API is wrapped up easy-to-use functions which are made available in the dataface-public-api.php script, which is always present in a Xataface application (it is loaded at the beginning of your index.php file).
===Some Common Tasks===
====Loading a Single Record from the Database====
// Load record from 'people' table matching person_id=10
$record = df_get_record('people', array('person_id'=>10));
// Load record from people table with first_name 'John' and last_name 'Smith'
$record2 = df_get_record('people', array('first_name'=>'=John', 'last_name'=>'=Smith'));
// $record and $record2 are Dataface_Record objects.
echo ""Loaded Person: "".$record->val('person_id').
"" named "".$record->val('first_name').' '.$record->val('last_name');
In the above examples we load a [http://dataface.weblite.ca/Dataface_Record Dataface_Record] object and use the val() method to display particular field values.
The 2nd arguments of df_get_record() is an array which serves as a query. See [[URL Conventions]] for more examples of the types of queries that you can provide here.
====Loading a set of records from the Database====
// Load the first 30 canadians from the people table
$people = df_get_records_array('people', array('nationality'=>'=canadian'));
foreach ( $people as $person){
// $person is a Dataface_Record object
echo ""
Person "".$person->val('person_id')."" is named "".$person->val('first_name');
'''Caveat: Note that when loading records using df_get_records_array() it only loads a preview of each record for memory's sake.''' A preview of the record is the same as a full record except that all fields are truncated to be less than 255 characters. If you have long text fields that you need to load, then these will be truncated. There are a few different solutions if you need to load the entire contents of a long field, including:
* Use df_get_record instead. (This is only preferable if you are only loading a single record).
* Use the [[struct]] [[fields.ini file]] directive on the field to designative the field contents as a 'stucture' that should never be truncated.
* Use the extended form of ''df_get_records_array()'' with the 5th parameter (preview) set to false. E.g.
$people = df_get_records_array('people',array(), null, null, false);
====Editing and Saving a Record====
$person = df_get_record('people', array('person_id'=>10));
// Using setValue() to set a single field value.
$person->setValue('first_name', 'Peggy');
// Using setValues() to set multiple field values at once
$person->setValues(array('first_name'=>'Peggy', 'last_name'=>'Sue'));
// Commit the changes to the database
","xataface api, df_get_record, df_get_records_array, Dataface_Record, Editing, Saving, Loading, Searching",en,
Key,83,"fields.ini Directive: Key","The '''Key''' directive is used only when the table is a view and you need to explicitly define which columns are part of the primary key. For example, if we created a view on the books table to only show books in a given year as follows:
create view books_2000 as
select * from books where year='2000'
And we wanted to use this view as a table in our Xataface application we would need to tell it that the primary key of this view is the book_id field. So in the fields.ini file we would add:
Note that this is case sensitive. key=PRI will not work.
===Compound Primary Keys===
For primary keys comprising multiple columns we would add this directive for each field in the key. E.g. if our books_2000 view had 2 fields in the primary key, say author_id and book_index, we would have in the books_2000 fields.ini file:
* [http://xataface.com/forum/viewtopic.php?f=4&t=6723 Lookup widget on view with compound primary key]
Return to [[fields.ini file]]","Key, Views, MySQL Views, Create View, PRI, Primary Keys",en,
LDAP_or_Active_Directory,65,"How to authenticate users with LDAP or Active Directory","[[toc]]
It is often easier to use the existing LDAP or Active Directory to authenticate users in Xataface than to create a new password for every user in the table users.
===In the conf.ini===
In the conf.ini file, in the [auth] part, you need to add your LDAP or AD configuration data :
users_table = xata_users
username_column = id
ldap_host = ""xxx.xxx.xxx.xxx""
ldap_port = ""389""
ldap_base = ""OU=blabla,DC=blablabla""
Here in the table users, you need the login but the password can be just ''PASS'', because the password will be fetched into the LDAP base.
You need to add the [http://weblite.ca/svn/dataface/modules/Auth/ldap/trunk/ auth module] in the conf/modules directory.
===See Also===
* [[authentication]] - Overview of Authenthentication features in Xataface","LDAP,Active Directory,Authentication",en,0
list:type,128,"list:type relationships.ini file directive","Return to [[relationships.ini file]]
The list:type directive allows you to override the default list that is used to display related records. As of Xataface 1.3 there is only one possible value that will have any effect on this directive: ""treetable"".
will cause the related records to be displayed as an expandable/collapsible tree table as shown here:
The TreeTable component needs to be able to figure out the logical children of each record in order to know what to show when a row is expanded. You can use either the [[meta:class]] directive of the [[relationships.ini]] file to specify a relationship as a ""children"" relationship, or you can implement the [[getChildren]] method of the table delegate class to manually define a record's child elements.
==See Also==
* [[getChildren]]
* [[meta:class]]
* [[getParent]]",,en,
loginFailed,184,"loginFailed() Application Delegate Trigger","[[toc]]
The loginFailed() method of the Application Delegate class is executed after a failed login attempt.
'''Available since 2.0.1'''
function loginFailed($username, $userIp, $time){
error_log(""Failed login for username: $username at IP $userIp at time $time"");
","login permissions failed password",en,
lookup,61,"The Lookup Widget","Return to [[widget:type]] page to see list of all widget types.
Back to [[fields.ini file]] to see other fields.ini directives.
The lookup widget allows users to look a record from another table to insert into the field. It is like a select widget except that it doesn't use a vocabulary. Instead you just specify a table on which it should search using the widget:table directive. In order to use the lookup widget to edit a field, you should set the [[widget:type]] directive of the [[fields.ini file]] for the field to '''lookup''. I.e.
'''Note that the lookup widget requires the [[widget:table]] directive to be set to the target table of the lookup or it will not work properly.'''
===Required Directives===
The following [[fields.ini file]] directives are required to accompany the field definition if a lookup widget is used:
{| class=""listing listing2""
! Name
! Description
! Version
| widget:table
| The name of the table in which the lookup widget should look up related records.
| 1.0
===Optional Directives===
The following additional optional directives may be used to customize the behaviour of the lookup widget:
{| class=""listing listing2""
! Name
! Description
! Version
| widget:filters:-limit
| Sets the number of records that are shown by default in the lookup widget. Default is 30 if this is omitted. E.g.widget:filters:-limit=100
to show 100 records at a time.
| 1.0
| widget:filters:-sort
| Specifies the columns to sort the results on. E.g. widget:filters:-sort=category_name asc, year desc
| 1.0
| widget:filters:*
| Any valid Xataface directive can be used to filter the results by specifying widget:filters:param (where ""param"" is a valid Xataface GET parameter, which could include a column name to filter results on, or other filter directives). widget:filters:country=Canada
To only show results with Country=Canada.
| 1.0
| widget:filters:*=$*
| Dynamic filters. Causes the options in the record browser to be filtered on the value of another field in the form. e.g. widget:filters:country_id=""$country_id""
would show only results with records having country_id matching the value of the 'country_id' field in the current form.
| 1.3.1
See [[URL Conventions]] for an overview of the types of GET parameters Xataface can take. Any GET parameters that manipulate a query can be used with the widget:filters:* directive to modify the query results that are shown in the lookup widget.
In this example we have a field named appointee that is supposed to reference the contacts table. So in the [[fields.ini file]] we would have:
Initially we just have a little find icon next to the field. If the user clicks it, a dialog pops up enabling them to search for the contact that they want:
===Additional Tips===
Although the lookup widget does not use a vocabulary as indicated in the Synopsis above, it is still useful to define a vocabulary in the fields.ini file for this field. The reason is because the lookup widget is only used with the edit action, where you are inserting or editing data into the field. However, it is not used to the display the data in the view or list actions. Therefore, you must still have a vocabulary defined to properly display these values.
In order to customize the display of the lookup widget's select list, you must edit the delegate class for the table which is referenced by the widget:table directive. There are two important points to note:
# The items in the selection list are formatted based on the getTitle(&$record) delegate class function if it is defined. However, ...
# The Search box will search on text in VARCHAR and TEXT fields. If you need to search for data in numeric fields, you can create a grafted field using a function such as CONCAT() to display numbers as text.
* [http://xataface.com/forum/viewtopic.php?f=4&t=6723 Lookup widget on view with compound primary key]","lookup widget, widget:filters, widget:-filters:limit, widget:table",en,0
meta:class,127,"meta:class relationships.ini file directive","Return to [[relationships.ini file]]
The ''meta:class'' directive allows you to ascribe special meaning to a relationship which Xataface can use in various parts of your application to provide enhanced capabilities.
For example you can specify a relationship as a ""parent"" relationship, thereby using the relationship to obtain the ""parent"" of records of this table. This can be used to help build breadcrumbs.
You can also specify a relationship as a ""children"" relationship which would treat records in the relationship as children of the current record. This can be used in conjunction with the [[list:type]]=treetable directive of the [[relationships.ini file]] to build a tree table that navigates all child records and subtrees.
The Dataface_Record class contains some methods for retrieving the parent and children of records and these methods will take into account any settings you make here.
===Allowed Values===
{| class=""listing listing2""
! Name
! Description
! Version
| parent
| Designates the relationship as a 'parent' relationship, meaning that the first record in this relationship will be treated as the parent of the current record. This setting can be overridden by the [[getParent]] method of the table delegate class if implemented.
| 0.8
| children
| Designates the relationship as a 'children' relationship meaning that records of the the relationship will be treated as a children. This setting can be overridden by the [[getChildren]] method of the table delegate class if implemented.
| 0.8
==See Also==
# '''[[list:type]]''' - [[relationships.ini file]] directive to use a treetable for the related record list of a relationship.
# '''[[getChildren]]''' - Delegate class method to explicitly define the Dataface_Record objects that are to be considered as child records of the current record.
# '''[[getParent]]''' - Delegate class method to explicitly define the Dataface_Record object that is to be considered as the parent record of the current record.
modules,30,"Xataface Modules","[[toc]]
Xataface provides a number of hooks that allow developers to create modules to extend its functionality. This page lists a handful of the currently available modules.
* [[ShoppingCart|Shopping Cart]] - Converts your application into a shopping cart.
* [[Filemaker]] - Export record sets as Filemaker XML.
* [[DataGrid|Data Grid]] - Editable Datagrid.
* [[Email]] - Convert your database into a email list. Send email to any found set.
* [[reCAPTCHA module]] - A reCAPTCHA module to add CAPTCHA support to your Xataface forms.
* [[XataJax]] - Platform for building Web 2.0 AJAX applications with Xataface. Will be a standard component for Xataface starting with version 1.3.
==Module Installation==
You can add modules in either:
# DATAFACE_PATH/modules directory (since 1.0)
# DATAFACE_SITE_PATH/modules directory (since 1.3)
Modules in the DATAFACE_SITE_PATH directory will supersede modules in the DATAFACE_PATH/modules directory (since 1.3).
To activate a module for your application you also need to add an entry to the [[_modules]] section of your [[conf.ini file]]. Each module will come with its own installation instructions.
==Authentication Modules==
Modules to add alternative authentication methods are added to the modules/Auth directory.
==Developing Your Own Modules==
See [[Module Developers Guide]].","modules, captcha",en,0
Module_Developers_Guide,112,"Module Developers Guide","[[toc]]
==Why Write a Xataface Module?==
Xataface modules are components that can be used to extend Xataface's functionality in a generic way so that it can be used on multiple applications. If you find yourself trying to add the same functionality in multiple applications, you might consider writing a Xataface module so that you can share the functionality more easily.
==What can you do with a Xataface Module==
* Create custom authentication handlers.
* Provide custom actions and templates.
* Implement blocks and slots for existing templates.
* Respond to certain application triggers.
==Where do I place a Xataface Module?==
Xataface modules can be placed in the xataface/modules directory (i.e. DATAFACE_PATH/modules). As of Xataface 1.3 they can also be placed directly in your application's modules directory (i.e. DATAFACE_SITE_PATH/modules).
==Your first module==
For our first module, we're going to create a simple module that adds ""hello world"" at the beginning of every page.
===Step 1: Create the Module Class===
In your modules directory, create a directory called ""Hello"". And in this directory, create a file named ""Hello.php"", with the following contents:
(So this file would be located at DATAFACE_PATH/modules/Hello/Hello.php)
===Step 2: Implement the block__before_body method===
We are going to add the phrase ""hello world"" before every page of our application. The easy way to do this is to fill the [[before_body]] slot of the [[Dataface_Main_Template.html]] template. We do this by implementing the ''block__before_body'' method in your module (just as we would if we were trying to fill this slot from the [[Application Delegate Class]].
===Step 3: Activate the Module===
Xataface only loads the modules that have been enabled in the conf.ini. We can enable our module by adding the following section to the [[conf.ini file]]:
All this does is tell Xataface that the module class modules_Hello can be loaded from the location modules/Hello.php.
Now if you start up your application, you should see the phrase ""hello world"" written at the top of each page.
==Example 2: Adding a Custom Action==
Our first module shows an example of filling blocks and slots using a module. Let's now extends that to include a custom action that displays Hello World on its own page.
Complete the following steps:
# Add an ''actions'' directory inside our new module directory. i.e. modules/Hello/actions
# Add a file named hello.php inside the ''actions'' directory with the following contents:
# Go to index.php?-action=hello To see the results of your action. It should say ""Hello World"" on a blank page.
From here on you can improve this action just as you would if you defined the action inside the application's actions directory. You can go on to restrict access to this action using permissions, or you could decide to use a template to display the action.
===Defining a Custom ""hello"" permission for our action===
Perhaps we want to create a special permission for our action so that regular users won't have access to this action unless they are specifically granted this permission. Let's create a ""hello"" permission with which to limit access to our action.
# Create a file named ""permissions.ini"" inside your modules/Hello directory with the following contents:
hello = Permission to access the hello action
Now if you try to access your action (and you haven't been assigned ALL() permissions) you should receive either a login prompt or a permission denied message.
If you want users to be able to access your action, you will need to explicitly add this permission to one of the user's assigned roles or return it as part of the list of authorized permissions in the getPermissions() method.
===Granting the ""hello"" permission to the ""READ ONLY"" role===
If we want the default READ ONLY role to have access to the ""hello"" permission we can actually modify the READ ONLY role inside the [[permissions.ini file]] that we created inside the Hello module:
hello = Permission to access hello action
[READ ONLY extends READ ONLY]
==Example 3: Using Module Templates==
Xataface, by default, stores its templates in the DATAFACE_SITE_PATH/templates and DATAFACE_PATH/templates directories. However if you are writing a module you probably want to keep templates that are used by the module inside the module directory so that you don't break dependencies when you use the module in different applications.
You can use the [http://dataface.weblite.ca/df_register_skin df_register_skin] method to register additional directories for Xataface to look for templates in. This will allow you to add a ''templates'' directory inside your module directory for use by your module's templates.
It is probably best to register this directory on demand (i.e. as part of individual actions) rather than register it globally.
===Using a Template from the hello action===
Let's modify our hello action to use a template that we are going to store and distribute with our module.
# Create a directory named ""templates"" in the modules/Hello directory.
# Create a file named ""hello.html"" inside the templates directory with the following contents:
{use_macro file=""Dataface_Main_Template.html""}
{fill_slot name=""main_section""}
Hello World
Notice that we are extending the Dataface_Main_Template.html template (which is located in the main Xataface install) so that our hello action can now take on the look and feel of the rest of the application.
# Modify the modules/Hello/actions/hello.php file to look like this: Notice that we call the df_register_skin function to register the templates directory that we created in the previous step. Then we call df_display() to display the template.
==See Also===
* [[modules]] - A list of existing Xataface modules that you can download and install.
* [[block__blockname]] - A list of some of the available blocks that can be filled in the default Xataface templates.
* [http://xataface.com/documentation/tutorial/customizing-the-dataface-look-and-feel Customizing Xataface's Look and Feel with Templates] - A tutorial on how to use Xataface's built-in smarty template engine. It has some sections on using delegate classes to override blocks and slots.
* [http://xataface.com/documentation/tutorial/getting_started/changing-look-and-feel Changing Xataface's Look and Feel] - Part of the Getting Started tutorial that shows how to use slots and blocks to customize the Xataface look and feel.",modules,en,
no_access_text,59,no_access_text,"Whenever the NO_ACCESS permission is given for a field, normally the text NO ACCESS appears. But we might want to display another text. Here is an example of the text subscribe is used instead of NO ACCESS whenever the NO_ACCESS permissions is given.
function no_access_text(&$record){
return ""Subscribe"";
permissions.ini_file,26,permissions.ini_file,"==The permissions.ini File==
The permissions.ini file stores custom permissions and roles that can be used by an application. It is an optional file that should be placed in the application root directory (i.e. the same directory where your conf.ini, and index.php files are located).
The permissions.ini file allows you to define two things:
# Permissions
# Roles (i.e. sets of permissions).
Permissions and roles are used throughout Xataface to limit access to actions, records, fields, and relationships. For example, each action in your application can specify a permission that is necessary to perform the action. Your delegate classes may include getPermissions() methods to define what permissions a user gets when interacting with different records. This file (permissions.ini) simply defines the permissions that can be used by your application. It doesn't actually assign those permissions. Assigning permissions is the job of the getPermissions() (or getRoles()) method.
===Defining Permissions===
Permissions are defined by standalone properties in the beginning of the permissions.ini file. For example, if you were desiging a proof-reading application, you might need permissions for ""submit_for_proof"", or ""approve_text"" to correspond with the submitting a document to be proof-read, and approving a document's proof. In this case we would have the following at the beginning of our permissions.ini file:
submit_for_proof = Submit a document to be proofread
approve_text = ""Approve this document's proof""
The left side of the equals sign is the name of the permission. The right side contains a human readable description of the permission and what it is for.
===Limiting Access to Actions based on Permissions===
At this point these permissions don't do anything. In order to be useful we need reference these permissions from an action or a section. For example, let's create an action called ""submit_for_proof"" which displays a form for a user to submit a document record to be proofread.
Our actions.ini file entry might look something like:
label=""Submit document for proof""
And for completeness, since this make-believe action specifies th ""submit_for_proof.html"" template, we'll create the ""submit_for_proof.html"" template in the templates directory:
You have permission to perform this action.
===Defining Who Get's Which Permissions===
Finally, in order to benefit from permissions, your application has to decide that it is going to use permissions (unless you define a getPermissions() method, users are granted ALL permissions by default. Hence if you try to access our submit_for_proof action, we'll see it without any problem. Regardless of who we are. So let's create a simple, but restrictive getPermissions() method in our application delegate class:
Now if we try to access our submit_for_proof action it will give us a ""Permission Denied"" message, because we are only granted READ ONLY permissions (which is a role that includes the view permission and some others - but not our custom ""submit_for_proof"" permission.
Now we'll make a small modification to our getPermissions() method to provide us with our submit_for_proof permission:
Now if we try to access our submit_for_proof action, it will show us our template with no error messages (hopefully).
Roles are sets of permissions. They are defined in the permissions.ini file as sections with lists of included permissions. It might be handy to create roles such as EDITOR or MANAGER which contain sets of permissions that are meant to be assigned to users of those types. For example an EDITOR may have the view and edit permissions, but not the delete permission. A MANAGER might have the view, edit, and delete permissions. You can define these two roles in the permissions.ini file as follows:
Then we could assign these roles to users using the Dataface_PermissionsTool::getRolePermissions() method:
function getPermissions(&$record){
$user =& Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
if ( $user and $user->val('role') == 'EDITOR' ){
return Dataface_PermissionsTool::getRolePermissions('EDITOR');
} else if ( $user and $user->val('role') == 'MANAGER' ){
return Dataface_PermissionsTool::getRolePermissions('MANAGER');
return Dataface_PermissionsTool::READ_ONLY();
Or equivalently we could use the getRoles() method of our delegate class instead of getPermissions():
function getRoles(&$record){
$user =& Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
if ( $user and $user->val('role') == 'EDITOR' ){
return 'EDITOR';
} else if ( $user and $user->val('role') == 'MANAGER' ){
return 'MANAGER'
return 'READ ONLY';
===Xataface Core Permissions & Roles===
Xataface is distributed with its own permissions.ini file that defines some core permissions and roles. You can look at this permissions.ini file (located in the Xataface directory) to see what the format should look like. Any settings you place in your application's permissions.ini file will augment or override settings in Xataface's file.
Some core permissions include:
{| class=""listing listing2""
! Name
! Description
! Version
| view
| Permission to view a record or field. This permission is required to access the view tab, and several other details tabs.
| 0.6
| list
| Permission to access the list tab.
| 0.6
| calendar
| Permission to access the calendar tab.
| 0.6
| edit
| Permission to edit a record or field. This also gives access to the edit tab.
| 0.6
| new
| Permission to edit a record or field for the purpose of creating a new record. This permission is required to access the new record form.
| 0.6
| select_rows
| Permission to select rows in list view to perform actions on them.
| 0.6
| post
| Permission to post a record using HTTP POST
| 0.6
| copy
| Permission to copy a record.
| 0.6
| update_set
| Permission to perform an update on a result set (i.e. access the update set action).
| 0.8
| add new related record
| Permission to add a new record to a relationship. See [[Relationship Permissions]]
| 0.6
| add existing related record
| Permission to add an existing record to a relationship. See [[Relationship Permissions]]
| 0.6
| view related records
| Permission to view the records in a relationship. See [[Relationship Permissions]]
| 1.0
| delete
| Permission to delete a record.
| 0.6
| delete found
| Permission to access the delete found set action (to delete multiple records at a time).
| 0.6
| show all
| Permission to access show all records action.
| 0.6
| remove related record
| Permission to remove a record from a relationship. See [[Relationship Permissions]]
| 0.6
| delete related record
| Permission to delete a record in a relationship. This is stronger than the remove related record permission in that it allows the user to delete the record from the database. See [[Relationship permissions]]
| 0.6
| find
| Permission to perform the find action.
| 0.6
| import
| Permission to perform the import action (to import records into the database).
| 0.6
| export_csv
| Permission to perform the Export CSV action (to export the result set in comma-separated-value format).
| 0.6
| export_xml
| Permission to perform the Export XML action (to export the result set as XML).
| 0.8
| translate
| Permission to translate a record into another language. This permission provides access to the ""translate"" tab.
| 0.8
| history
| Permission to view history information for a record (e.g. the history tab). This requires that history be enabled.
| 0.8
| edit_history
| Permission to edit history information such as undo/redo support for a record.
| 0.8
| navigate
| Permission to navigate through records of a table.
| 0.6
| reorder_related_records
| Permission to reorder the records of a relationship (this is different than just sorting). It sets a default order for the records. Requires the metafields:order directive to be set for the relationship.
| 0.6
| ajax_save
| Permission to save a record through AJAX.
| 0.8
| ajax_load
| Permission to load a record through AJAX.
| 0.8
| ajax_form
| Permission to access the inline editing ajax form for a record.
| 0.8
| find_list
| Permission to search current table.
| 0.6
| find_multi_table
| Permission to perform a site-wide search.
| 0.8
| register
| Permission to register for an account.
| 0.8
| xml_view
| Permission to view a result set as xml.
| 0.8
| view_xml
| View the XML for an individual record.
| 0.8
| manage_output_cache
| Management permission to clear the output cache.
| 0.8
| manage_migrate
| Permission to access the migration tool to migrate between versions.
| 0.8
| manage
| Permission to access the management control panel.
| 0.8
| manage_build_index
| Permission to rebuild the search index.
| 0.8
| expandable
| Whether the record can be expanded in the left nav menu
Some core roles include:
{| class=""listing listing2""
! Name
! Permissions Included
! Version
| view, list, calendar, view xml, show all, find, navigate, ajax_load, find_list, find_multi_table, rss, export_csv, export_xml, and export_json
| 0.6
| All permissions in READ ONLY, and edit, add new related record, add existing related record, add new record, remove related record, reorder_related_records, import, translate, new, ajax_save, ajax_form, history, edit_history, copy, update_set, and select_rows
| 0.6
| All permissions in EDIT, and delete and delete found.
| 0.6
| All permissions in DELETE except navigate, new, and delete found.
| 0.6
| All permissions in READ ONLY, and edit and translate.
| 0.6
| All permissions in READ ONLY, and add new related record.
| 0.6
| All permissions in DELETE and xml_view
| 0.6
| All permissions in ADMIN and manage, manage_output_cache, manage_migrate, manage_build_index, and install.
| 0.6
===Extending and Overriding Roles===
The cleanest and easiest way to define a new role is to extend an existing role. Xataface allows you to extend roles via the '''extends''' keyword. For example, if you wanted to create a role '''TEST ROLE''' that contained all of the same permissions as the READ ONLY role, you could define it as follows in your application's permissions.ini file:
[TEST ROLE extends READ ONLY]
If we wanted it to contain the same permissions as READ ONLY but to also allow the edit permission we would define it as:
[TEST ROLE extends READ ONLY]
If we wanted to disallow the list permission, we would do something like:
[TEST ROLE extends READ ONLY]
===Overriding Existing Roles===
You can also redefine existing roles:
[READ ONLY extends READ ONLY]
This is handy if you have added your own custom permissions that you feel should be included in a core role.
Note that there are some caveats regarding the order of how these roles are defined. Please refer to this forum post for more details:
[http://www.xataface.com/forum/viewtopic.php?t=6187 Overriding Roles / Permissions]
==See Also==
* [[Relationship Permissions]]
* [[getPermissions]] - The getPermissionsMethod
* [[Delegate class methods]] - Delegate class methods.
* [http://xataface.com/documentation/tutorial/getting_started/permissions Getting started with Xataface permissions]","permissions.ini, getPermissions, permissions",en,0
preferences,10,preferences,"==Xataface Preferences==
Xataface preferences can be defined in 3 ways:
# In the ''[_prefs]'' section of rhe [[conf.ini file]] for global static preferences.
# Implementing the [[getPreferences]] method in the [[Application Delegate Class]]
# In the [[__prefs__]] section of the fields.ini file for a table for static preferences on that table. (Limited to only certain preferences).
===Example [_prefs] section===
In the conf.ini
===Example [[getPreferences]] method===
In the [[Application Delegate Class]]:
function getPreferences(){
return array('hide_update'=>1, 'hide_posted_by'=>1);
===Available Preferences===
{| class=""listing listing2""
! Name
! Description
! Default
! Version
| show_result_stats
| Show the result statistics (e.g. found x of y records in table z)
| 1
| 0.6
| show_jump_menu
| Show he drop-down menu that allows you to ""jump"" to any record in the found set.
| 1
| 0.6
| show_result_controller
| Show Next, previous, page number .. links...
| 1
| 0.6
| show_table_tabs
| Show Details, List, Find, etc... tabs.
| 1
| 0.6
| show_actions_menu
| Show New record, Show all, delete, etc..
| 1
| 0.6
| show_logo
| Show logo at top of app
| 1
| 0.6
| show_tables_menu
| Show the tabs to select a table.
| 1
| 0.6
| show_search
| Show search field in upper right.
| 1
| 0.6
| show_record_actions
| Show actions related to particular record
| 1
| 0.6
| show_bread_crumbs
| Show bread crumbs at top of page to show where you are.
| 1
| 0.6
| show_record_tabs
| View, Edit, Translate, History, etc...
| 1
| 0.6
| show_record_tree
| Show tree to navigate the relationships of this record.
| 1
| 0.6
| list_view_scroll_horizontal
| Whether to scroll list horizontal if it exceeds page width
| 1
| 0.6
| list_view_scroll_vertical
| Whether to scroll list vertical if it exceeds page height.
| 1
| 0.6
| hide_posted_by
| Whether to hide the ''posted by'' text in glance lists (e.g. in the view tab, the related records are shown in the left column. This hides the ''posted by'' text next to each related record.
| 0
| 1.0b4
| hide_updated
| Whether to hide the ''updated'' text in the glance lists (e.g. in the view tab, the related records are shown in the left column. This hides the ''updated'' text next to each related record.
| 0
| 1.0b4
| SummaryList_logo_width
| The width of the logo to be used as the preview image in summary lists.
| null
| 0.7
| SummaryList_hideSort
| Hides the sort control for a summary list (the box that allows users to sort by column).
| 0
| 0.7
| hide_user_status
| Hides the user's status (e.g. ""You are logged in as ...""
| 0
| 0.7
| hide_personal_tools
| Hides the personal tool links in upper right. This includes likes such as ""Control Panel"" and ""My Profile""
| 0
| 0.7
| hide_resultlist_controller
| Hides the controller for a result list (E.g. next/back/results per page etc...).
| 0
| 0.7
| hide_related_sections
| Hides the sections of the view tab that show the related records. These are the sortable section boxes. Not the related tabs.
| 0
| 1.3
| hide_record_search
| Hides the record search form that appears in the view tab. Not to be confused with the find tab.
| 0
| 1.3
| show_resultlist_controller_only_when_needed
| Sets the resultlist controller (e.g. back/next/results per page/etc...) to only show up if paging is required (i.e. if there are more records than can be shown on one page (according to the '-limit' parameter).
| 0
| 1.0
| hide_record_view_logo
| Hides the logo for a record that appears in the upper left of the view tab for each record.
| 0
| 0.7
| horizontal_tables_menu
| Whether to force the tables menu to appear as tabs along the top of the page (alternative is as a menu on the left). If there are 10 or fewer allowed tables, then the default is 1, otherwise the default is set to 0.
| 1
| 0.6
| hide_result_filters
| In list view, setting this value to 1 will cause the column filters to be hidden (the select lists to filter the results).
| 0
| 0.7
| disable_select_rows
| A value of 1 causes the checkboxes in each row of the list view to be hidden.
| 0
| 0.7
| result_list_use_geturl
| Use the getURL() method to link to records in the list view rather than the default (which uses the -cursor parameter).
| 0
| 0.7
| disable_ajax_record_details
| Whether to disable the ajax record details (the '+' sign beside each record in list view that expands to show the record details.
| 1
| 0.7
| use_old_resultlist_controller
| As of Xataface 1.1, a new style result list controller is used that resembles facebook. It is more slimmed down and is easier to manage. If you prefer the old controller, set this preference to 1.
| 0
| 1.1
===Inverse Preferences===
The following preferences perform the inverse of some of the options above. When these options are set to 1, their respective option is set to 0.
{| class=""listing listing2""
! Name
! Inverse
| hide_nav_menu
| show_tables_menu
| hide_view_tabs
| show_table_tabs
| hide_result_controller
| show_result_controller
| hide_table_result_stats
| show_result_stats
| hide_search
| show_search
","preferences, prefs, getPreferences",en,0
reCAPTCHA_module,99,"The reCAPTCHA module","[[toc]]
The Xataface reCAPTCHA module CAPTCHA support to any Xataface form that is rendered to the public (i.e. when users are not logged in). This is particularly useful for the [[registration form]] as a means of spam prevention. Below is a screenshot of a registration form with the reCAPTCHA module installed:
For more information about reCAPTCHA see [http://recaptcha.net/].
# Download/extract the module directory into your xataface/modules directory. Currently this module is only available in SVN (http://weblite.ca/svn/dataface/modules/reCAPTCHA/trunk/)
# Add the following to the [_modules] section of your [[conf.ini file]].
# Add the following section to your conf.ini file.
Where public_key, private_key are your keys from your reCAPTCHA account. '''(Note that you need to register for a free reCAPTCHA account at [http://recaptcha.net/] in order for this to work.'''
If you are NOT logged in, you will now see a reCAPTCHA validation image before the submit button for all webforms in your Xataface application. If you fail to enter the captcha text correctly the form will not validate. If you are logged in this module has no effect.
===See Also===
* [[registration_form|Enabling User Registration in Xataface]]
* [[modules|Xataface Modules]]
","captcha, registration, validation",en,
registration_form,98,"Setting up User Registration","[[toc]]
Xataface optionally enables you to allow users to register for an account in your application. If your ''users'' table includes a column for email, it will also perform email validation before the account is activated. Before tackling user registration, it is good to have an understanding of Xataface's [[authentication]] and [http://xataface.com/documentation/tutorial/getting_started/permissions permissions] faculties.
===Enabling Registration===
To enable registration, simply add the following to the ''[[_auth]]'' section of the [[conf.ini file]]:
e.g. after adding this, your ''[[_auth]]'' section might look like:
After doing this, you'll notice a little ''Register'' link below the login form.
Clicking on this link will produce a registration form for the user which is essentially a ""New Record"" form on your ''users'' table.
Some features of this registration form include:
* Checks to ensure that the username is unique
* If the users table contains an ''email'' field, it will use the user-entered address for email validation before activation is complete.
===Setting up Permissions to Support Registration===
'''Xataface <= 1.2.4''': You must ensure that unlogged-in users have permission to add new records to the ''users'' table. This means that your getPermissions() method on the users table should, at least, provide the ''new'' permission. In addition these users must be granted the ''register'' permission in order to be able to register to begin with.
'''Xataface >= 1.2.5''': You no longer need to provide the ''new'' permission to allow users to register. You simply need to provide the ''register'' permission.
====Sample Permissions on Users Table====
In the tables/users/users.php file (assuming my ''users'' table is actually named ""users"")
class tables_users {
function getPermissions($record){
if ( isAdmin() ) return null;
$perms['register'] = 1;
return $perms;
'''Note that this example is only applicable for Xataface 1.2.5 or higher. In Xataface 1.2.4 you needed to provide users with the ''new'' permission rather than the ''register'' permission, which opens up a small security hole since users could potentially just use the ""new"" action if they new the URL and by-pass the registration and activation email altogether'''.
Some notes on this example:
* The isAdmin() function is not part of Xataface. It is used as a bit of *magic* here to reduce code. It is supposed to simply return true if the currently logged in user is an admin. Hence if the user is an admin, this method defers to the Application Delegate class's permissions (i.e. this method should not affect administrators).
* We are giving all users (logged in or not) the register permission which enables them to register for an account on the system.
* Generally you will want to restrict permissions on some of the fields in the users table. E.g. users should not be able to set their role or access level when they register. You can define more fine-grained permissions on these fields using the [[fieldname__permissions]] method of the users table delegate class (per the following example).
====Restricting Permissions on Particular Fields====
You probably don't want users to be able to set their access level when the register for an account, and your ""users"" table will quite often contain some field like ""role"" which stores this information. So the previous example is not quite realistic. You will also need to restrict permissions on the ""role"" field (and any other fields that you want to prevent users from setting themselves.
function role__permissions(&$record){
if ( isAdmin() ) return null;
return Dataface_PermissionsTool::NO_ACCESS();
This will cut off the user's ability to set their own role when they register. You will likely want to set the default role value either in the mysql table definition or in the [[beforeInsert]] trigger.
===Email Validation===
As mentioned above, registration works by sending an activation email to the address specified in the user's registration. This email contains a link back to the ''activate'' action of your Xataface application, which will create the user account and log the user in. This implies that your ''users'' table must store an email address for your users. If you add a field named ''email'' to the ''users'' table, Xataface will assume that you mean to use this field as the user's email address, and thus, for email validation. However you can override this functionality and use *any* field as an email field by setting the ''email'' directive of the appropriate field in the [[fields.ini file]] for the ''users'' table.
'''Example: Assigning the my_addr field of the users table to be used for email validation''':
In the tables/users/fields.ini file:
====Disabling Email Validation====
99% of the time, email validation is the preferred way of ensuring that people who register are who they say they are. You may, however, prefer to let users register directly without requiring the email activation step. You can disable email validation by overriding the ''register'' action in the [[actions.ini file]] as follows:
In your application's [[actions.ini file]]:
[register > register]
After setting this, the user account will automatically be created, and the user logged in upon saving the registration form.
===Triggers: Overriding Registration Workflow===
Xataface provides a number of triggers in the [[Application Delegate Class]] to override and extend the behavior of the user registration and activation process. For a list of available triggers see [[Application Delegate Class#registration]].
===Preventing Spam with CAPTCHA===
One problem with enabling automatic registration is that it invites SPAM in the form of bots that can learn how to automatically register for user accounts and then leave unwanted input into your application. The Xataface [[reCAPTCHA module]] allows you to avoid these problems to some extent by forcing users who aren't logged in to fill a CAPTCHA field in order to successfully submit the form. This is especially helpful for registration forms.
After installing the [[reCAPTCHA module]] the registration form will include a CAPTCHA field like the one depicted below:
For more information about the reCAPTCHA module [[reCAPTCHA module|click here]].
","registration form, _auth, authentication",en,
relationship,68,"The relationship fields.ini directive","[[fields.ini file|Return to fields.ini file directives]]
Certain types of widgets (e.g. grid (v1.0) and checkbox (v1.2)) support the relationship directive which allows them to effectively add/remove records from a specified relationship. This directive only works with transient fields.
===Example 1: Checkboxes to add/remove categories===
(Note: This example requires Xataface 1.2 or higher to work)
Suppose we have a database that keeps track of courses and the branch of research that they belong to. A course can be part of multiple branches. We want to be able to select the branches that a particular course belongs to on the edit form for that course using checkboxes.
Table Structure:
course_id : int (primary key)
course_title : varchar
branch_id : int (primary key)
branch_name : varchar
branch_description: text
course_id : int
branch_id : int
Relationship definition: (from the tables/courses/[[relationships.ini file]]):
Field definitions: (from tables/courses/[[fields.ini file]]):
Things to notice:
# This is a many-to-many relationship (hence the need for the course_branches join table.
# The [branches] field is a transient field.
# The relationship directive from the [[fields.ini file]] references our branches relationship that was defined in the [[relationships.ini file]].
# You can call the field anything that you like. There is no need for it to have the same name as the relationship. It just turned out that way in this example.
===Example 2: Using a grid widget===
Let's modify example 1 slightly to use a grid widget instead of checkboxes. The grid widget will allow us edit the records in a relationship using dynamic table. It automatically uses the correct widget for each column of the table according to the definition in the target table's [[fields.ini file]]. Most of the definition can remain the same. We only change the [[fields.ini file]] directive:
In this case we are able to edit the branch name and description in each row of the grid.
===See Also===
* [[grid|The grid widget]]
* [[checkbox|The checkbox widget]]
* [[relationships.ini file|The relationships.ini file]]
* [[fields.ini file|The fields.ini file]]","grid widget, relationship, checkbox",en,0
relationships.ini_file,20,relationships.ini_file,"==relationships.ini File Reference==
The relationship.ini file is a configuration file which is associated with a single table of a database application. It provides metadata about the table's relationships to other tables to help Xataface dictate how they should be included in the application.
===Field Directives===
The following directives may be added to a field's section of the relationship.ini file to customize the field's behavior. Some directives are not applicable to all fields.
{| class=""listing listing2""
! Name
! Description
! Version
| __sql__
| The SQL query that defines this relationship.
| all
| [[action:visible]]
| A boolean value (0 or 1) that indicates whether this relationship should be visible in the record tabs.
| all
| [[action:condition]]
| An expression that evaluates to a boolean that determines at runtime whether the relationship's tab should appear in the record tabs.
| all
| [[action:delegate]]
| The name of an alternative action that can be used instead of the standard related records list. One possible value for this would be ""related_records_checkboxes"" which would provide the user with a checkbox group to select the records that should be part of the relationship rather than the usual related record list.
| 1.0
| [[section:limit]]
| Integer. The number of records to show in the related record sections (in the view tab). Default is 5.
| 1.0
| [[section:visible]]
| Boolean value (0 or 1) indicating whether the relationship information should appear as a section on the left side of the table.
| all
| [[actions:addexisting]]
| Boolean value (0 or 1) indicating whether the action to add existing records should exist in this relationship.
| all
| [[actions:addnew]]
| Boolean value (0 or 1) indicating whether the action to add news records should exist in this relationship.
| all
| [[action:label]]
| The label that appears in the relationship tab for this relationship.
| all
| [[list:type]]
| Optional type of list to use for the related record list. Possible value: ""treetable""
| 0.8
| [[meta:class]]
| An optional special class to assign to the relationship. E.g. ""parent"" or ""children"".
| 0.8
| [[metafields:order]]
| If the relationship should have a default order this specifies the field that should be used for this sort.
| all
| [[visibility:fieldName]]
| If given the value hidden will make that particular fieldName disappear in the relationship. This will only be applied for that particular relationship.
| all
| [[visibility:find]]
| If given the value hidden this will cause the related fields to not appear on the find form. Normally each relationship is provided a section of the find form to enable users to find records that contain at least one match in the related records.
| 1.3rc4
| [[vocabulary:existing]]
| Specifies a valuelist that can be used to provide the set of records that can be added to this relationship. If target table has a single column primary key then the valuelist should use the primary key for the value. If it has a multi-column primary key, then the value should be in the form key1=value1&key2=value2 etc... See also [[relationshipname__getAddableValues]] delegate class method for a programatic solution.
| 1.0
==Relationship Permissions==
See [[Relationship Permissions]]
==See Also==
* [http://xataface.com/documentation/tutorial/getting_started/relationships Getting started with relationships]","relationships.ini file, relationships",en,0
Relationship_Permissions,111,"Relationship Permissions","[[toc]]
As relationships are a core feature of Xataface, it is helpful to understand how to handle permissions on related records. Even if you apply permissions to every table individually, you need to take into account the relationships that you have defined between tables, because they may open access to actions that you did not intend.
For example, suppose we have two tables: ''people'' and ''publications'', and we have a relationship from ''publications'' table to the ''people'' table called ''publication_authors''.
Suppose you give a user write access to a record of the publications table, but no access to the people table. If you are allowing the ''add new related record'' permission on the ''publications'' table record, then the user will still be able to add new people, via the ""Add related people record"" function of the database. This may or may not be desirable.
This article discusses the issues that arise due to relationships and permissions, and how to deal with them.
==Relationship Permissions==
The Xataface [[permissions.ini file]] defines a handful of permissions that are related to the management of related records. These include:
{| class=""listing listing2""
! Name
! Description
! Included in Roles
| [[add new related record]]
| Permission to add a new related record to a relationship.
| [[add existing related record]]
| Permission to add an existing record to a relationship.
| [[remove related record]]
| Permission to remove a record from a relationship. (This only allows removing a record from the relationship - not deleting the record from the database, so this is only really relevant in a many-to-many relationship).
| [[delete related record]]
| Permission to delete a related record. This allows both removing the related record from the relationship, and deleting the record from the database. This permission is not included in any default roles. A combination of permission for [[remove related record]] in the source table and [[delete]] in the target table, are equivalent to access to this permission. Use this permission only when you need to override the ability to delete records from the database based on membership in a relationship.
| -
| [[view related records]]
| Permission to view the records of a relationship.
| [[related records feed]]
| Permission to access the RSS feed of a relationship.
==Fine-grained, Per-relationship Permissions==
You may often find that defining a flat set of permissions to all relationships on a record is insufficient for your purposes, because some relationships may demand different access levels than others. You can override the permissions for any particular relationship by implementing the [[rel_relationshipname__permissions]] method in the table's delegate class, where ''relationshipname'' is the name of the relationship.
e.g. Consider the relationship ''manufacturers'':
function rel_manufacturers__permissions($record){
// $record is a Dataface_Record object
return array(
'view related records' => 0
This will tell xataface that users should not be able to view related records on the ''manufacturers'' relationship. This will override any permissions that were defined in the [[getPermissions]] method.
==More Complete Example==
In the following example, we design a products database. We use 2 relationships on our products table: One to keep track of the parts that are used in our product. The other to keep track of the users that are allowed to edit our products.
We want to make it so that only the product owner can manage the editors for a product, but anyone in the product_editors relationship is allowed to edit the product or add/remove parts from the product.
We don't want to give any users access directly to the parts, product_parts, or product_editors tables. We want all access to go through the relationships on the products table.
===Database/Relationship Design===
Consider a database with 4 tables:
# products (product_id, product_name, owner_username)
# parts (part_id, part_name)
# product_parts (part_id, product_id)
# product_editors (product_id, editor_username)
# users (username, password, role)
And we have the following relationships on the ''products'' table:
===Application Permissions : Very Restrictive===
Like a good boyscout, we define our default permissions in the [[Application Delegate Class]] to be very restrictive: Don't let anyone do anything.
class conf_ApplicationDelegate {
function getPermissions($record){
return Dataface_PermissionsTool::NO_ACCESS();
===Products Table Permissions: Less restrictive===
Now we open it up for our products table in the getPermissions() method of the products delegate class.
In tables/products/products.php:
class tables_products {
function getPermissions($record){
$user = Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
if ( $user and $record and $record->val('owner_username') == $user->val('username')){
// Give the record owner Edit permissions on the product
return Dataface_PermissionsTool::getRolePermissions('EDIT');
// Everybody else gets read only access to the products table.
return Dataface_PermissionsTool::READ_ONLY();
===Checking if the current User is an Editor===
So far we have given the product owner edit permissions and everyone else read only permissions. We still need to allow editors to edit the product. In order to do this we need to be able to *efficiently* find out if the current user is an editor of a particular product. There are a few different ways to do this, but some are better than others. Some strategies include:
# Perform an SQL query inside the [[getPermissions]] method to see if the user is an editor for the product. '''THIS IS VERY BAD!!!''' The [[getPermissions]] method should not include any IO or database queries because it is called a large number of times per request... making expensive calls in this method will slow down your app dramatically.
# Create a function to load and cache all of the current user's products so that this can be easily checked at will. This is fine if the user is expected be able to edit only a few products. If he could be an editor for thousands of products, this may not be practical as it will cause you to have to load thousands of records into memory on every page request.
# Use the [[__sql__]] method of the delegate class to create a grafted field on the ''products'' table indicating whether the current user is an editor for the product. This results in a very quick and accessible indicator variable that can be used in the [[getPermissions]] method to check to see if the current user is an editor for the current product. E.g. In the tables/products/products.php file (delegate class):
function __sql__(){
return sprintf(""select p.*, pe.editor_username from products p
left join product_editors pe on p.product_id=pe.product_id
where pe.editor_username='%s'"",
This will result in a situation where product records will have an additional field ''editor_username'' which will either be blank if the current user is not an editor for the product; or will contain the current user's username if they are an editor for the product.
===Table Permissions for Product Editors===
Now that we have a reliable way to tell, for any given product, whether the current user is, in fact, an editor, we can ammend the [[getPermissions]] method of the products table to include our editor permissions.
class tables_products {
function getPermissions($record){
$user = Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
if ( $user and $record and $record->val('owner_username') == $user->val('username')){
// Give the record owner Edit permissions on the product
return Dataface_PermissionsTool::getRolePermissions('EDIT');
if ( $user and $record and $record->val('editor_username') == $user->val('username') ){
// If the user is an editor, we give them edit permissions
// also
return Dataface_PermissionsTool::getRolePermissions('EDIT');
if ( $user ){
// Other logged in users have read only access
$perms = Dataface_PermissionsTool::READ_ONLY();
$perms['new'] = 1; // We'll also let them add new products
return $perms;
// Regular users just get the default permissions as
// defined in the Application Delegate class
return null;
===Removing Editor Access to the Editor Relationship===
You'll notice that at this point, the product editor has exactly the same permission as the product owner. They both have permission to add and remove records from all relationships on the product. However, we don't want them to be able to access the editors relationship at all. We will use the [[rel_relationshipname__permissions]] method to override the permissions for the ''editors'' relationship.
In the tables/products/products.php delegate class:
function rel_editors__permissions($record){
$user = Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
if ( $user and $record and $record->val('owner_username') == $user->val('username')){
// Owners should just get their normal permissions
return null;
if ( $user and $record and $record->val('editor_username') == $user->val('username') ){
// If the user is an editor, we give them edit permissions
// also
return array(
'view related records' => 0,
'add new related record' => 0,
'add existing related record' => 0,
'remove related record' => 0,
'delete related record' => 0
// Other users just get their normal permissions
return null;
===Assigning product owner by default===
With the current permissions, something funny would happen. Users have permission to add new records, but once the record is added they won't be able to edit it because they are neither an editor nor the owner of the product. We'll fix this by assigning the current user as the product's owner using the [[beforeSave]] trigger in the products delegate class:
function beforeSave($record){
$user = Dataface_AuthenticationTool::getInstance()->getLoggedInUser();
if ( $user ){
$record->setValue('owner_username', $user->val('username'));
===Testing Out Our Solution===
In your testing of the solution, you should find the following:
# Trying to access any table other than the ''products'' table should result in a ''permission denied'' error.
# If you access the ''products'' table, you should be able to see a list of existing products, and the ""Add New Record"" action.
# After you add a new product you should see that you are the product owner.
# As a product owner you should see both the ''parts'' and ''editors'' tabs in your product record. You should be able to view and add new records to both of these relationships.
# Add another user as an editor to your product, then log in as that user. You should be able to edit the product, but you shouldn't be able to see the ''editors'' tab for the product.
==See Also==
* [[permissions.ini file]] - Overview of the Xataface permissions.ini file
* [http://xataface.com/documentation/tutorial/getting_started/permissions Getting Started with Xataface Permissions]
* [[How to granulate permissions on each field]] - Brief tutorial on how to set permissions on a field by field basis.
* [[Delegate class methods]] - A list of all of the available delegate class methods that you can implement. Many of them pertain to permissions and triggers.
* [[Application Delegate Class]] - Overview of the application delegate class.
* [[relationships.ini file]] - The relationships.ini file directives.
","relationships, permissions, rel_relationshipname__permissions, getPermissions, permissions.ini",en,
secure,88,"secure fields.ini directive","[[fields.ini file]] directive used only with [[container fields]]. If this flag is set, then the field contents will be treated in a secure manner and will obey the application permissions. If this directive is not set, then uploaded files in [[container fields]] are served directly by the web server without considering application permissions. Setting this directive will cause the application use a special get_blob action to serve the uploaded file, and this obeys application permissions.
Given a field to upload a PDF report, your [[fields.ini file]] section for this field might be something like:
Now if we upload a file named ""foo.pdf"" in this field, it will be uploaded to:
Now we change the field definition to use the secure directive:
In this case it will still upload files to the ''uploads'' directory, but all of the links generated in the Xataface interface (and via the ''display()'' and ''htmlValue()'' methods) will be for a URL like:
Which will serve up the PDF file as an attachment.
===Restricting Direct Access to uploads directory===
Note: You still need to restrict access to the uploads directory or it may be possible for users to still guess the absolute URL to files in it. You can restrict access by placing an .htaccess file in the uploads directory (if you are using Apache) with the following contents:
deny from all
If you are using IIS or another web server you should look into the methods available for you to restrict access to directories.
===HTTP Response Codes===
The [[getBlob action]] will return the following HTTP Response Codes:
* '''404''' - If either the record does not exist, or the record's specified container field is empty.
* '''403''' - If the current user doesn't have permission to access this record.
* '''500''' - If there is another error. The actual error will be written to the error log.","secure,fields.ini file",en,
Selected_Records_Actions,58,Selected_Records_Actions,"==Creating a Custom ''Selected Records'' Action==
If you view the ''list'' tab in any of your Xataface applications, you'll notice that there is a checkbox next to each row of the list, and there are a number of actions listed at the bottom of the list that you can perform on the selected records. Xataface comes pre-built with only a few of these actions:
# Delete selected
# Update selected
# Copy selected
However it is quite easy to add your own actions here that are performed on selected records. This article describes exactly how to do this.
===What is a ''Selected Record'' action?===
A ''Selected Record'' action is no different than any other action in Xataface, except that it is meant to act on the records that have been selected in the list tab.
==Example Action: Approve Records==
Consider a news site where news stories are automatically imported into the database en masse, but each news story has a field ''approved'' to indicate whether the store has been approved to appear on the site yet. The usage pattern of this application involves a lot of looking through lists of news stories and approving them. Therefore it would be convenient if the user could just select the rows that he wants to approve and click a button to approve them all.
Out of the box Xataface would allow the user to select the records, click ''update selected records'', then update them all via the ''update selected records'' form. But avoiding this extra step will improve usability greatly.
===Step 1: Design the Action===
First we need to specifically decide how our action will work. In this case, the flow goes as follows:
# User selects the news items they want to approve.
# User clicks the ''Approve Selected'' button. (to be created)
# Our action approves the selected records.
# User is automatically redirected back to the list tab with a message stating how many records were successfully approved, and whether there were any errors.
===Step 2: Gather Our Tools===
Before we actually create the action, let's look at a few tools that we'll be using from the Xataface framework to make this happen.
# In the [[actions.ini file]], the ''[[selected_result_actions]]'' category is reserved for actions that act on selected records of the list tab. E.g.
# The [http://dataface.weblite.ca/df_get_selected_records df_get_selected_records()] function returns an array of [http://dataface.weblite.ca/Dataface_Record Dataface_Record] objects that represent the rows that were selected to initiate the action. E.g.
$app =& Dataface_Application::getInstance();
$query =& $app->getQuery();
$records = df_get_selected_records($query);
foreach ($records as $record){
# The [http://dataface.weblite.ca/checkPermission Dataface_Record::checkPermission()] method allows us to see if the current user has access to a specific permission on the given record. We'll use this method to ensure that the user has permission to approve the news record. E.g.
if ( !$record->checkPermission('edit', array('field'=>'approved')) ){
return PEAR::raiseError(""You don't have permission to edit the approved field for this record."");
# The Xataface will pass the redirect URL where your action should send the user upon completion of the action as the ''--redirect'' attribute of the ''POST'' variables. This value is base64_encoded so you'll need to decode it before redirecting. E.g.:
if ( @$_POST['--redirect'] )
$url = base64_decode($_POST['--redirect']);
$url .= '&--msg='.urlencode($updated.' records were deleted.');
header('Location: '.$url);
===Step 3: Create the Action===
We will call our action ''approve_news'' so we'll place it in the ''actions/approve_news.php'' file of our application:
$records =& df_get_selected_records($query);
$updated = 0; // Count the number of records we update
$errs = array(); // Log the errors we encounter
foreach ($records as $rec){
if ( !$rec->checkPermission('edit'), array('field'=>'approved')) ){
$errs[] = Dataface_Error::permissionDenied(
""You do not have permission to approve '"".
""' because you do not have the 'edit' permission."");
$rec->setValue('approved', 1);
$res = $rec->save(true /*secure*/);
if ( PEAR::isError($res) ) $errs[] = $res->getMessage();
else $updated++;
if ( $errs ){
// Errors occurred. Let's let the user know.
// The $_SESSION['--msg'] content will be displayed to the user as a message
// in the next page request.
$_SESSION['--msg'] = 'Errors Occurred:
', $errs);
} else {
$_SESSION['--msg'] = ""No errors occurred"";
$url = $app->url('-action=list'); // A default URL in case no redirect was supplied
if ( @$_POST['--redirect'] ) $url = base64_decode($_POST['--redirect']);
$url .= '&--msg='.urlencode($updated.' records were deleted.');
// Redirect back to the previous page
header('Location: '.$url);
===Step 4: Add the action to your actions.ini file===
The actions.ini file allows us to specify how and where this action is used, and by whom. We can specify permissions that are required to perform the action, conditions that are required to display the action, confirmation messages that are to be displayed to the user when they are about to perform the action, and more. Our [[actions.ini file]] entry looks like:
description=""Approve selected records""
permission = edit
confirm=""Are you sure you want to approve the selected records?""
condition=""$query['-table'] == 'news'""
This should be fairly straight forward. The only special items here are the ''category'' and ''confirm'' directives. The ''condition'' directive tells Xataface that this action should only be shown for the ''news'' table.
The ''confirm'' directive defines a confirmation message that should be displayed to the user when they attempt to approve records.
The ''icon'' directive allows you to specify the path to an icon to display for the action. In our case we have an icon located in the images directory of our application.
===Step 5: Trying it out===
Now when we go to the ''list'' tab of the ''news'' table there is an ''Approve'' button along the bottom where it says ""With Selected"". You we can click on this button to approve any of the selected rows.
sendRegistrationActivationEmail,16,sendRegistrationActivationEmail,"==sendRegistrationActivationEmail() Hook==
A hook that can be implemented in the [[Application Delegate Class]] or the [[Table Delegate Class]] to override the sending of an activation email to the user.
function sendRegistrationActivationEmail( Dataface_Record &$record, string $activationURL ) : mixed
{| class=""listing listing2""
! Name
! Description
| &$record
| A Dataface_Record object encapsulating the record that is being inserted in the users table for this registration.
| $activationURL
| The URL where the user can go to activate their account.
| returns
| Mixed. If this method returns a PEAR_Error object, then registration will fail with an error.
$email = $record->val('email');
mail($email, 'Welcome to the team',
'Welcome '.$record->val('username').
'. You have been successfully registered.
Please visit '.$activationURL.' to activate your account'
===See Also===
* [[beforeRegister]]
* [[afterRegister]]
* [[validateRegistrationForm]]
* [[getRegistrationActivationEmailInfo]]
* [[getRegistrationActivationEmailSubject]]
* [[getRegistrationActivationEmailMessage]]
* [[getRegistrationActivationEmailParameters]]
* [[getRegistrationActivationEmailHeaders]]",,en,0
setSecurityFilters,91,"setSecurityFilter() method","== Example ==
In the delegate class for the users table:
This will only set the filter on non-admin users (assuming that you have defined a function isAdmin() to tell you if the current user is an admin user.",,en,
ShoppingCart,31,ShoppingCart,"==Xataface Shopping Cart Module==
Status: Under development
Current Version: 0.2
Add a shopping cart to your xataface application. You can treat any record as a product that can be sold. Includes Paypal connectivity, shipping calculation, and more.
* Xataface 1.0 or higher
* PHP 5 or higher
* MySQL 4.1 or higher
===Installation Instructions===
# Download the ShoppingCart module, extract it, and place the ShoppingCart directory in your Xataface modules directory. (i.e. /path/to/xataface/modules/ShoppingCart).
# Add the following line to the [_modules] section of your [[conf.ini file]]:
# Add the following to the beginning of your [[index.php file]]:
function __autoload($class){
if ( $class == 'ShoppingCart' ) require_once 'modules/ShoppingCart/lib/ShoppingCart/ShoppingCart.class.php';
# In the [[fields.ini file]] for any table whose records you wish to represent items for sale, add the following:
# Specify which fields should be used for the item description, price, width, height, length, and weight in the [[fields.ini file]] for each table whose records you wish to represent items for sale by adding the following directives to the appropriate fields:
E.g. if your table has a field named """"price"""" that you want to represent the unit price, you would have something like:
The shopping cart module will make its best guess on which fields to use for these values if they are not explicitly specified.
# Specify the paypal account where money should be deposited by adding the following to your application's [[actions.ini file]]:
===Usage Instructions===
Once the Shopping Cart module is installed you can:
# Add items to your shopping cart
# View your cart contents
# Checkout and pay with paypal
====Adding Items to the Cart====
In the View tab of any salable record, you'll notice a little block on the left side of the page with the heading ""Add Item to Cart"". This includes a field to specify the quantity and a button to add the item to the shopping cart.
====Viewing Cart Contents====
The Shopping Cart module automatically introduces an action to view the cart contents. This action is named ""view_cart"". Hence you can always view the cart contents by entering the URL: index.php?-action=view_cart .
====Checking Out====
# View the cart contents.
# Click ""Check out""
# This will take you to a paypal page to pay for your items.
This module adds the following actions to your application.
{| class=""listing listing2""
! Name
! Content-type
! Description
! Version
| checkout
| text/html
| Sends user to paypal to pay for the contents of their cart.
| 0.1
| calculate_shipping
| text/html
| Calculates the shipping charges for the cart.
| 0.1
| add_to_cart
| text/html
| Adds an item to the cart.
| 0.1
| clear_cart
| text/html
| Empties the shopping cart.
| 0.1
| get_shipping_provinces
| text/json
| Returns JSON array of provinces for a given country.
| 0.1
| invoices
| text/html
| Displays the current user's invoices.
| 0.1
| payment_complete
| text/html
| Page that is displayed after a successful payment on paypal.
| 0.1
| paypal_ipn
| none
| Handles paypal events such as successful payments.
| 0.1
| refresh_shipping_methods
| text/html
| Refreshes the shipping methods available to the system.
| 0.1
| set_shipping_method
| text/html
| Sets the selected shipping method to a particular method.
| 0.1
| view_cart
| text/html
| View the cart contents.
| 0.1
==Blocks and Slots==
This module adds the following blocks and slots to your applications.
{| class=""listing listing2""
! Name
! Description
! Version
| shipping_method
| A block with a form to select the shipping method.
| 0.1
| add_to_cart
| A block with a form to add a record/item to the shopping cart.
| 0.1
==Application Delegate Class Hooks==
You can modify the shopping cart behavior by defining the following methods to the application delegate class.
{| class=""listing listing2""
! Name
! Description
! Version
| isShippingMandatory
| Returns a boolean value indicating whether the user must select a shipping method.
| 0.1
| getDefaultShippingMethod
| Returns a string with the name of the default shipping method to be used.
| 0.1
==Table Delegate Class Hooks==
You can modify the behavior of the shopping cart by defining the following methods to the delegate class of any table that implements the InventoryItem ontology (i.e. any table that is to be used to store products that can be added to the cart).
{| class=""listing listing2""
! Name
! Description
! Version
| field__taxes
| A calculated field that returns an associative array of all applicable taxes for a product.
| 0.1
==Internal Storage==
This module creates the following tables to store its data:
The dataface__invoices table stores the actual invoices for purchases made. An invoice is automatically created as soon as the user ""checks out"".
{| class=""listing listing2""
! Column Name
! Data Type
! Description
! Version
| InvoiceID
| int(11)
| Auto incrementing primary key for the invoice.
| 0.1
| dateCreated
| datetime
| The date that the invoice was created.
| 0.1
| dateModified
| datetime
| The date that the invoice was last modified
| 0.1
| status
| enum
| The status of the invoice (either PENDING, PAID, or APPROVED).
| 0.1
| amount
| decimal(10,2)
| The total amount on the invoice.
| 0.1
| paymentMethod
| varchar(32)
| The name of the payment method used.
| 0.1
| referenceID
| varchar(64)
| ??
| 0.1
| username
| varchar(32)
| The username of the user who owns this invoice.
| 0.1
| firstName
| varchar(32)
| The first name of the payer.
| 0.1
| lastName
| varchar(32)
| The last name of the payer.
| 0.1
| address_name
| varchar(100)
| The name on the shipping address.
| 0.1
| address1
| varchar(100)
| The shipping address line 1.
| 0.1
| address2
| varchar(100)
| The shipping address line 2.
| 0.1
| city
| varchar(40)
| The shipping address city.
| 0.1
| province
| varchar(2)
| The shipping province or state.
| 0.1
| country
| varchar(2)
| The shipping country.
| 0.1
| postalCode
| varchar(32)
| The shipping postal code.
| 0.1
| shipping_method
| varchar(50)
| The name of the shipping method to use.
| 0.1
| phone
| varchar(32)
| The phone number of the payer.
| 0.1
| email
| varchar(127)
| The email address of the buyer.
| 0.1
| data
| text
| Serialize shopping cart data.
| 0.1
Stores the available shipping methods.
{| class=""listing listing2""
! Column Name
! Data Type
! Description
! Version
| shipping_method_id
| int(11)
| Auto increment ID for a shipping method.
| 0.1
| shipping_method_name
| varchar(50)
| The name of the shipping method.
| 0.1
| shipping_method_label
| varchar(100)
| The label for the shipping method (displayed to the user).
| 0.1
| shipping_method_enabled
| tinyint(1)
| Whether or not this shipping method is currently enabled.
| 0.1
| shipping_method_module
| varchar(32)
| The name of the handler that this shipping method belongs to.
| 0.1
==Payment Handlers==
Information about payment handlers to be added here.
==Shipping Handlers==
The Shopping Cart module is itself modular, allowing you to develop custom shipping handlers for different types of shipping. A shipping handler is responsible for calculating shipping costs to a destination address. Currently only a UPS shipping handler has been created, but it is not difficult to create other handlers.
===Shipping Handler Public Interface===
{| class=""listing listing2""
! Method
! Description
! Version
| calculateShipping
| Calculates the shipping cost for the current shopping cart, and adds the shipping cost to the cart as a line item.
| 0.1
| getInfo
| Returns an array of shipping methods that can be handled by this handler.
| 0.1
site_with_backoffice,86,,"==How to build a site with an optional login form==
To publish a public site with data without any need to login to access, here is the code :
function getPermissions(&$record){
if ( isAdmin() ) return Dataface_PermissionsTool::ALL();
else return Dataface_PermissionsTool::READ_ONLY();
In this way, you still can login to administrate your data.",,en,
sql_delegate_method,87,"__sql__ Delegate Method","return to [[Delegate class methods]]
The __sql__ delegate class method can be defined in any delegate class to specify the SQL query that should be used to fetch records for a given table. This method overrides the [[__sql__]] directive of the fields.ini file. This strategy is primarily used to graft columns from another table onto the base table.
=====Use Caution=====
This is an advanced feature and, if used incorrectly, can muck up your application. Make sure that your SQL query includes a superset of the columns in the base table, and is a row-for-row match for the rows in the base table. I.e. you should never use an internal join. Always use a left join so that all of the rows of the base table are returned even if the join table doesn't have a corresponding row.
If you want to simply filter a table's records, and don't need to graft any additional columns onto the table, you should use the [[setSecurityFilters]] method.
Given the table foo, its delegate class:
class tables_foo {
function __sql__(){
return ""select f.*, c.category_name from foo f left join categories c on f.category_id=c.category_id"";
This effectively grafts a column ""category_name"" onto the foo table based on a join with the categories table.
","__sql__, SQL queries, delegate class",en,
tab,48,tab,"==tab directive of the fields.ini file==
The ''tab'' directive of the [[fields.ini file]] specifies which tab of the record edit form a field should be displayed on. Xataface supports multiple tabs on the edit form by way of this ''tab'' directive. If no fields contain the ''tab'' directive then all fields are displayed in a single tab (named ''__main__'').
==Example 1: Placing address info on separate tab==
Consider the following ''people'' table:
CREATE TABLE `people` (
person_id int(11) not null auto_increment primary key,
first_name varchar(32) not null,
last_name varchar(32) not null,
address varchar(100),
city varchar(100),
province varchar(100),
country varchar(100),
postal_code varchar(20)
We want to split the fields into two tabs:
* Personal Info
* Address Info
===Splitting form into tabs===
We'll do this in two steps. We use the ''tab'' directive to assign all address-related fields to the ''address_info'' tab. In the tables/people/fields.ini file:
Now, when we load the edit form of the ''people'' table, we see two tabs:
* __main__
* address_info
''__main__'' is the name assigned to the default tab (for all fields that don't have a tab defined explicitly.
===Customizing the tab labels===
Next we will customize the tab labels by adding the following to the beginning of the [[fields.ini file]]:
label=""Personal Information""
label=""Address Information""
===Reordering the tabs===
If we want to reorder the tabs so that the ''address_info'' tab comes first, we would just reorder the definitions of the tabs:
label=""Address Information""
label=""Personal Information""
===Try This Example App===
You can try this tiny sample application out [http://dev.weblite.ca/tab_test here].",,en,0
table,66,table,"When using widget:type table, it will store the data as XML.
So the field type must be TEXT (or varchar... but text is better). You can decide which columns you want in the table by creating sub-fields in your fields.ini file as follows:
Suppose you want a column called 'name' and a column called 'url'
Now when you access the stored value using the Dataface API, the value of myfield will be stored as an array of associative arrays. e.g.
foreach ( $record->val('myfield') as $vals){ echo $vals['name'].' -- '.$vals['url']; }
templates:tags:use_macro,24,templates:tags:use_macro,"==use_macro Template Tag==
The use_macro tag includes another template into the current template with the option to override certain sections.
{| class=""listing listing2""
! Name
! Description
! Version
| file
| The path the template to include (within the templates directory).
| 0.6
In this example we will create a template for a user profile, but this template will include a slot that can be overridden by other templates to customize the user bio.
User profile
User bio
{define_slot name=""bio""}
This text will be overridden by other templates to place the correct
bio information.
{use_macro file=""user-profile.html""}
{fill_slot name=""bio""}
This is Steve's bio. It will override the text in the bio slot.
===See also:===
* [[xataface templates|Xataface templates]]
* [[templates:tags:define_slot|The define_slot tag]]
* [[templates:tags:fill_slot|The fill_slot tag]]
* [http://www.xataface.com/documentation/tutorial/getting_started/changing-look-and-feel Changing the Look & Feel of Xataface] (From the Getting Started Tutorial)
* [http://www.xataface.com/documentation/tutorial/customizing-the-dataface-look-and-feel Cusomizing the Xataface Look & Feel] Tutorial
testpage2,2,testpage2,"Another test page
test_page_34,177,"Hello World","Hello world",,en,
timestamp,44,timestamp,"Return to [[fields.ini file]]
A very simple sample of this could be your table contains the table date_created as a type of date. In your fields.ini, you would include this:
The widget:type=hidden will make the field not visible during entry and editing. And the timestamp=insert causes the field to be filled upon insertion of a new record.
===Possible Values===
* '''update''' - Causes timestamp to be updated whenever the record is modified.
* '''insert''' - Causes the timestamp to be updated only when the record is first inserted.","timestamp, date, datetime",en,0
Troubleshooting,49,Troubleshooting,"==Xataface Troubleshooting==
This document is intended to help Xataface developers through some of the most common issues.
==All I get is a blank white screen!==
The most common issue mentioned in the forums is that an application comes up with a blank white screen in the web browser. This can happen for a number of reasons but the most common reason is because PHP has encountered a fatal error and your PHP installation is not set up to display errors.
The first step to troubleshooting this problem must be to find out what the error is. You can do that in one of the following ways:
# Check your Apache error log if you know where it is. One common location on many linux installations is
but your system may have it located elsewhere. If you cannot find your error log, continue to the next option.
# Turn on the ''display_errors'' flag in your ''php.ini'' file. I.e., in your ''php.ini'' file, find where it says
display_errors Off
and change it to
display_errors On
. After this is done, restart your apache webserver. If you don't know where your ''php.ini'' file is located see the section later in this document on locating your ''php.ini'' file. If you don't have access to your php.ini file, move on to the next option.
# In your application's ''.htaccess'' file, add the following directives to enable displaying errors:
php_flag display_errors on
. Note that this method will only work if your apache config file allows you to override these values at the directory level. If you still get a blank white screen after this, continue to the next option.
# At the beginning of your application's index.php file, add the following:
. Note that if the error occurs in the parsing or compiling of your PHP files you will still get a blank screen. But this will at least display runtime errors on the page.
Once you can see the error messages that caused the blank white screen you are in a much better position to solve the problem.
==Locating your php.ini file==
Locating your ''php.ini'' file is actually quite easy. The quickest way is to create a php script with the following contents:
then navigate to this page in your web browser. This look at the line where it says the ''php.ini file''. It will list the path there.",,en,0
URL_Conventions,37,URL_Conventions,"==Xataface URL Conventions==
Xataface adheres to a few simple URL conventions for all of its actions. When you understand how Xataface URLs work you begin to get far more out of your applications. By specifying the appropriate query parameters to can jump directly to any point in your application, or produce a specific result set.
For example, the URL ''index.php?-table=people'' will take you to the ''people'' table (and since the default action for a Xataface application is ''list'', it will take you to the ''list'' view.
You could be more explicit by specifying the action in the URL directly: ''index.php?-table=people&-action=list''. This would take you to the same screen. From this example, you see that you can specify such things as the table and action via GET parameters. Xataface accepts many more GET parameters also, as you'll see in the next section.
===Available GET Parameters===
{| class=""listing listing2""
! Name
! Description
! Default
! Version
| -action
| Specifies the action to perform. E.g. ''browse'', ''list'', ''find'', ''edit'', ''new'', ... etc..
| list
| all
| -table
| The name of the table to use as the context table.
| The first table in the [_tables] section of your [[conf.ini file]]
| all
| -skip
| Skip a certain number of results in the current found set to display. E.g. If there are 100 records in the table and you want to start browsing from the 30th record, you would set ''-skip=29''.
Not to be confused with the ''-cursor'' parameter which is used to specify which record to view in the ''details'' tab.
| 0
| all
| -limit
| The maximum number of records in the found set to display.
| 30
| all
| -cursor
| The index of the record in the current found set that is treated as the ""current"" record. This is used in the ''details'' tab to identify which record to act on. E.g. which record to view or edit.
| 0
| all
| -sort
| A comma-delimited list of columns to sort the result set on.
| null
| all
| -relationship
| If we are browsing related records, this specifies the name of the relationship.
| null
| all
| -related:start
| If we are browsing related records, this is the first record in the relationship to show.
| 0
| all
| -related:limit
| If we are browsing related records, this is the number of records to show per page.
| 30
| all
| -search
| A keyword search term to filter the found set on. Any row containing any field that matches the query will be returned.
| null
| all
| --no-query=1
| A flag to indicate that xataface should not query the database by default. This flag is used in the new record form to prevent the form parameters from being interpreted as query parameters to search in the database. If you set this flag, it likely result in a message saying ""No records found"". Generally you would only use this in a custom action where you are not relying on Xataface's default found set.
| 0
| 1.3
There are many other GET parameters that are used in various contexts but the above parameters are available throughout the entire application.
===Finding Records using the URL===
Notice that all of the GET parameters mentioned in the previous section begin with a hyphen (i.e. '-'). This is a convention Xataface uses to distinguish directives from search queries. All parameters that do not begin with '-' are treated as a query to filter the found set.
For example, ''first_name=bob'' used as a GET parameter would cause the found set to be filtered so that only records where the ''first_name'' column contains the phrase ""bob"" are returned. Putting this all together, suppose we wanted to show the list tab for the ''people'' table, but only wanted to show the people with first names containing ""bob"":
====Exact, Range, and Pattern Matching====
By default, queries on text columns look for partial matches. I.e. if you search for ""bob"" it will match ""bob"", ""bobby"", ""rubob"", and any other text that contains ""bob"". If you are only interested in finding records that match ''exactly'' ""bob"", then you can prepend an ""="" to the query. E.g. ''first_name==bob'', or the full URL:
This should show the ''list'' tab for the ''people'' table with only records with first name exactly ""bob"".
There are a number of modifiers that you can prepend to your query to modify how it is executed. They are as follows:
=====Search Operators=====
{| class=""listing listing2""
! Prefix
! Usage Example
! Description
| >
| age=>10
| Match records greater than search parameter.
| <
| age=<10
| Match records less than search parameter.
| >=
| age=>=10
| Match records greater than or equal to the search parameter.
| <=
| age=<=10
| Match records less than or equal to the search parameter.
| ..
| age=10..20
| Match records in a given range.
| =
| first_name==bob
| Match records that exactly match the search parameter (if there is no prefix then it will search for partial matches on text/varchar/char fields.).
| ~
| first_name=~a%
| Exact match, but you can include wildcards such as '%' and '?' in your search.
=====Search Examples=====
Given the following data set:
{| class=""listing listing2""
! first_name
! age
| Bob
| 10
| Cindy
| 12
| Julie
| 6
| Jake
| 8
| Kabob
| 16
Here are some example queries on this data set and their results:
{| class=""listing listing2""
! Query
! Matches
| age=>10
| match records where ''age'' is greater than 10. This includes ''Cindy'' and ''Kabob''.
| age=<10
| match records where ''age'' is less than 10. This includes ''Julie'' and ''Jake''
| age=>=10
| match records where ''age'' is greater or equal to 10. This includes ''Bob'', ''Cindy'', and ''Kabob''.
| age=<=10
| match records where ''age'' is less than or equal to 10. This includes ''Bob'', ''Julie'', and ''Jake''.
| age=8..10
| match records where ''age'' is between 8 and 10. This includes ''Bob'' and ''Jake''.
| first_name=bob
| Matches records where ''first_name'' contains ""bob"". This includes ''Bob'' and ''Kabob''.
| first_name==bob
| Matches records where ''first_name'' is exactly ""bob"". This includes ''Bob'' only.
| first_name=~J%
| Matches records that begin with ""J"". This includes ''Jake'' and ''Julie''
====Matching on Related Records====
It is also possible to match records based on their related data (i.e. data that is not physically stored in the record itself, but in related records via a relationship). For example if we want to find authors who have written about a particular topic, we would normally have to first find all of the articles that contain a topic, and then cross-reference that result against the ''authors'' table. With Xataface we can perform this query directly from the ''authors'' table using something like the following query:
This assumes that the ''authors'' table has a relationship named ''articles'' that contains all of the articles that an author has written. So the above query returns precisely those authors who have written at least one article whose ''title'' field contains the phrase ""sports"".
=====Anatomy of a Related Query=====
This matches all records in the current table such that at least one record in its '''' relationship matches the query: ''%field%=%query%''.
====Using the ''OR'' Operator====
Xataface allows you to search for more than one value at a time using the ''OR'' operator. E.g.
Would match all records with ''first_name'' containing ""bob"" or ""steve"".
Would match all records with ''first_name'' containing ""bob"" or exactly matching ""steve""
Would match all records with age less than 10 or greater than 20.
====Combining Multiple Queries in One Request====
Xataface allows you to filter on more than one field at a time. If you combine multiple queries in the same request it has the effect of strengthening the filter, matching only those rows that match ''both'' queries. E.g.
would match all records where ''age'' is greater than 10 '''AND''' that have ''first_name'' containing ""bob"".
=====Examples of Combined Queries=====
Given the same data set as the previous set of examples:
{| class=""listing listing2""
! first_name
! age
| Bob
| 10
| Cindy
| 12
| Julie
| 6
| Jake
| 8
| Kabob
| 16
would return no matches because there are no records that contain both ''first_name'' ""bob"" and ''age'' 11. However
would return only ''Bob'' and
would return only ''Kabob''.
====Special Common Queries====
=====Search For Null or Blank Value=====
Searching for a null value or a blank value is an exact match for """". Therefore you can simply search for ""="". E.g. To find records with a null or blank first_name you would use the query ''first_name==''. Or the full query:
=====Search for Non-blank Value=====
Searching for a non-blank value is the same as searching for a value greater than """". Therefore you can simply search for "">"". E.g. if you wanted to find records with a first_name, you would use the query ''first_name=>''. Or the full query:
==Preserved vs Non-preserved Parameters==
As mentioned above any parameters that are prefixed by a hyphen (i.e. ""="") are treated as directives rather than search filters. Hence if you want to use your own GET parameters you should always prefix them with a ""-"" to ensure that Xataface does not attempt to apply it as a search filter. In order to keep a consistent context for users, all browsing within the same table preserves both search queries and directives. Hence if you go to the URL:
It will show you the ''list'' tab of the ''people'' table with only those records with ''first_name'' ""bob"". Now if you click on the ''details'' tab it will preserve your query ''first_name''. The query will become something like:
index.php?-table=people&-action=details&first_name=bob&...etc... more parameters
(Although the parameters may appear in a different order). This allows you to navigate forward and back to previous and next records and stay within the same found set. It also ensures that if you click on the ''list'' tab to return to the list view, it will retain your place in the list.
Note that navigating within the same table it will also preserve your directives. E.g. If you specify the ''-limit'' directive to show 100 records per page:
And then you click on the ''details'' tab, it will retain your ''-limit'' parameter. Of course the ''-limit'' parameter is not actually used by the ''details'' action because it works on only one record at a time (it uses the ''-cursor'' parameter instead), when you click back on the ''list'' tab it will still show you 100 records per page.
Because of this, we call the ''-limit'' parameter a preserved parameter. It is retained when navigating within the same table. '''Note:''' parameters are retained in the HTTP Query string, not in sessions or cookies. This ensures that there are no surprises when you enter a URL to your Xataface application.
===Unpreserved Parameters===
If you ''don't'' want Xataface to preserve one of your parameters, you should prefix two hyphens to the parameter name. I.e. ""--"". One example of an unpreserved parameters throughout Xataface applications is the ''--msg'' parameter. The value of this parameter will be displayed on the page as an info message to the user. Clearly you don't want this parameter preserved across requests, as you only want the user to see a message once. E.g.
Would didsplay the mesage ""Record Successfully Saved"" at the top of the page. If you click on any link in the application, it will not retain the ''--msg'' parameter so you will not see the message on subsequent requests.
This parameter is useful if you want to give feedback to the user about an action that has been carried out.
{| class=""listing listing2""
! Parameter Type
! Prefix
! Examples
! Description
| Preserved
| -
| -limit, -skip, -cursor, -action, -table
| Parameter value is preserved when user navigates away from the page (within the same table).
| Unpreserved Parameters
| --
| --msg
| Parameter is ''NOT'' retrained with the user navigates away from the page.
","URL Conventions, GET Parameters, POST parameters, Request Parameters",en,0
Using_RecordGrid,115,"Using RecordGrid","==Xataface RecordGrid Class and Template==
Also see [http://lamp.weblite.ca/dataface-0.6/docs/index.php?-table=Classes&-action=browse&ClassID=30| RecordGrid in the API Doc].
[[toc collapse=0]]
As we learned in '''[http://xataface.com/documentation/tutorial/getting_started/dataface_actions Actions I: The Basics]''', we can retrieve custom data from the DB in action via queries. This site deals with showing data in tabular form, like it could be received from even such a query. It is done by using Dataface_RecordGrid.
===First Example===
class actions_testTableAction {
// Will be called from Xataface, if this action is called
function handle(&$params){
$this->app =& Dataface_Application::getInstance(); // reference to Dataface_Application object
// Custom query
$result = mysql_query(""select * from testTable"", $this->app->db());
$body = ""
// Error handling
$body .= ""MySQL Error ..."";
while($row = mysql_fetch_assoc($result)) // Fetch all rows
// Maybe do something with the single rows
$data[] = $row; // Add singe row to the data
mysql_free_result($result); // Frees the result after finnished using it
$grid = new Dataface_RecordGrid($data); // Create new RecordGrid with the data
$body .= $grid->toHTML(); // Get the HTML of the RecordGrid
// Shows the content (RecordGrid or error message) in the Main Template
df_display(array('body' => $body), 'Dataface_Main_Template.html');
You get your data from the query, fetch it into an associative array, create with it an RecordGrid and use the toHTML function. This is sure better than manually create the html tags around the data.
=====Screenshot: Blank RecordGrid=====
=====Screenshot: ResultList=====
===Colored Example===
As you see above, the resultlist has colored rows, our First Example not. But you can easily change this, when you override the Dataface_RecordGrid.html template:
{foreach from=$labels item=label}
{section name=row loop=$data}
{foreach from=$columns item=col}
The magic happens in
The {cycle values=""odd,even""} value cycles these two values and creates so the alternating row classes, like they are in the RecordList. By the way, {cycle ...} is a Smarty Function, see [http://www.smarty.net/docsv2/en/language.custom.functions.tpl| Smarty Doc].
(Find fruther information to template overriding in the tutorial and its links: [http://xataface.com/documentation/tutorial/getting_started/changing-look-and-feel| Changing the Look and Feel])
=====Screenshot: colored RecordGrid=====
===Example completly imitating ResultList===
The Colored Example doesn't look like the ResulList? Its rows aren't as high as theres? That's a styling matter or rather in this case a cause of the checkboxes. Here an example with checkboxes and added (empty) links, so it looks completly like the ResultList:
Change the part in action.php
while($row = mysql_fetch_assoc($result)) // Fetch all rows
// Maybe do something with the single rows
$row[''] = '';
$data[] = $row; // Add singe row to the data
mysql_free_result($result); // Frees the result after finnished using it
$grid = new Dataface_RecordGrid($data, // Create new RecordGrid with the data
array('', 'testID', 'name', 'description', 'number'),
//Order and selection of the colums
null); // No other labels defined -> it uses keys of the associative array
$body .= $grid->toHTML(); // Get the HTML of the RecordGrid
Dataface_RecordGrid.html template
{foreach from=$labels item=label}
{section name=row loop=$data}
{foreach from=$columns item=col}
=====Screenshot: RecordGrid completly imitating ResultList=====
=====Screenshot: ResultList=====
===Try it out===
Use the following code with static test data and any template in this article (or even without overriding it) to try it out.
class actions_testTableAction {
// Will be called from Xataface, if this action is called
function handle(&$params){
$this->app =& Dataface_Application::getInstance(); // reference to Dataface_Application object
$result_dummy = array(
array('testID' => '1', 'name' => 'testname',
'description' => 'a short description', 'number' => '258'),
array('testID' => '2', 'name' => 'another name',
'description' => 'a bit longer description to this data set', 'number' => '946'),
array('testID' => '3', 'name' => 'dummy name',
'description' => 'yea, a dummy data set!', 'number' => '1342'),
array('testID' => '4', 'name' => 'not empty',
'description' => 'this data set isn\'t empty ...', 'number' => '282'),
array('testID' => '5', 'name' => 'your entry',
'description' => 'this entry is only for you', 'number' => '79'),
array('testID' => '6', 'name' => 'no idea',
'description' => 'running out of ideas ...', 'number' => '203'),
array('testID' => '7', 'name' => 'the last one',
'description' => 'the end', 'number' => '26841')
$body = ""
foreach($result_dummy as $row) // Fetch all rows
// Maybe do something with the singe rows
$row[''] = '';
$data[] = $row; // Add singe row to the data
$grid = new Dataface_RecordGrid($data, // Create new RecordGrid with the data
array('', 'testID', 'name', 'description', 'number'),
//Order and selection of the colums
null); // No other labels defined -> it uses keys of the associative array
$body .= $grid->toHTML(); // Get the HTML of the RecordGrid
// Shows the content (RecordGrid or error message) in the Main Template
df_display(array('body' => $body), 'Dataface_Main_Template.html');
","RecordGrid, Dataface_RecordGrid, data in tabular form",en,
validateRegistrationForm,15,validateRegistrationForm,"==validateRegistrationForm() hook==
A hook that validates the input into the user registration form to make sure that the input is valid.
function validateRegistrationForm( array $values ) : mixed
{| class=""listing listing2""
! Name
! Description
| $values
| An associative array of the input values of the registration form.
| returns
| Mixed. If this method returns a PEAR_Error object then the validation will fail - and the user will be asked to correct his input.
===Validation via the Users table Delegate class===
Note that since the registration form is just a ""new record form"" for the users table, it is also possible (and preferred) to do validation through the users [[table delegate class]].
===See Also===
* [[afterRegister]]
* [[beforeRegister]]
* [[sendRegistrationActivationEmail]]
* [[getRegistrationActivationEmailInfo]]
* [[getRegistrationActivationEmailSubject]]
* [[getRegistrationActivationEmailMessage]]
* [[getRegistrationActivationEmailParameters]]
* [[getRegistrationActivationEmailHeaders]]",,en,0
validators,95,"validators:NAME fields.ini directive","Return to [[fields.ini file]]
In the fields.ini file you can specify validation rules to be applied to any field by adding the validators:NAME directive in that field's section of the [[fields.ini file]].
===Available Validators===
{| class=""listing listing2""
! Name
! Description
! Value
! Version
| required
| Field is required
| 1
| All
| maxlength
| Maximum number of characters allowed.
| $length
| All
| minlength
| Minimum number of characters allowed.
| $length
| All
| rangelength
| Range (min and max) characters allows
| $min,$max
| All
| email
| Input must be syntactically correct email address.
| 1
| All
| emailorblank
| Accepts an email address or a blank field.
| 1
| All
| regex
| Input must match the provided regular expression.
| A regular expression
| All
| lettersonly
| Input must contain only letters (i.e. [a-zA-Z]
| 1
| All
| numeric
| The input must contain a valid positive or negative integer or decimal number.
| 1
| All
| nopunctuation
| The input must not contain any of these characters: ( ) . / * ^ ? # ! @ $ % + = , "" ' > < ~ [ ] { }.
| 1
| All
| nonzero
| The input must not begin with zero.
| 1
| All
| uploadedfile
| The element must contain a successfully uploaded file.
| 1
| All
| maxfilesize
| The uploaded file must be no more than $size bytes.
| $size
| All
| The uploaded file must have a filename that matches the regular expression $file_rx.
| $file_rx
| All
To make a the first_name field required we add the following to the [[fields.ini file]]:
'''Note that fields that are declared NOT NULL in the database are required by default.'''. If you wanted to remove the ''required'' validator from a field that is NOT NULL in the database you would add the following to the [[fields.ini file]]:
===See Also===
* [[fieldname__validate]] - For more complex validation you can define the [[fieldname__validate]] method in the [[Delegate class methods|Table Delegate Class]].
* [http://www.devarticles.com/c/a/Web-Graphic-Design/Using-HTML-Quickform-for-Form-Processing/12/ HTML_QuickForm article] going over HTML_Quickform validation. Dataface's forms are built on HTML_QuickForm.
* [http://xataface.com/documentation/tutorial/getting_started/validation Form Validation] - Section from getting started tutorial introducing form validation in a tutorial format.
","validation, form validation, validators,validator:name",en,
validators:VALIDATOR_NAME:message,96,"validators:VALIDATOR_NAME:message directive for the fields.ini file","Return to [[fields.ini file]]
If you want to customize the error message associated with a particular [[validator|validation rule]] you can use the validators:VALIDATOR_NAME:message directive in the fields.ini file.
validators:VALIDATOR_NAME:message = MESSAGE
If you don't like the default error message that is displayed when you make the first_name field required, you can customize it with your own message. E.g.
validators:required:message = ""Please enter your first name""
===See Also===
* [[validators]] - The [[fields.ini file]] directive for adding a validation rule to a field. This directive must be used in conjunction with [[validators]].
* [[fieldname__validate]] - For more complex validation rules you can define them in the table delegate class.
* [http://xataface.com/documentation/tutorial/getting_started/validation Form Validation] - Section in the Getting Started tutorial on form validation.","validation messages,error messages,form validation rules",en,
valuelists.ini_file,5,valuelists.ini_file,"==valuelists.ini file Reference==
The valuelists.ini file stores value lists that can be used as [[vocabulary|vocabularies]] for select lists, checkbox groups, and other widgets the provide the user with options to choose from.
Each table can have an associated valuelists.ini file located in its [[table configuration directory]]. E.g. for a table named ""people"" its valuelists.ini file will be stored in ""tables/people/valuelists.ini"".
In addition you can define an application-wide valuelists.ini file in the root of your application's directory, whose valuelists can be used by any table.
The valuelists.ini file uses [[INI file syntax]], where a valuelist is defined by a single section of the INI file. E.g.
This example would define a single valuelist named ""colors"" with 3 values: r,g, and b (with corresponding labels ""Red"", ""Green"", and ""Blue). The values (the left of the equals sign) are stored in the database, while the labels are rendered on screen for the user's convenience.
===Dynamic Valuelists===
It is often advantageous to load valuelists from the database rather than store them directly in the valuelists.ini file. The __sql__ directive allows you to specify an SQL query which selects up to 2 columns (the first is the id and the second, the label).
__sql__ = ""select colorCode, colorName from colors""
===Defining Valuelists in a Delegate Class===
If you require more flexibility with the definition of your valuelists than can be gained from the valuelists.ini file, you can define your valuelist using PHP inside a delegate class. Essentially you just create a method that returns an associative array, where the keys are the IDs that are stored in the database, and the values are the values that are visible in the select list.
e.g. In either the application delegate class or a table delegate class:
function valuelist__colors(){
return array(
This method is called each time the valuelist is about to be used, so if your method performs any sort of intensive processing, it is a good idea to use a caching scheme so that it only runs the critical code once per request. For example, you could use a static variable as follows:
function valuelist__colors(){
static $colors = -1;
if ( !is_array($colors) ){
$colors = array();
$res = mysql_query(""select colorCode, colorName from colors"", df_db());
if ( !$res ) throw new Exception(mysql_error(df_db()));
while ($row = mysql_fetch_row($res) ) $colors[$row[0]] = $row[1];
return $colors;
In this example the database query is only executed once per request to load the $colors variable. The rest of the time it simply loads the cached value from $colors.","valuelists, dynamic valuelists, programmatically defined valuelists",en,0
viewable_editable_fields,180,"How to make a field editable for some users and only viewable for some other users","If we want only some users to edit a field and some other users only to view that field, then we need to define a '''fieldX__permissions()''' method for that field which gives desired permissions for specific users.
One solution is as below.
[Field Viewer]
[Field Editor extends Field Viewer]
==TableX.php (Delegate class of TableX)==
function fieldX__permissions(&$record) {
if($user) {
$role='Field Viewer';
else if($user->val('usernameField')==""UserY"")
$role='Field Editor';
return Dataface_PermissionsTool::getRolePermissions($role);
return Dataface_PermissionsTool::NO_ACCESS();
visibility:ConferenceID = hidden
This will make the ConferenceID in the relationship list view disappear.",,en,0
widget:atts,46,widget:atts,"==widget:atts Directive Reference==
The widget:atts directive in the fields.ini file allows any arbitrary HTML attributes to be added to any of the fields. It may also be used to specify javascript event handler functions that the widget should call upon the specified event. In particular, here are some examples of possible widget:atts directives:
===Available Widget Event Handlers===
{| class=""listing listing2""
! name
! description
! version
| [[field_size|widget:atts:size]]
| This directive sets the length of the input area a text box field, but it does not limit the number of characters that can be entered. For example:
widget:atts:size = 50
| ?
| [[field_maxlength|widget:atts:maxlength]]
| This directive limits the maximum number of characters that can be entered into a text box field. For example:
widget:atts:maxlength = 25
| ?
| [[field_style|widget:atts:style]]
| This directive specifies the style (font-size, font-family, etc.) for the field. For example:
widget:atts:style = ""font-size: 24pt; font-family: Apple Chancery""
| ?
| [[field_rows|widget:atts:rows]]
| This directive specifies the number of rows for a text area field to display. For example:
widget:atts:rows = 10
| ?
| [[field_cols|widget:atts:cols]]
| This directive specifies the number of columns for a text area input field (1 character = 1 column). For example:
widget:atts:cols = 10
| ?
| [[field_javascript_onchange|widget:atts:onchange]]
| This directive will cause the specified javascript function to be called with the value of the field whenever its value is changed (i.e. when you change the field and tab out of it). For example:
widget:atts:onchange = ""doJsFunction();""
| ?
| [[field_javascript_onclick|widget:atts:onclick]]
| This directive will cause the specified javascript function to be called with the value of the field whenever it is clicked. For example:
widget:atts:onclick = ""doJsFunction();""
| ?
===Helpful tutorials===
See the bottom of this page in the Getting Started tutorial for more details on the basic directives above:
[http://xataface.com/documentation/tutorial/getting_started/customizing Customizing Field labels, descriptions, and widgets]
This tutorial talks about how to use the javascript directives:
widget:editor,35,widget:editor,"==widget:editor fields.ini directive==
Return to [[fields.ini file]]
The widget:editor directive is applicable in the [[fields.ini file]]. It specifies the type of HTML editor that should be used. This directive is only used when [[widget:type]] is set to [[widget:type htmlarea|htmlarea]]. Xataface currently supports FCKEditor, TinyMCE, and NicEdit.
===Allowed Values===
{| class=""listing listing2""
! Value
! Description
! Version
| fckeditor
| Use [http://www.fckeditor.net/ FCKEditor]. This is the default value.
| all
| tinymce
| Use [http://tinymce.moxiecode.com/ TinyMCE editor].
| 0.6
| nicedit
| Use [http://www.nicedit.com/ NicEdit].
| 1.0.5
====Example 1: Using FCKEditor====
Given a field 'content' that you wish to be able to edit with FCKEditor, you would have the following section in your [[fields.ini file]]:
Note that since FCKEditor is the default editor, the above would give the same result as:
====Example 2: Using TinyMCE====
Further from example 1, if we wanted to use TinyMCE editor, we would change our directive to:
====Example 3: Using NicEdit====
Further from example 1:
==Enabling Image Uploads==
By default image uploads are disabled in these WYSIWYG editors.
===Enabling Image Uploads in FCKEditor===
# Create a directory named ''uploads'' inside your application directory. e.g.
cd /path/to/myapp/uploads
# Make the ''uploads'' directory writable by the webserver. e.g.
chmod 777 /path/to/myapp/uploads
# Edit the ''lib/FCKeditor/editor/filemanager/connectors/php/config.php'' file inside your ''xataface'' directory so that:
$Config['Enabled'] = true ;
$Config['UserFilesPath'] = '/url/to/myapp/uploads/' ;
// The path portion of the URL to your uploads directory.
// e.g. if your uploads directory is accessible at
// http://example.com/myapp/uploads, then this value should
// be /myapp/uploads/
$Config['UserFilesAbsolutePath'] = '/path/to/myapp/uploads/' ;
// The absolute file system path to your uploads directory.
// e.g. if your uploads directory is located at
// /home/myhome/www/myapp/uploads, then this value should be
// /home/myhome/www/myapp/uploads
# Now when you click on the ""Add Image"" link in your HTML editor, it will allow you to upload images and browse existing uploaded images.
widget:type,4,widget:type,"==widget:type Directive Reference==
The widget:type directive in the [[fields.ini file]] specifies the type of widget that should be used to edit a particular field in HTML forms. Xataface uses [http://pear.php.net/package/HTML_QuickForm/ HTML_QuickForm] for its form generation so theoretically any widget supported by HTML_QuickForm should work with Xataface.
===Available Widget Types===
{| class=""listing listing2""
! Name
! Description
! Version
| [[advmultiselect]]
| Two select lists with add/remove buttons. Selected items appear in the right select list. Options may be selected from the left select list.
| 1.0
| [[autocomplete]]
| An autocomplete. text field. This is not to be confused with the [[yui_autocomplete]] widget. The main difference is that this widget does not provide a drop-down list of possibilities, it just tries to complete what the user is typing inside the text field based on a valuelist.
| all
| [[calendar]]
| A DHTML pop-up calendar to select the date. [[Image:http://media.weblite.ca/files/photos/calendar_widget.png?max_width=400]]
| 0.5.3
| [[checkbox]]
| A checkbox or checkbox group.
Example 1: Checkbox as boolean on Tinyint field.
Example 2: Checkbox group to allow multiple selections.
| all
| [[date]]
| Select lists for month, year, day, hour, etc...
| all
| [[file]]
| A file widget (default type for [[container]] fields and [[blob]] fields. [[Image:http://media.weblite.ca/files/photos/file_widget.png?max_width=400]]
| all
| [[grid]]
| A grid widget for editing multiple rows of related records inside the edit form. Supports adding/removing/reordering. As of version 1.2.5, file uploads are not supported in the grid widget.
[[Image: http://media.weblite.ca/files/photos/grid_widget.png?max_width=500]]
| 1.0
| [[group]]
| A compound widget for editing multiple fields but storing the data in a single XML field.
| all
| [[hidden]]
| A hidden field
| all
| [[htmlarea]]
| A WYSIWYG (What you see is what you get) HTML editor. This defaults to [http://www.fckeditor.net/ FCKeditor], but [http://tinymce.moxiecode.com/ TinyMCE] is also supported. [[Image:http://media.weblite.ca/files/photos/htmlarea_widget.png?max_width=400]]
| all
| [[lookup]]
| A field that allows users to look-up a record from another table. THis is a good alternative to a select list. It doesn't use a vocabulary, so this is appropriate when vocabularies would be unpractical (for large vocabularies). You do, however need to specify the widget:table directive for the field so that the lookup knows from which table to load the records.
| 1.2
| [[password]]
| A password field.
| all
| [[select]]
| A select list.
Example 1: A single select.
Example 2: A multi-select. To use a multi-select, add repeat=1 to your fields.ini.
| all
| [[table]]
| A compound widget for editing tabular data. This widget dictates the storage format as XML.
| all
| [[text]]
| A text field
| all
| [[textarea]]
| A text area (multi-line text field)
| all
| [[time]]
| A select list of times separated by a specified interval (default 30 minutes).
| 0.7
| [[yui_autocomplete]]
| An autocomplete widget ported from the [http://developer.yahoo.com/yui/autocomplete/ Yahoo UI Library].
| 1.0
Writing_Custom_Authentication_Plugins,22,Writing_Custom_Authentication_Plugins,"==Writing a Custom Authentication Plugin for Xataface==
Xataface has a pluggable [[authentication]] framework that allows you to easily write your own custom [[authentication]] modules to tie in with other systems. Several plugins have already been created including:
* [[CAS Authentication Module|Yale CAS]]
* [[LDAP Authentication Module|LDAP]]
* [[Facebook Authentication Module|Facebook]]
* [[HTTP Authentication Module|HTTP]]
===Example: Creating a custom authentication plugin===
Before we begin, a couple of conventions:
# '''%XATAFACE_ROOT%''' refers to your Xataface installation directory. This is where all of the Xataface files are located includeing dataface-public-api.php
# '''%SITE_ROOT%''' refers to your Xataface application's installation directory. This is where your conf.ini file, index.php, and other application files are stored.
====About our plugin====
Our plugin will be the simplest, most useless authentication plugin you can imagine. It simply checks an array of usernames and passwords to see if the password that the user supplied is valid.
====Creating our plugin====
# Create the '''%XATAFACE_ROOT%/modules/Auth''' directory if it doesn't exist already. This directory will store all of our Xataface authentication plugins.
#Create the '''%XATAFACE_ROOT%/modules/Auth/XDB''' directory if it doesn't exist already. This directory will house all of the scripts and files associated with our custom plugin.
#Create a new PHP file named '''XDB.php''' inside our '''XDB''' directory that we just created, with the following contents:
class dataface_modules_XDB {
var $passwords = array(
'steve' => 'stevespass',
'mike' => 'foo'
function checkCredentials(){
$auth =& Dataface_AuthenticationTool::getInstance();
$creds = $auth->getCredentials();
if ( @$this->passwords[$creds['UserName']] == $creds['Password'] ){
return true;
} else {
return false;
# Now, change the '''[_auth]''' section of the conf.ini file to let Xataface know that we want to use our custom module:
# Try to log into your application. You'll notice that the only username/password combinations that are accepted are the ones that we specified in our '''$passwords''' array in our module.
This is just a simple example, but you can see how this can be expanded to provide more complex modules.
===checkCredentials() not enough?===
Some authentication plugins will need more control than simply checking credentials. Some plugins may want to make use if their own login forms, or redirect to other sites to handle the authentication. Xataface's [http://dataface.weblite.ca/Dataface_AuthenticationTool authentication tool] is up to the task, as virtually all parts of the login/logout process can be overridden and customized in your module. The previous example shows how the getCredentials() method can be overridden, but there are other methods that can be implemented to customize the login process as well.
* showLoginPrompt() - This method is called when it is time to display the login prompt for the user. It could also be made to redirect to another site that has a login prompt.
* logout() - This is called when the user tries to log out. If there are any special cookies of variables that need to be cleaned up to facilitate a successful logout, you could implement this method.
* [http://dataface.weblite.ca/getLoggedInUser getLoggedInUser()]
* [http://dataface.weblite.ca/getLoggedInUsername getLoggedInUsername()]
* getCredentials() - Handles the obtaining of credentials from the request or from the environment.
* authenticate() - Handles the whole login process
===See Also:===
* [[Application Delegate Class]] for before/after login/logout triggers that may be more appropriate in some circumstances than creating a custom authentication plugin.
* [[authentication|Xataface Authentication]]",,en,0
xataface_templates,23,xataface_templates,"==Xataface Templates==
Xataface uses the [http://smarty.php.net Smarty Template Engine] to power all of its templates. Templates are stored in the one of the following locations:
* %XATAFACE_ROOT%/Dataface/templates
* %SITE_ROOT%/templates
Where %XATAFACE_ROOT% is the Xataface directory (includes files such as dataface-public-api.php), and %SITE_ROOT% is the path to your application.
You may also have subdirectories within these templates directories.
===Cascading Templates===
Xataface uses a simple cascading technique for deciding which template to use. If there are templates in the %SITE_ROOT%/templates and %XATAFACE_ROOT%/Dataface/templates directories with the same name, then Xataface will use the one in the %SITE_ROOT%/templates directory. In this way, you are able to override any of Xataface's core templates by adding one of the same name to your %SITE_ROOT%/templates directory.
The most common template to override is the Dataface_Main_Template.html template which defines the look and feel for the entire application (e.g. header, footer, etc...). Hence, if you wanted to customize the look & feel of your application, you would likely start by copying %XATAFACE_ROOT%/Dataface/templates/Dataface_Main_Template.html into the %SITE_ROOT%/templates directory and make modifications to it as desired.
===Useful Smarty Tags introduced by Xataface===
In addition to the standard set of Smarty tags, Xataface templates provide some of its own.
==Xataface Templates==
Xataface uses the [http://smarty.php.net Smarty Template Engine] to power all of its templates. Templates are stored in the one of the following locations:
* %XATAFACE_ROOT%/Dataface/templates
* %SITE_ROOT%/templates
Where %XATAFACE_ROOT% is the Xataface directory (includes files such as dataface-public-api.php), and %SITE_ROOT% is the path to your application.
You may also have subdirectories within these templates directories.
===Cascading Templates===
Xataface uses a simple cascading technique for deciding which template to use. If there are templates in the %SITE_ROOT%/templates and %XATAFACE_ROOT%/Dataface/templates directories with the same name, then Xataface will use the one in the %SITE_ROOT%/templates directory. In this way, you are able to override any of Xataface's core templates by adding one of the same name to your %SITE_ROOT%/templates directory.
The most common template to override is the Dataface_Main_Template.html template which defines the look and feel for the entire application (e.g. header, footer, etc...). Hence, if you wanted to customize the look & feel of your application, you would likely start by copying %XATAFACE_ROOT%/Dataface/templates/Dataface_Main_Template.html into the %SITE_ROOT%/templates directory and make modifications to it as desired.
===Useful Smarty Tags introduced by Xataface===
In addition to the standard set of Smarty tags, Xataface templates provide some of its own.
{| class=""listing listing2""
! Name
! Description
! Version
| [[templates:tags:use_macro|use_macro]]
| Include another template with the option to override certain sections.
| 0.6
| define_slot
| Marks a section that can be overridden by other templates that include this one via the use_macro tag.
| 0.6
| fill_slot
| Overrides content in a template that has been included via the use_macro tag.
| 0.6
| block
| Marks an insertion point where content can be inserted by delegate classes and modules.
| 0.6
| load_record
| Loads a [http://dataface.weblite.ca Dataface_Record] object from the database to be used in the template.
| 0.6
| group
| Groups an array of records together based on a field value.
| 0.6
| img
| Displays a thumbnail of an image.
| 0.6
| actions
| Loads an associative array of actions defined in the actions.ini file, based on certain criteria.
| 0.6
| actions_menu
| Displays a menu of actions based on certain criteria.
| 0.6
| record_actions
| A specialization of the actions_menu tag. This displays a menu of actions only in the record_actions category.
| 0.6
| record_tabs
| A specialization of the actions_menu tag. This displays a menu of actions only in the record_tabs category.
| 0.6
| result_controller
| Displays the paging controls for the current table's records. Use this for any listing of records.
| 0.6
| result_list
| Displays the result list (from the list tab) for the current request.
| 0.6
| related_list
| Displays the related records list for the current request.
| 0.6
| bread_crumbs
| Displays the bread crumbs for the current request.
| 0.6
| search_form
| Displays the find form for the current table.
| 0.6
| language_selector
| Displays a menu to select the user's preferred language.
| 0.6
| next_link
| Displays a link to the next XXX records.
| 0.6
| prev_link
| Displays a link to the previous XXX records.
| 0.6
| jump_menu
| Displays the select list of the records found in this found-set so that the user can jump directly to any record.
| 0.6
| limit_field
| Displays a text field for the user to select the number of records to display per page.
| 0.6
| result_index
| Displays the index of pages (1 to XXX) for this query.
| 0.6
| summary_list
| Displays a list of records in the current found set using a summary format rather than the regular table format.
| 0.6
| sort_controller
| Displays a control to sort the results on any column.
| 0.6
| glance_list
| Displays a simple, brief list of records matching certain criteria.
| 0.6
| record_view
| Loads structured data for a record as required for the view tab.
| 0.6
| feed
| Generates a link to an RSS feed based on certain criteria.
| 0.6
| translate
| Display a section of text in the user's selected language. (i18n).
| 0.6
| if_allowed
| The contents of this block are shown only if the user has certain permissions.
| 0.6
| editable
| Make a section of the page editable using AJAX.
| 0.6
| abs
| Convert a URL into an absolute URL.
| 0.6
===Useful Template Variables===
Xataface makes certain variables available to every template:
{| class=""listing listing2""
! Name
! Description
! Version
| Reference to the $_REQUEST array (HTTP Request parameters, both GET and POST)
| 0.6
| Reference to the $_SESSION array (the session variables)
| 0.6
| The file system path to the Xataface directory (i.e. the directory containing all of the Xataface files such as dataface-public-api.php).
| 0.6
| The URL to the Xataface directory.
| 0.6
| The file system path to your application directory. (i.e. the directory containing your conf.ini and index.php files).
| 0.6
| The URL to your application directory.
| 0.6
| The URL to your application's script. This differs from the $ENV.DATAFACE_SITE_URL variable in that this also includes the script name.
| 0.6
| Same as $ENV.DATAFACE_SITE_HREF
| 0.6
| A reference to the application's conf array (i.e. the parsed contents of the conf.ini file).
| 0.6
| A reference to the Dataface_Application object for the application.
| 0.6
| A reference to the $_SERVER array.
| 0.6
| A reference to the current query (i.e. Dataface_Application::getInstance()->getQuery())
| 0.6
| $ENV.action
| The name of the current action as specified by the -action REQUEST parameter.
| 0.6
| $ENV.table
| The name of the current table as specified by the -table REQUEST parameter.
| 0.6
| $ENV.table_object
| A reference to the current table.
| 0.6
| $ENV.relationship
| The name of the current relationship as specified by the -relationship REQUEST parameter.
| 0.6
| $ENV.limit
| The value of the -limit REQUEST parameter. This is the number of records to show per page.
| 0.6
| $ENV.start
| The value of the -start REQUEST parmeter. This is the starting point in the result set which is currently being displayed.
| 0.6
| $ENV.resultSet
| A reference to the [http://dataface.weblite.ca/Dataface_QueryTool Dataface_QueryTool] object for this result set.
| 0.6
| $ENV.record
| A reference to the [http://dataface.weblite.ca/Dataface_Record Dataface_Record] object that is matched by the current query.
| 0.6
| $ENV.mode
| The name of the current mode. e.g. find, list, browse
| 0.6
| $ENV.language
| The 2-digit ISO language code that is currently selected as the user's preferred language.
| 0.6
| $ENV.prefs
| A reference to the preferences array ($conf['_prefs'])
| 0.6
| $ENV.search
| The value of the current full-text search (i.e. the search that was entered into the upper right search field.
| 0.6
==Smarty Plugins==
One of the most powerful features of [http://www.smarty.net Smarty] is its pluggable architecture. You can easily add your own custom plugins to a registered ""plugins"" directory to add functions, modifiers, blocks, and other features to your templates.
Prior to Xataface 2.0, you Smarty plugins could only be placed in the ''lib/Smarty/plugins'' directory of the Xataface distribution folder. This is not very conducive to Xataface updates, though. In general it is best practice to not change anything inside the xataface directory. Most other configuration and extensions can be handled by making changes to your application's directory which override corresponding functionality in Xataface.
As of Xataface 2.0, you can create a directory named ''plugins'' to your application directory, Smarty knows to look in this directory for plugins.
For versions of Xataface prior to 2.0, you can make a small modification to the SkinTool to also add support as desribed in [http://xataface.com/forum/viewtopic.php?f=4&t=6722 this post].
===Example Plugin===
The following is an example Smarty plugin adapted from [http://www.smarty.net/docs/en/plugins.functions.tpl this page] but modified slightly to work in Xataface. It is a simple ""eightball"" plugin that adds a tag {eightball} to Xataface that you can use in any of your templates. Whenever this tag is rendered it outputs one of a set of predefined strings randomly.
# Add a ''plugins'' directory to your application directory. i.e. ''path/to/app/plugins''
# Add a file inside this ''plugins'' directory called ''function.eightball.php '' with the following content:
# If you compare this function to the original example in [http://www.smarty.net/docs/en/plugins.functions.tpl the smarty tutorial] you'll notice that the 2nd parameter has been changed to type ''Dataface_SkinTool'' from ''Smarty_Internal_Template''. If you don't make this change, you will get a fatal error when you try to use the tag. This function defines an ''{eightball}'' tag that can be added to any Smarty template in Xataface.
# Next we'll create a template that uses this tag. If your application doesn't have a ''templates'' directory, create one now (i.e. path/to/app/templates).
# Add a file inside your templates directory called ''testing.html'' with the following content:
The eight ball says {eightball}
# Now we need to display this template somewhere in our interface. In this case, we'll choose the ''before_record_content'' block. (This will render the template before the main section of the view tab). Add the following method to your [[Application_Delegate_Class]]:
function block__before_record_content(){
df_display(array(), 'testing.html');
# Now if you load your application in a web browser and navigate to the details view for a record, you should see something like the following:
===See also:===
* [http://www.xataface.com/documentation/tutorial/getting_started/changing-look-and-feel Changing the Look & Feel of Xataface] (From the Getting Started Tutorial)
* [http://www.xataface.com/documentation/tutorial/customizing-the-dataface-look-and-feel Cusomizing the Xataface Look & Feel] Tutorial","templates, plugins, smarty",en,0
XataJax,113,"Introduction to XataJax","[[toc]]
Xataface 1.3 comes with a new module [[XataJax]] which comes installed standard. [[XataJax]] serves as a foundation for Javascript/AJAX powered Xataface applications and will hopefully usher in a new fresh generation of Xataface powered applications.
Xataface provides pieces of infrastructure:
# [[XataJax Compiler|A Javascript/CSS Compiler & Linker]]
# A Javascript component library & API
====The Javascript/CSS Compiler & Linker====
Web 2.0 and HTML 5 is a great platform for application development, but it presents a challenge when it comes to developing large-scale, robust applications. It can be difficult to manage applications that consist of dozens or even hundrends of javascript libraries, some of which depend on each other.
The XataJax compiler provides a solution to this problem by providing a just-in-time compilation of all of the javascripts that are necessary to service a particular request. It doesn't actually compile your Javascript into machine code, it just aggregates and minifies all of the javascript code together into a single file at runtime so that you don't have to worry about figuring out exactly which libraries you need to import in each template.
This has 2 key benefits:
1. Load time. By having all of the scripts grouped into a single file, it is much quicker for the client to load the your scripts.
2. Code organization. Since the compiler will automatically resolve the script dependencies, you can keep your code nicely organized, which produces a far more maintainable source code base.
====The Javascript Component Library & API====
The 2nd part of the XataJax module is a new API that will help you develop rich Web 2.0 applications that interact with your database. The will allow you to build forms more dyanmically with Javascript, or load, update, and delete records directly using a javascript API.
The goal is to eventually expose all important Xataface functionality via the XataJax API.
Additional modules may build on top of this API to produce alternative dynamic interfaces for Xataface using existing web UI component libraries like JQueryUI or Sencha.","XataJax, Ajax, Web 2.0",en,
XataJax_Compiler,114,"Introduction to the XataJax Compiler","Return to [[XataJax]]
'''DISCLAIMER''': This page introduces features that require Xataface 1.3 or higher. At present (Jan. 2011) only Xataface 1.2.6 has been released to the public.
===Compiler Directives===
{| class=""listing listing2""
! Name
! Description
! Version
| [[xatajax include directive|include]]
| Includes another javascript file inside the current one in place of this directive. Sample code://include
| XataJax 0.1 Xataface 1.3
| [[xatajax require directive|require]]
| Includes another javscript file inside the current one only if that file hasn't already been included. Sample code: //require
| XataJax 0.1 Xataface 1.3
| [[xatajax require-css directive|require-css]]
| Includes a CSS script in the CSS file. This will will search in the [[Dataface_CSSTool]] include path for the script. Sample code: //require-css
| XataJax 0.1 Xataface 1.3
| [[xatajax load directive|load]]
| XataJax 0.1 Xataface 1.3
===How it Works===
The XataJax compiler works similar to a regular code compiler. It provides 4 server-side directives to allow you to express dependencies between scripts and stylesheets:
# '''include''' : Includes another javascript file inside the current script in place of the '''include'' directive.
# '''require-css''' : Registers a dependency to a CSS file. If your script depends on a CSS file, then it can be registered in this way.
===Brief Example===
alert('You are in script A');
alert('You are in script B');
If you loaded ''scriptA.js'', it would actually result in the following javascript being executed:
alert('You are in script B');
alert('You are in script A');
Notice that it included ''scriptB.js'' inside script A before the alert of script A. That is why script B's alert comes first. Note that this example won't work if you simply try to load scriptA.js directly in Apache. These directives are only evaluated if the scripts are served by Xataface. Here is a simple Xataface action that demonstrates how to use this in your Xataface script.
====Creating a custom action====
In your application directory, create an ''actions'' directory if you don't already have one. Then create a single file named ''hello.php'' with the following content:
class actions_hello {
function handle($params){
$jsTool = Dataface_JavascriptTool::getInstance();
$jsTool->addPath('js', DATAFACE_SITE_URL.'/js');
echo ''.$jsTool->getHtml().'';
'''About this code:'''
$jsTool = Dataface_JavascriptTool::getInstance();
We start by obtaining an instance of the JavascriptTool. This is the object that does all of the magic of compiling your scripts and managing dependencies.
$jsTool->addPath('js', DATAFACE_SITE_URL.'/js');
This line adds the ''js'' directory to the tool's include path, and specifies (with the 2nd parameter) the URL to reach this directory also. The JavascriptTool works like most source code compilers. You need to give it the path where it can expect to find its libraries and scripts. Only paths that you add here will be searched for javascripts. You can add as many paths as you like. By default it will have the DATAFACE_PATH/js and the XATAJAX_PATH/js directories in the include path so you can directly reference any scripts in those directories always.
This is where we declare that we want to use ''scriptA.js'' in the current request. This line then assumes that the scriptA.js file is located in one of the directories of the current include path. In our case we make sure that it resides in the DATAFACE_SITE_PATH/js directory.
echo ''.$jsTool->getHtml().'';
On this line we simply output the HTML script tags that the javascript tool generates linking to our resulting script.
Now we can test our our action by going to the page index.php?-action=hello. If everything worked correctly you should see the appropriate alert dialogs appear - first telling you you're in Script B, then telling you you're in Script A. If it doesn't work, you should check your javascript error logs to see what went wrong.
'''NOTE:''' - This simple example actually shows you the step of writing out the HTML tags explicitly with the getHtml() method. If you are using a standard Xataface template that is based on the Dataface_Main_Template.html template, then this step is unnecessary because the XataJax module will automatically include this HTML just before the closing