page_name,page_id,page_title,content,keywords,language,original_page
GettingStarted:triggers,81,Triggers,"==Triggers==

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:<code><?
class tables_Course {}
</code>
# Okay, we want our trigger to be called every time a record is inserted. There are 2 possible triggers that can be defined, then:<nowiki>
<ul>
<li>beforeInsert</li>
<li>afterInsert</li>
</ul>
<p>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:</p>
</nowiki><code>
<?
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('admin_email@yourdomain.com','Subject Line', 'Message body'); 
    }
}
</code>
# 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:
<code>
function afterInsert(&$record){
    $response =& Dataface_Application::getResponse();
        // get reference to response array

    if ( mail('shannah@sfu.ca', 'Subject Line', 'Message Body') ){
        $response['--msg'] .= ""\nEmail sent to shannah@sfu.ca successfully."";
    } else {
        $response['--msg'] .= ""\nMail could not be sent at this time."";
    }
}
</code>

Now, when the user inserts a new record he will see a confirmation as follows:

[[Image:http://framework.weblite.ca/documentation/tutorial/getting_started/trigger-after-insert-confirm.gif]]

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.:
<code>
$response =& Dataface_Application::getResponse(); // correct!
$response = Dataface_Application::getResponse(); // WRONG!!
</code>

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:
<code>
<?
class tables_Course {
    function beforeInsert(&$record){
        $response =& Dataface_Application::getResponse();
        if ( mail('shannah@sfu.ca', 'Notification', 'Your record was created')){
            $response['--msg'] .= ""\nEmail sent successfully to shannah@sfu.ca"";
        } else {
            return PEAR::raiseError(
                ""Errors occurred while sending email.  Record could not be inserted"",
                 DATAFACE_E_NOTICE
            );
        }
    }
     
}
</code>

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:

[[Image:http://framework.weblite.ca/documentation/tutorial/getting_started/trigger-error.gif]]


'''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,
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.'''

[[toc]]

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:<code>
[_database]
    host=localhost
    name=mydb
    user=username
    password=mypass

[_tables]
    ;; This section lists the tables to include in your application menu
    table1=Label for table 1
    table2=Label for table 2
</code>
# Create an .htaccess (i.e. ''myapp/.htaccess'') file to prevent Apache from serving your ''conf.ini'' file:<code>
<FilesMatch ""\.ini$"">
Deny from all
</FilesMatch>
</code>  '''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:<code>
<?php
// Include the Xataface API
require_once 'xataface/dataface-public-api.php';

// Initialize Xataface framework
df_init(__FILE__, 'xataface')->display();
    // 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)
</code>
# 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====

[[Image:http://media.weblite.ca/files/photos/people-find.png?max_width=400]]

====New Record Form====

[[Image:http://media.weblite.ca/files/photos/people-new-record.png?max_width=400]]

====List View====

[[Image:http://media.weblite.ca/files/photos/people-list.png?max_width=400]]

===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
URL_Conventions,37,URL_Conventions,"==Xataface URL Conventions==

[[toc]]

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"":

index.php?-action=list&-table=people&first_name=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:

index.php?-action=list&-table=people&first_name==bob

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:
 index.php?-table=authors&articles/title=sports
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=====

 %relationship%/%field%=%query%
This matches all records in the current table such that at least one record in its ''<relationship>'' 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.
 first_name=bob+OR+steve
Would match all records with ''first_name'' containing ""bob"" or ""steve"".
 first_name=bob+OR+=steve
Would match all records with ''first_name'' containing ""bob"" or exactly matching ""steve""
 age=<10+OR+>20
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.
 age=>10&first_name=bob
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
|}

 first_name=bob&age=11
would return no matches because there are no records that contain both ''first_name'' ""bob"" and ''age'' 11.  However
 first_name=bob&age=10
would return only ''Bob'' and
 first_name=bob&age=16
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:
 index.php?-table=people&first_name==

=====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:
 index.php?-table=people&first_name=>

==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:
 index.php?-table=people&-action=list&first_name=bob
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:
 index.php?-table=people&-action=list&-limit=100
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.
 index.php?--msg=Record+Successfully+saved.
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.

===Summary===

{| 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
fieldname__validate,94,"fieldname__validate Delegate Class Method","Return to [[Delegate class methods]]

[[toc]]

===Synopsis===

Xataface allows you to add validation on any particular field in table by adding a fieldname__validate method to the table's delegate class of the form:
<code>
function myfield__validate(&$record, $value, &$params){
    if ( $value != 'Steve' ){
        $params['message'] = 'Sorry you must enter ""Steve""';
        return false;
    }
    return true;
}
</code>

===Parameters===

* &$record : A [http://dataface.weblite.ca/Dataface_Record Dataface_Record] object encapsulating the record we are validating.  Note that the values of this object correspond with the submitted values from the form, and not necessarily the actual values of the record in the database.
* $value : The value that is being inserted.
* &$params : An output array that can be used to pass back a message if validation fails.  You would set this array's 'message' parameter to be a message.

===Returns===

Returns a boolean value.  True if the value is ok and false if validation failed.

===See Also===

* [[validators]] - For simple validation rules you can use the [[validators|validator:VALIDATOR_NAME]] directive of the [[fields.ini file]].
* [http://xataface.com/documentation/tutorial/getting_started/validation Form Validation] - Section on form validation in the Getting Started tutorial.

","validate, validation, delegate class validation, custom validator",en,
validators:VALIDATOR_NAME:message,96,"validators:VALIDATOR_NAME:message directive for the fields.ini file","Return to [[fields.ini file]]

[[toc]]

===Synopsis===

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.

===Format===

<code>
[myfield]
    validators:VALIDATOR_NAME:message = MESSAGE
</code>

===Examples===

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.
<code>
[first_name]
    validators:required=1
    validators:required:message = ""Please enter your first name""
</code>

===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,
validators,95,"validators:NAME fields.ini directive","Return to [[fields.ini file]]

[[toc]]

===Synopsis===

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: <nowiki>( ) . / * ^ ? # ! @ $ % + = , "" ' &gt; &lt; ~ [ ] { }.</nowiki>
| 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
|-
|filename
| The uploaded file must have a filename that matches the regular expression $file_rx.
| $file_rx
| All
|}


===Examples===

To make a the first_name field required we add the following to the [[fields.ini file]]:
<code>
[first_name]
    validators:required=1
</code>

'''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]]:
<code>
[first_name]
    validators:required=0
</code>

===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,
valuelists.ini_file,5,valuelists.ini_file,"==valuelists.ini file Reference==

[[toc]]

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.

===Syntax===

The valuelists.ini file uses [[INI file syntax]], where a valuelist is defined by a single section of the INI file.  E.g.

<code>
[colors]
    r=Red
    b=Blue
    g=Green
</code>

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).

E.g.

<code>
[colors]
    __sql__ = ""select colorCode, colorName from colors""
</code>


===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:

<code>
function valuelist__colors(){
    return array(
        'r'=>'Red',
        'g'=>'Green',
        'b'=>'Blue'
    );
}
</code>

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:

<code>
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;
}
</code>

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
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:<nowiki><br/></nowiki>[[Image:http://xataface.com/documentation/tutorial/getting_started/application-structure-valuelists.gif]]
# Edit the valuelists.ini file so that it looks like:<code>
[Subjects]
	ENGL = English
	MATH = Math
	PHYS = Physics
	CHEM = Chemistry
</code> 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:<code>
[Subject]
	widget:type = select
	vocabulary = Subjects
</code> 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.<nowiki><br/></nowiki>[[Image:http://xataface.com/documentation/tutorial/getting_started/actions-menu-1.gif]]<nowiki><br/><br/></nowiki>This will bring up a form to create a new Course record, so that we can see what the form looks like. It should look like:<nowiki><br/></nowiki>[[Image:http://xataface.com/documentation/tutorial/getting_started/new-course-form-1.gif]]<nowiki><br/></nowiki>Notice that the ""Subject"" field is represented by a select widget, its options are as follows:<nowiki><br/></nowiki>[[Image:http://xataface.com/documentation/tutorial/getting_started/course-subject-pulldown-1.gif]]<nowiki><br/></nowiki> And if you look at the HTML source code for this select list, it would look like:<code>
<select class=""default"" id=""Subject"" name=""Subject"">
	<option value="""">Please Select...</option>
	<option value=""ENGL"">English</option>
	<option value=""MATH"">Math</option>
	<option value=""PHYS"">Physics</option>
	<option value=""CHEM"">Chemistry</option>
</select>
</code>

===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:<code>
[Subject]
widget:type = checkbox
vocabulary = Subjects
</code>

Now load the form again and notice that the 'Subject' field is now represented by checkboxes.

[[Image:http://xataface.com/documentation/tutorial/getting_started/checkbox-group-1.gif]]

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:<code>
PHYS
CHEM
</code>

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:<code>
[Programs]
	__sql__ = ""SELECT ProgramID, ProgramName FROM Program ORDER BY ProgramName""
</code> '''Note: Make sure you use two underscores on either side of 'sql' in the above example. It should be '__sql__' not '_sql_'.'''<nowiki><p></nowiki>This valuelist will be a list of the records in the 'Program' table in alphabetical order on the program name. Note that this query selects 2 columns. The first column is always taken to be the ID column of the value-list and the 2nd column (if specified) is the Name column of the valuelist. The ID column is what will actually be stored in the database, and the Name column is what will be shown to the user in place of the ID.<nowiki></p></nowiki>
# Add a field definition for the ProgramID field in the fields.ini file of the 'Course' table as follows:<code>
[ProgramID]
	widget:type = select
	vocabulary = Programs
</code>

Now we can load up our form and see what it looks like:

[[Image:http://xataface.com/documentation/tutorial/getting_started/programid-select-list.gif]]

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:<code>
<select class=""default"" id=""ProgramID"" name=""ProgramID"">
	<option value="""">Please Select...</option>
	<option value=""2"">Advanced Widgetry</option>
	<option value=""1"">Basic Widgetry</option>
	<option value=""3"">International Widgetry</option>
</select></code>

===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.

===Summary===

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:customizing,76,"Customizing Field labels, descriptions, and widgets","==Customizing Field labels, descriptions, and widgets==

Using simple INI configuration files, you can customize the look and feel of your application. You can change widgets, labels, field descriptions, and more.
In the previous 2 sections we learned how to create a simple application by desiging a database and then installing the basic directory structure to make our application operational. Now it is time to ""decorate"" the application a little bit. Decoration occurs by way of simple configuration files that are placed in strategic locations in the application. We can customize such things as:

* Widget types (e.g., use a select list for a field rather than a text field)
* Labels (e.g., The ProgramName field's label can say ""Program Name"" instead of just ""ProgramName"")
* Field Descriptions . You can add descriptions to fields to help explain their meaning and how to use the application.
* HTML attributes. (e.g., Make a text field 50 characters wide)

===Table Configuration Directories===

You will recall, that when we used the 'makesite' script to generate the directory structure for our web application, it created a directory named 'tables', with subdirectories named after each of the tables in our database. The directory structure of the application looked like:

[[Image:http://xataface.com/documentation/tutorial/getting_started/directory-structure-1.gif]]

The 'tables/Program' and 'tables/Course' are refered to as ""table configuration directories"" . All of the configuration files a table in a Xataface application are stored in its associated table configuration directory. For example all configuration files for the 'Program' table are located in the 'tables/Program' directory.

There are 4 main files that are generally contained in a table's configuration directory:

* '''fields.ini''' - Contains configuration for the fields of the table (e.g., field labels, descriptions, widget types, etc...)
* ''valuelists.ini''' - Contains value lists (vocabularies) that can be used in the table to limit input into certain fields like select lists.
* '''relationships.ini''' - Defines the relationships between this table and other tables in the application.
* '''<TableName>.php''' (where <TableName> is the name of the table. - A delegate PHP class that allows you to further customize the behavior of the application with respect to this table. May contain custom fields, importing/exporting functionality, permissions information, and more...

===Customizing Labels and Descriptions===

We will start off by adding custom labels and descriptions to the 'Program' table of our 'FacultyOfWidgetry' application. This sort of customization settings are placed in a file named 'fields.ini' inside the table's configuration directory.

# Create the 'fields.ini' file in the Program table configuration directory (i.e., tables/Programs/fields.ini).
# Add the following to this file:<code>
[ProgramName]
	widget:label = ""Program Name""
	widget:description = ""Enter the name of the program""
</code><nowiki><br></nowiki>Now look at the ""Edit Record"" form in the Xataface application:

[[Image:http://xataface.com/documentation/tutorial/getting_started/program-name-label-1.gif]]


Notice how the label for the ""ProgramName"" now says ""Program Name"" (note the space between ""Program"" and ""Name""). And its description matches the description specified in the fields.ini file.

The widget:label and widget:description attributes can be defined for any field in any table of the application.

===Using different widgets===

If no widgets are defined in the fields.ini file, a Xataface application will make a best guess at the type of widget that should be used to edit the value in a field. In general, the widgets used by default are as follows:

* VARCHAR, CHAR, INT : html text field
* DATE, DATETIME fields: calendar widget
* TEXT fields : html text area
* BLOB fields : html file upload field
* INT Fields with ""AUTO INCREMENT"" : html hidden field
* VARCHAR or CHAR fields with ""Password"" or ""password"" as part of the name : html password field
* ENUM fields : html select list
* SET fields : html checkbox group (not yet supported as of this writing).

You can change the widget that is used to edit a field by specifying a ""widget:type"" attribute for the field in the fields.ini file. For more information about the available widgets, see [[widget:type]].

====Example: Using HTML Editor to edit the HTMLOutline field====

Clearly the HTMLOutline field in the Program table is intended to store HTML content. By default our application only provides a text area to do the editing so the user is expected to enter the HTML markup by hand. It would be much better to provide the user with a WYSIWYG (What you see is what you get) HTML editor widget. That is exactly what we are going to do.
We will add a section to the fields.ini file so that it now looks like: <code>
[ProgramName]
	widget:label = ""Program Name""
	widget:description = ""Enter the name of the program""

[HTMLOutline]
	widget:type = ""htmlarea""
</code>

Now refresh the Xataface application in your web browser and look at the edit form for a record of the Program table:

[[Image:http://xataface.com/documentation/tutorial/getting_started/htmlarea-1.gif]]

As you can see, the HTMLOutline field now has an HTML Editor widget for editing. Most users will find this much nicer to work with than a normal text area. Xataface uses FCKEditor for its html editor widget.

There are a number of widgets that can be specified in the [[widget:type]] parameter:

* '''[[checkbox]]''' - An HTML checkbox (or checkbox group depending on context).
* '''[[date]]''' - Month/Day/Year select lists for selecting dates.
* '''[[calendar]]''' - A text field with a button that opens a small calendar widget when clicked.
* '''[[group]]''' - A complex widget type for editing multiple values as a group (useful for XML fields)
* '''[[hidden]]''' - a hidden field
* '''[[password]]''' - An HTML password widget
* '''[[select]]''' - An HTML select list (requires the 'vocabulary' attribute)
* '''[[static]]''' - an uneditable field
* '''[[table]]''' - A complex widget type for editing multiple values in a tabular format (Useful for XML fields)
* '''[[text]]''' - an html text field
* '''[[textarea]]''' - an html text area

===Changing HTML attributes of widgets===

Sometimes you may want even finer grained control of your widgets' appearance than to just specify the type, label, and desription. Perhaps you want to make a text field 50 characters wide, or to set the CSS class of the html element. This can be done using the 'widget:atts:' parameter for a field. A short example is the easiest way to explain how this works.

Modify the fields.ini for the Program table so it looks like:<code>
[ProgramName]
widget:label = ""Program Name""
widget:description = ""Enter the name of the program""
widget:atts:size = 50
widget:atts:style = ""font-size: 24pt; font-family: Apple Chancery""

[HTMLOutline]
widget:type = htmlarea
</code>

We have added 2 lines:<code>
widget:atts:size = 50
widget:atts:style = ""font-size: 24pt; font-family: Apple Chancery""
</code>

What this does is add the html attributes size=""50"" and style=""font-size: 24pt; font-family: Apple Chancery"" to the html text field that is used to edit the ProgramName field.
Look at the results:

[[Image:http://xataface.com/documentation/tutorial/getting_started/widget-atts-1.gif]]

The HTML tag for the text field now looks like:<code>
<input class=""default"" id=""ProgramName"" name=""ProgramName"" 
	type=""text"" size=""50"" 
	style=""font-size: 24pt; 
		font-family: Apple Chancery"" 
	value=""Basic Widgetry"" 
/>	
</code>
In fact you can add arbitrary attributes to any of the fields using the same convention. Some useful examples are:

* '''[[widget:atts:rows]]''' for text areas to set the number of rows of text they should display.
* '''[[widget:atts:cols]]''' for text areas to set the number of columns (1 character = 1 column)
You can even use javascript calls in here if you like:
* '''[[widget:atts:onclick]]''' = ""doJsFunction();""

===Download source files===

[http://xataface.com/documentation/tutorial/getting_started/facultyofwidgetry-6-tar.gz Download the source files] for this application as a tar.gz archive
These source files reflect the state of the application at the current point of the tutorial. As changes are made to the application in later sections, downloads of those versions are made available for download also.

===Summary===
In this section we learned how to change the labels, descriptions, and widgets for fields. We also learned how to add HTML attributes to the widgets to achieve very fine-grained control over the display of our forms.","widget labels descriptions onclick handlers",en,
Introduction_to_the_Xataface_API,101,"Introduction to the Xataface API","Back to [http://xataface.com/wiki the wiki]

[[toc]]

===Synopsis===

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====

<code>
// 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');
</code>

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====

<code>
//  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 ""<br>Person "".$person->val('person_id')."" is named "".$person->val('first_name');
}
</code>

'''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. <code>
$people = df_get_records_array('people',array(), null, null, false);
</code>

====Editing and Saving a Record====

<code>
$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
$person->save();
</code>

","xataface api, df_get_record, df_get_records_array, Dataface_Record, Editing, Saving, Loading, Searching",en,
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.

===Features===

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.

[[toc]]

===Synopsis===

The XataJax compiler is a Javascript CSS compiler and linker that comes with the [[XataJax]] module and will be a standard part of Xataface starting in version 1.3.  It provides a mechanism to process and compile (or so to speak) all of the javascripts required for a page request at the time that the page is requested.  This results in a more scalable, manageable javascript and CSS source base - and in improved performance for your applications.

===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:<code>//include <myscript.js></code>
| 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: <code>//require <myscript.js></code>
| 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: <code>//require-css <mystyles.css></code>
| XataJax 0.1 Xataface 1.3
|-
| [[xatajax load directive|load]]
| Loads the specified Javascript file in a separate script tag.  This enables you to reference other scripts without including them in the same bundle, allowing for more effective caching.  Sample code: <code>//load <myscript.js></code>
| 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''' : Includes another javascript file inside the current script (if it hasn't already been included) - i.e. if a script is included twice with a require directive, it will only actually be included once.
# '''load''' : Registers a dependency to another script, but doesn't include it in the same bundle.  This may be used if your script requires code from another javascript, but you don't want it all to be bundled into the same javascript file.  This may help with caching in certain cases.
# '''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===

''scriptA.js'':
<code>
//require <scriptB.js>
alert('You are in script A');
</code>

''scriptB.js'':
<code>
alert('You are in script B');
</code>

If you loaded ''scriptA.js'', it would actually result in the following javascript being executed:
<code>
alert('You are in script B');
alert('You are in script A');
</code>

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:
<code>
class actions_hello {
    function handle($params){
        $jsTool = Dataface_JavascriptTool::getInstance();
        $jsTool->addPath('js', DATAFACE_SITE_URL.'/js');
        $jsTool->import('scriptA.js');
        echo '<html><head></head><body>'.$jsTool->getHtml().'</body></html>';
        exit;
    }
}
</code>

'''About this code:'''

<code>$jsTool = Dataface_JavascriptTool::getInstance();</code>
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.

<code>$jsTool->addPath('js', DATAFACE_SITE_URL.'/js');</code>
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.

<code> $jsTool->import('scriptA.js');</code>
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.

<code>echo '<html><head></head><body>'.$jsTool->getHtml().'</body></html>';</code>
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 </body> tag in your pages.



","XataJax, compiler, javascript, css, compiler",en,
_auth,97,"_auth section of the conf.ini file","[[conf.ini file|Return to conf.ini file]]

[[toc]]

===Synopsis===

The ''_auth'' section of the conf.ini file includes configuration directives to enable authentication in a Xataface application.  For more information about authentication and registration see [[authentication]].  This section may include the following directives:

===Directives===

{| class=""listing listing2""
|-
! Directive
! Description
! Required
! Default
! Version
|-
| users_table
| The name of the table that contains your user accounts.
| Yes
| None
| 0.6
|-
| username_column
| The name of the column that stores the username.
| Yes
| None
| 0.6
|-
| password_column
| The name of the column that stores the password.
| Required if using basic authentication.
| None
| 0.6
|-
| auth_type
| Specifies the authentication module that is being used.  E.g. basic, cas, ldap, http, facebook, etc...
| No
| basic
| 0.6
|-
| allow_register
| Flag to enable user registration.  If this is set to 1, then a ''register'' link will appear below the login form.
| No
| 0
| 0.8
|-
| session_timeout
| Number of seconds of inactivity after which the user will be logged out. Note: Arithmetic don't work in the conf.ini, use seconds.
| No
| 86400 (=> 24*60*60 (24 hours))
| 1.3rc4
|}

===See Also===

* [[authentication]] - Overview of Xataface Authentication
* [[conf.ini file]] - Directives available in the conf.ini file.","_auth,authentication,conf.ini file,allow_register",en,
__global__,106,"__global__ section for the fields.ini file","Return to [[fields.ini file]]

[[toc]]

===Synopsis===

The fields.ini file supports a __global__ section that applies to all fields in the current table.  This is particularly useful for setting up default functionality that you wish to see on all fields except a few.  For example you may wish to have all fields hidden from list view by default, and only explicitly enable a few.  Same for CSV export or the details form.

===Example 1: Hiding All Fields from List View===

In the fields.ini file:
<code>
[__global__]
    ;; hide all of the fields from list view
    visibility:list=hidden

[first_name]
    ;; show the first name in list view 
    visibility:list=visible

[last_name]
    visibility:list=visible

;;.... etc....
</code>

In the above example we used the __global__ section to declare that we want all fields to be hidden from list view by default.  Then we explicitly showed first_name and last_name in list view. In this case only first_name and last_name will appear in the list view.

==See Also==

*[[fields.ini file]]
*[[visibility:list]]","__global__, fields.ini, visibility:list",en,
sql_delegate_method,87,"__sql__ Delegate Method","return to [[Delegate class methods]]

===Synopsis===

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.

===Example===

Given the table foo, its delegate class:

<code>
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"";
    }
}
</code>

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,
