### Full Example with Datagrid Button Setup
Source: https://www.grocerycrud.com/docs/set-datagrid-button
A comprehensive example demonstrating the setup of a datagrid, including relation and display configurations, and the addition of a custom datagrid button.
```php
$crud->setTable('employees');
$crud->setSubject('Employee', 'Employees');
$crud->setRelation('officeCode','offices','city');
$crud->displayAs('officeCode','City');
// The below code is just to show you how to use the datagrid button at the demo page.
$crud->setDatagridButton('Add Office', 'plus', '#add-office-mock');
// A better real-world example would be the below line:
// $crud->setDatagridButton('Add Office', 'external-link-alt', 'https://example.com', true);
```
--------------------------------
### Full Example: Setting Language Path and Language
Source: https://www.grocerycrud.com/docs/set-language-path
A complete example showing table setup, column definitions, language path configuration, and rendering the CRUD output.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->setLanguagePath('application/language/grocery-crud');
$crud->setLanguage('Spanish');
$output = $crud->render();
```
--------------------------------
### Offices CRUD Implementation Example
Source: https://www.grocerycrud.com/docs/grocery-crud-enterprise-laravel-installation
This snippet illustrates how to quickly create another CRUD interface, for example, offices, by reusing the refactored Grocery CRUD Enterprise setup methods.
```php
public function offices()
{
$crud = $this->_getGroceryCrudEnterprise();
$crud->setTable('offices');
$crud->setSubject('Office', 'Offices');
$output = $crud->render();
return $this->_showOutput($output);
}
```
--------------------------------
### Example Native PHP Project Structure
Source: https://www.grocerycrud.com/docs/grocery-crud-enterprise-installation
An example directory structure for a native PHP project before installing Grocery CRUD Enterprise.
```bash
├── assets
├── index.php
└── customers.php
```
--------------------------------
### Full setRelationNtoN Example
Source: https://www.grocerycrud.com/docs/set-relation-n-to-n
A comprehensive example demonstrating the setup of N-to-N relationships, both with and without sorting capabilities, for 'actors' and 'categories'.
```php
$crud->setTable('film');
$crud->setSubject('Film', 'Films');
// With the ability to order the results
$crud->setRelationNtoN(
'actors', 'film_actor',
'actor', 'film_id',
'actor_id', 'fullname',
null, null, 'priority'
);
// Without the ability to order the results
$crud->setRelationNtoN(
'categories', 'film_category',
'category', 'film_id',
'category_id', 'name'
);
$output = $crud->render();
```
--------------------------------
### Full Example: Setting Table, Subject, and Add Fields
Source: https://www.grocerycrud.com/docs/add-fields
This example demonstrates a complete setup for GroceryCRUD, including setting the table, subject, and specifying fields for the add form using addFields. The render method is called to generate the output.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->addFields(['customerName','phone','addressLine1','creditLimit']);
$output = $crud->render();
```
--------------------------------
### Basic Grocery CRUD Enterprise Example
Source: https://www.grocerycrud.com/docs/grocery-crud-enterprise-installation
A minimal example demonstrating how to initialize Grocery CRUD Enterprise, set a table and subject, and render the output. This example assumes 'database.php' and 'config.php' are included.
```php
setTable('customers');
$crud->setSubject('Customer', 'Customers');
$output = $crud->render();
if ($output->isJSONResponse) {
header('Content-Type: application/json; charset=utf-8');
echo $output->output;
exit;
}
$js_files = $output->js_files;
$output = $output->output;
include('view.php');
```
--------------------------------
### Full Example: Setting Table, Fields, and API URL Path
Source: https://www.grocerycrud.com/docs/set-api-url-path
This snippet demonstrates a complete setup including setting the table, defining fields, and configuring the API URL path for Grocery CRUD. All subsequent AJAX requests will be sent to the specified API URL.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->fields(['customerName','phone','addressLine1','creditLimit']);
$crud->setApiUrlPath('https://demo.grocerycrud.com/set-api-url-path');
$output = $crud->render();
```
--------------------------------
### Basic setActionButtonMultiple Example
Source: https://www.grocerycrud.com/docs/set-action-button-multiple
A basic example demonstrating how to set up an action button for multiple selections. The URL is a placeholder and does not perform redirection.
```php
$url = 'https://example.com/view_avatar';
$crud->setActionButtonMultiple('Avatar', 'fa fa-user', $url, true);
```
--------------------------------
### Full Example: Setting Theme and Theme Path
Source: https://www.grocerycrud.com/docs/set-theme-path
This example demonstrates setting a specific theme ('Cyborg') and then defining a custom path for themes using setThemePath.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->setTheme('Cyborg');
$crud->setThemePath('private/themes/');
$output = $crud->render();
```
--------------------------------
### Full Example with setSkin
Source: https://www.grocerycrud.com/docs/set-skin
This example demonstrates setting the 'dark' skin and configuring basic table and subject settings for a customer management interface. It includes rendering the output.
```php
$crud->setSkin('dark');
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$output = $crud->render();
```
--------------------------------
### Full Example: Setting Up and Unsetting Clone Fields
Source: https://www.grocerycrud.com/docs/unset-clone-fields
This example demonstrates how to set up the table, subject, enable cloning, and then unset specific fields for the clone operation.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->setClone();
$crud->unsetCloneFields(['salesRepEmployeeNumber','creditLimit']);
$output = $crud->render();
```
--------------------------------
### Full Example of setRules in GroceryCRUD
Source: https://www.grocerycrud.com/docs/set-rules
A complete example showing the setup of a GroceryCRUD table, columns, and the application of validation rules using the setRules method. This illustrates a practical use case for setting multiple validation constraints.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->setRules(
[
[
'fieldName' => 'creditLimit',
'rule' => 'min',
'parameters' => '100'
],
[
'fieldName' => 'postalCode',
'rule' => 'lengthBetween',
'parameters' => ['4','6']
],
]
);
$output = $crud->render();
```
--------------------------------
### Full setActionButtonMultiple Example with Single Action Button
Source: https://www.grocerycrud.com/docs/set-action-button-multiple
A comprehensive example showing the setup of setActionButtonMultiple for batch actions and a corresponding setActionButton for single row actions. The URL uses a placeholder '#/avatar/' for demonstration.
```php
$crud->setTable('employees');
$crud->setSubject('Employee', 'Employees');
$crud->setRelation('officeCode','offices','city');
$crud->displayAs('officeCode','City');
$crud->unsetEdit();
// For demo purposes we are using the # so we will not have a new URL redirection
$crud->setActionButtonMultiple('Avatar', 'fa fa-user', '#/avatar/');
// Although this is not required, it is better for a usability perspective to
// also include the button for a single use
$crud->setActionButton('Avatar', 'fa fa-user', function ($row) {
return '#/avatar/' . $row->employeeNumber;
}, false);
```
--------------------------------
### Full Example with setDatabaseSchema
Source: https://www.grocerycrud.com/docs/set-database-schema
An example demonstrating the usage of setDatabaseSchema along with other common GroceryCRUD configurations like setting the table, subject, and columns.
```php
$crud->setDatabaseSchema('example_schema');
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
```
--------------------------------
### Full example with requiredCloneFields and requiredAddFields
Source: https://www.grocerycrud.com/docs/required-clone-fields
This example demonstrates the complete setup for enabling required fields during the cloning process. It includes setting the table, subject, display aliases, enabling cloning, and disabling deletion, followed by the crucial definition of both clone and add required fields.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->displayAs('customerName', 'Name');
$crud->displayAs('contactLastName', 'Last Name');
$crud->setClone();
$crud->unsetDelete();
// In order to make the clone form fields required, we need to use requiredCloneFields and requiredAddFields
$crud->requiredCloneFields(['customerName', 'contactLastName', 'contactFirstName']);
$crud->requiredAddFields(['customerName', 'contactLastName', 'contactFirstName']);
$output = $crud->render();
```
--------------------------------
### Full Example of Setting Required Fields
Source: https://www.grocerycrud.com/docs/required-fields
This example demonstrates setting up a table, columns, and then defining required fields for customer data before rendering the CRUD output.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->requiredFields(['customerName', 'contactLastName', 'contactFirstName']);
$output = $crud->render();
```
--------------------------------
### Basic Example: Unset Pagination
Source: https://www.grocerycrud.com/docs/unset-pagination
This basic example demonstrates how to unset pagination for a standard GroceryCRUD table setup.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->unsetPagination();
$output = $crud->render();
```
--------------------------------
### Basic Grocery CRUD Enterprise Setup (example.php)
Source: https://www.grocerycrud.com/docs/grocery-crud-enterprise-installation
This script demonstrates the basic setup for Grocery CRUD Enterprise. It includes necessary files, initializes the CRUD object with configuration and database details, sets the table and subject, and renders the output. It also handles JSON responses for AJAX requests.
```php
setTable('customers');
$crud->setSubject('Customer', 'Customers');
$output = $crud->render();
if ($output->isJSONResponse) {
header('Content-Type: application/json; charset=utf-8');
echo $output->output;
exit;
}
$js_files = $output->js_files;
$output = $output->output;
include('view.php');
```
--------------------------------
### Complete Example with Required Add Fields
Source: https://www.grocerycrud.com/docs/required-add-fields
This example demonstrates setting up a GroceryCRUD instance, defining columns, read-only edit fields, and then specifying fields that are required only for adding new customers.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->displayAs('customerName', 'Name');
$crud->displayAs('contactLastName', 'Last Name');
// A real case example where you need to have some fields required to add
// form but the user can't edit them later.
$crud->readOnlyEditFields(['customerName', 'contactLastName', 'contactFirstName']);
$crud->requiredAddFields(['customerName', 'contactLastName', 'contactFirstName']);
$output = $crud->render();
```
--------------------------------
### Full Example: Custom Rule Integration
Source: https://www.grocerycrud.com/docs/set-rule
A complete example demonstrating how to define a custom validation rule and apply it to form fields within a GroceryCRUD setup.
```php
\Valitron\Validator::addRule('checkGreekPhoneNumber', function($field, $value, array $params, array $fields) {
if (strstr($value, '+30')) {
return true;
}
return false;
}, 'must start with +30');
...
$crud->setTable('customers');
...
$crud->displayAs('mobile_phone', 'Mobile');
$crud->displayAs('home_phone', 'Home Number');
...
$crud->setRule('mobile_phone', 'checkGreekPhoneNumber');
$crud->setRule('home_phone', 'checkGreekPhoneNumber');
...
$output = $crud->render();
```
--------------------------------
### Full CRUD Setup
Source: https://www.grocerycrud.com/docs/full-example
Configures the customer table, sets column display names, defines fields for operations, and specifies required fields. This is a common starting point for table configuration.
```php
$crud->setTable('customers')
->setSubject('Customer', 'Customers')
->columns(['customerName', 'contactLastName', 'phone', 'city', 'country', 'creditLimit'])
->displayAs('customerName', 'Name')
->displayAs('contactLastName', 'Last Name')
->fields(['customerName', 'contactLastName', 'phone', 'city', 'country', 'creditLimit'])
->requiredFields(['customerName', 'contactLastName']);
$output = $crud->render();
```
--------------------------------
### Full Example with setLanguage
Source: https://www.grocerycrud.com/docs/set-language
This example demonstrates setting the language to Spanish along with other configurations like table, subject, fields, columns, and display names.
```php
$crud->setTable('customers');
$crud->setSubject('Cliente', 'Clientes');
$crud->fields(['customerName','phone','addressLine1','creditLimit']);
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->setLanguage('Spanish');
$crud->displayAs('customerName', 'Nombre')
->displayAs('phone', 'Teléfono')
->displayAs('addressLine1', 'Dirección')
->displayAs('creditLimit', 'Límite de crédito');
$output = $crud->render();
```
--------------------------------
### Full Example: unsetBootstrap with GroceryCRUD
Source: https://www.grocerycrud.com/docs/unset-bootstrap
This example demonstrates how to integrate unsetBootstrap into a typical GroceryCRUD setup. It configures the table and columns, then disables Bootstrap CSS before rendering the output. Ensure your project's template provides Bootstrap CSS when using this function.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->unsetBootstrap();
$output = $crud->render();
```
--------------------------------
### Full Example: Customizing Multiple Field Options
Source: https://www.grocerycrud.com/docs/field-options
This example demonstrates setting up a GroceryCRUD table and then applying hint text to multiple fields to enhance user experience. The hint text provides guidance for each field.
```php
$crud->setTable('employees');
$crud->setSubject('Employee', 'Employees');
$crud->setRelation('officeCode','offices','city');
$crud->displayAs('firstName','First Name');
$crud->displayAs('lastName','Last Name');
$crud->displayAs('jobTitle','Job Title');
$crud->displayAs('officeCode','City');
$crud->fieldOptions('firstName', [ 'hint_text' => 'First name of the employee' ]);
$crud->fieldOptions('lastName', [ 'hint_text' => 'Last name of the employee' ]);
$crud->fieldOptions('extension', [ 'hint_text' => 'Internal phone extension' ]);
$crud->fieldOptions('email', [ 'hint_text' => 'Email address of the employee' ]);
$crud->fieldOptions('jobTitle', [ 'hint_text' => 'Job title of the employee' ]);
$crud->fieldOptions('officeCode', [ 'hint_text' => 'City of the office' ]);
$output = $crud->render();
```
--------------------------------
### Full Example: Setting Up and Unsetting Edit Fields
Source: https://www.grocerycrud.com/docs/unset-edit-fields
This example demonstrates how to set up the table and subject, enable read functionality, and then use unsetEditFields to exclude 'salesRepEmployeeNumber' and 'creditLimit' before rendering the output.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->setRead();
$crud->unsetEditFields(['salesRepEmployeeNumber','creditLimit']);
$output = $crud->render();
```
--------------------------------
### Example: Set Quick Search Value on Button Click
Source: https://www.grocerycrud.com/docs/javascript-events
This example demonstrates setting the quick search value for the 'department_id' column to '3' when an external button is clicked.
```html
```
```javascript
document.getElementById('setSearchValue').addEventListener('click', () => {
groceryCrudSetQuickSearchValue('department_id', '3');
});
```
--------------------------------
### Full Example with displayAs Array
Source: https://www.grocerycrud.com/docs/display-as
This example demonstrates setting up a table, columns, and then using the displayAs function with an array to customize the labels for various fields across the CRUD interface.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->setRead();
$crud->displayAs([
'customerName'=> 'Customer Name',
'addressLine1'=> 'Address 1',
'creditLimit'=> 'Credit Limit',
'contactLastName' => 'Last Name',
'contactFirstName'=> 'First Name',
'addressLine2' => 'Address 2',
'postalCode' => 'Postal Code',
'salesRepEmployeeNumber' => 'Employee Number'
]);
$output = $crud->render();
```
--------------------------------
### Full Example with setUniqueId
Source: https://www.grocerycrud.com/docs/set-unique-id
This example demonstrates setting a unique ID for a customer table, enabling client-side caching of preferences like sorting and filtering.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','country','state','addressLine1']);
$crud->setUniqueId('customers_1234');
return $crud->render();
```
--------------------------------
### Full Example with Dependent Relations
Source: https://www.grocerycrud.com/docs/set-dependent-relation
This example demonstrates setting up multiple dependent relations for continents, countries, and cities. It requires corresponding setRelation calls for each field.
```php
$crud->setTable('customers_db');
$crud->setSubject('Customer', 'Customers');
$crud->displayAs('continent_id', 'Continent');
$crud->displayAs('country_id', 'Country');
$crud->displayAs('city_id', 'City');
$crud->setRelation('continent_id','continents','name');
$crud->setRelation('country_id','countries','name');
$crud->setRelation('city_id','cities','name');
$crud->setDependentRelation('country_id','continent_id','continent_code');
$crud->setDependentRelation('city_id','country_id','country');
$output = $output->render();
```
--------------------------------
### Full example of fields() usage
Source: https://www.grocerycrud.com/docs/fields
This example shows a complete implementation of the fields() method for a customer form, illustrating its effect on the datagrid and form layers.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->fields(['customerName', 'phone', 'addressLine1', 'creditLimit']);
$output = $crud->render();
```
--------------------------------
### Configuring GroceryCRUD Settings (v2)
Source: https://www.grocerycrud.com/docs/migrating-from-v2-to-v3
Example of passing settings as the first parameter when initializing GroceryCRUD in v2.
```javascript
// code before
$('.gc-container').groceryCrud({
callbackBeforeInsert: function () {
console.log('callback that is called right before the insert');
}
});
```
--------------------------------
### Full Example: Applying unsetOperations
Source: https://www.grocerycrud.com/docs/unset-operations
This example demonstrates how to set up a table, subject, columns, and then apply unsetOperations() to restrict user actions. The output shows only the datagrid with print and export options available.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->unsetOperations();
$output = $crud->render();
```
--------------------------------
### Full Example: Disable Add Operation
Source: https://www.grocerycrud.com/docs/unset-add
This example demonstrates how to set up a table and subject, then disable the 'Add' operation entirely.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->unsetAdd();
$output = $crud->render();
```
--------------------------------
### Set Language Path and Language
Source: https://www.grocerycrud.com/docs/set-language-path
This example demonstrates setting both the language folder path and the specific language to be used.
```php
$crud->setLanguagePath('application/language/grocery-crud');
$crud->setLanguage('Greek');
```
--------------------------------
### Full Example: Setting Up Clone Functionality
Source: https://www.grocerycrud.com/docs/clone-fields
This example demonstrates how to enable and configure the cloning feature in GroceryCRUD. It sets the table, subject, enables cloning, and specifies the fields to be included in the clone form using cloneFields.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->setClone();
$crud->cloneFields(['customerName','phone','addressLine1','creditLimit']);
$output = $crud->render();
```
--------------------------------
### Customizing Action Button Translations
Source: https://www.grocerycrud.com/docs/set-lang-string
This example demonstrates how to change the text for action buttons like 'delete' and 'print' using setLangString. It also shows the initial setup of the table and subject.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->setLangString('action_delete', 'Destroy!');
$crud->setLangString('print', 'Send to print');
$output = $crud->render();
```
--------------------------------
### Full Example: Disable Delete Operation
Source: https://www.grocerycrud.com/docs/unset-delete
This example demonstrates how to set up a table, subject, columns, and then disable the delete operation using unsetDelete().
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->unsetDelete();
$output = $crud->render();
```
--------------------------------
### Example composer.json with Grocery CRUD Repository
Source: https://www.grocerycrud.com/docs/grocery-crud-enterprise-laravel-installation
This is an example of a composer.json file after adding the Grocery CRUD Enterprise repository. It includes the necessary configuration under the 'repositories' key.
```json
{
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": [
"laravel",
"framework"
],
"license": "MIT",
"require": {
"php": "^8.2",
"laravel/framework": "^11.0",
"laravel/tinker": "^2.9"
},
"require-dev": {
"fakerphp/faker": "^1.23",
"laravel/pint": "^1.13",
"laravel/sail": "^1.26",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.0",
"phpunit/phpunit": "^10.5",
"spatie/laravel-ignition": "^2.4"
},
"autoload": {
"psr-4": {
"App\": "app/",
"Database\Factories\": "database/factories/",
"Database\Seeders\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\": "tests/"
}
},
"scripts": {
"post-autoload-dump": [
"Illuminate\Foundation\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force",
"@php artisan vendor:publish --provider=\"GroceryCrud\\LaravelAssetsServiceProvider\""
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi",
"@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"",
"@php artisan migrate --graceful --ansi"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true,
"repositories": {
"grocery-crud": {
"type": "composer",
"url": "https://composer.grocerycrud.com/"
}
}
}
```
--------------------------------
### Full Example of setRead() Usage
Source: https://www.grocerycrud.com/docs/set-read
This example demonstrates how to set up a table, subject, columns, and then enable the read-only view using setRead(). The output shows the 'View' button integrated into the grid actions.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->setRead();
$output = $crud->render();
```
--------------------------------
### Full Example: Linkable Customer Name
Source: https://www.grocerycrud.com/docs/callback-column
A complete example demonstrating how to make the 'customerName' column a clickable link to a customer profile page, ensuring the search functionality remains unaffected.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->callbackColumn('customerName', function ($value, $row) {
if (!empty($value)) {
return "$value";
} else {
// Make sure that you return white space or else the cell may break on print layout
return ' ';
}
});
$output = $crud->render();
```
--------------------------------
### Full Example: Setting Table and Unsetting Fields
Source: https://www.grocerycrud.com/docs/unset-add-fields
This example demonstrates setting the table, subject, read permissions, and then using unsetAddFields to exclude 'salesRepEmployeeNumber' and 'creditLimit' from the add customer form.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->setRead();
$crud->unsetAddFields(['salesRepEmployeeNumber','creditLimit']);
$output = $crud->render();
```
--------------------------------
### Configuring GroceryCRUD Settings (v3)
Source: https://www.grocerycrud.com/docs/migrating-from-v2-to-v3
Example of passing settings as the second parameter to `groceryCrudLoader` in v3.
```javascript
// code now
groceryCrudLoader(document.querySelectorAll(".grocery-crud")[0], {
callbackBeforeInsert: function () {
console.log('callback that is called right before the insert');
}
});
```
--------------------------------
### Full Example Controller for Grocery CRUD Enterprise
Source: https://www.grocerycrud.com/docs/grocery-crud-enterprise-codeigniter-4
A complete controller example demonstrating the integration of Grocery CRUD Enterprise, including index, customer management, output rendering, and helper methods.
```php
[],
'output' => ''
];
return $this->_example_output($output);
}
public function customers()
{
$crud = $this->_getGroceryCrudEnterprise();
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$output = $crud->render();
return $this->_example_output($output);
}
private function _example_output($output = null) {
if (isset($output->isJSONResponse) && $output->isJSONResponse) {
header('Content-Type: application/json; charset=utf-8');
echo $output->output;
exit;
}
return view('example.php', (array)$output);
}
private function _getDbData() {
$db = (new \Config\Database())->default;
return [
'adapter' => [
'driver' => 'Pdo_Mysql',
'host' => $db['hostname'],
'database' => $db['database'],
'username' => $db['username'],
'password' => $db['password'],
'charset' => 'utf8'
]
];
}
private function _getGroceryCrudEnterprise($bootstrap = true, $jquery = true) {
$db = $this->_getDbData();
$config = (new \Config\GroceryCrudEnterprise())->getDefaultConfig();
$groceryCrud = new GroceryCrud($config, $db);
$groceryCrud->setCsrfTokenName(csrf_token());
$groceryCrud->setCsrfTokenValue(csrf_hash());
return $groceryCrud;
}
}
```
--------------------------------
### Full Example: Unsetting Fields in GroceryCRUD
Source: https://www.grocerycrud.com/docs/unset-fields
A complete example demonstrating how to set the table, subject, and unset specific fields ('salesRepEmployeeNumber', 'creditLimit') before rendering the output.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->unsetFields(['salesRepEmployeeNumber','creditLimit']);
$output = $crud->render();
```
--------------------------------
### Full Example: Employee and Address 1-to-1 Relation
Source: https://www.grocerycrud.com/docs/set-relation-1-to-1
A complete example demonstrating how to set up a one-to-one relationship between an 'employees' table and an 'employees_addresses' table using setRelation1to1. This includes setting up fields, columns, and grouping.
```php
$crud->setSubject('Employee', 'Employees');
$crud->setTable('employees');
$crud->setRelation1to1('address_id', 'employees_addresses', [
'address_line_1','city','address_line_2','postal_code','country'
]);
$crud->fields([
'lastName', 'firstName', 'extension',
'country', 'city', 'address_line_1', 'address_line_2', 'postal_code',
'email', 'officeCode',
'file_url', 'jobTitle'
]);
$crud->columns([
'employeeNumber', 'lastName', 'firstName', 'extension',
'country', 'city', 'address_line_1', 'address_line_2', 'postal_code',
'email', 'officeCode',
'file_url', 'jobTitle'
]);
$crud->setClone();
$crud->groupFields('Basic Information', ['employeeNumber', 'lastName', 'firstName', 'extension', 'email', 'officeCode', 'jobTitle', 'file_url']);
$crud->groupFields('Address', ['country', 'city', 'address_line_1', 'address_line_2', 'postal_code']);
$crud->setRelation('country', 'countries', 'nicename');
$output = $crud->render();
```
--------------------------------
### Full Example: Disable Edit Operation
Source: https://www.grocerycrud.com/docs/unset-edit
This example demonstrates how to set up a table, subject, columns, and then disable the edit operation using unsetEdit().
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->unsetEdit();
$output = $crud->render();
```
--------------------------------
### Full Example: Disable Multiple Delete
Source: https://www.grocerycrud.com/docs/unset-delete-multiple
This example demonstrates how to set up a table, define columns, and then disable the multiple delete functionality. The user interface will no longer show options for batch deletion.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->unsetDeleteMultiple();
$output = $crud->render();
```
--------------------------------
### Full Example of Inline Editable Fields
Source: https://www.grocerycrud.com/docs/inline-edit-fields
This example demonstrates setting up a table, defining columns, and enabling inline editing for specific fields. After rendering, double-clicking these fields will make them editable.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->fieldType('creditLimit', 'numeric');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->inlineEditFields(['customerName','phone','addressLine1','creditLimit']);
$output = $crud->render();
```
--------------------------------
### Full Example: Grouping Fields for Customer Form
Source: https://www.grocerycrud.com/docs/group-fields
This example demonstrates setting up a customer table and grouping fields into 'Personal Info', 'Address', and 'Other' tabs for the add/edit/read forms. Fields not included in these groups will be omitted from the form.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->setRead();
$crud->groupFields([
'Personal Info' => ['customerName', 'contactLastName', 'contactFirstName'],
'Address' => ['addressLine1', 'addressLine2', 'city', 'state', 'postalCode', 'country'],
'Other' => ['salesRepEmployeeNumber', 'creditLimit']
]);
$output = $crud->render();
```
--------------------------------
### Full Example: Custom File Upload with Grocery CRUD Upload Library
Source: https://www.grocerycrud.com/docs/callback-upload
This comprehensive example demonstrates how to fully replace the default upload functionality using the Grocery CRUD Upload library. It includes validation, uploading, error handling, and returning the correct structure for successful uploads.
```php
// At this example we are using the Grocery CRUD Upload library.
// However, you can replace it with any other library you wish!
// Just make sure that you are returning the correct values as the below example.
$crud->callbackUpload(function ($uploadData) {
$uploadPath = $uploadData->uploadPath;
$fieldName = $uploadData->uploadFieldName;
$allowedFileTypes = $uploadData->allowedFileTypes;
$maxUploadSize = $uploadData->maxUploadSize;
$minUploadSize = $uploadData->minUploadSize;
$uploader = new GroceryCrudCoreUploadUpload($fieldName, $uploadPath);
$uploader->setValidationAllowedExtensions($allowedFileTypes);
$uploader->setValidationMaxUploadSize($maxUploadSize);
$uploader->setValidationMinUploadSize($minUploadSize);
if ($uploader->validate() === true) {
$uploader->upload();
} else {
$errors = "- " . implode("\n -", $uploader->getValidationErrors());
return (new GroceryCrudCoreErrorErrorMessage())->setMessage("There were some validation errors with the upload:\n" . $errors);
}
$uploadResult = $uploader->getUploadedFiles()->getFirstUploadedFile();
return (object)[
'uploadResult' => $uploadResult,
'stateParameters' => $uploadData
];
});
```
--------------------------------
### Example: Force 'In Process' Status on Order Insert
Source: https://www.grocerycrud.com/docs/callback-before-insert
This example demonstrates how to automatically set the 'status' field to 'In Process' for all new orders using callbackBeforeInsert.
```php
$crud->setTable('orders');
$crud->setSubject('Order', 'Orders');
$crud->unsetAddFields(['status']);
$crud->setRelation('customerNumber','customers','contactLastName');
$crud->callbackBeforeInsert(function ($stateParameters) {
$stateParameters->data['status'] = 'In Process';
return $stateParameters;
});
$output = $crud->render();
```
--------------------------------
### Full Example: Soft Delete with callbackDelete
Source: https://www.grocerycrud.com/docs/callback-delete
This example demonstrates skipping the default delete and implementing a soft delete by appending '[DELETED]' to the employee's last name. It also unsets the multiple delete functionality.
```php
$crud->setTable('employees');
$crud->setSubject('Employee', 'Employees');
$crud->setRelation('officeCode','offices','city');
$crud->displayAs('officeCode','City');
// Unsetting the multiple delete for this example. If we need it we also need to
// consider to add a $crud->callbackDeleteMultiple callback
$crud->unsetDeleteMultiple();
$crud->callbackDelete(function ($stateParameters) use ($callbackDeleteModel) {
$callbackDeleteModel->deleteEmployee($stateParameters->primaryKeyValue);
return $stateParameters;
});
$output = $crud->render();
```
--------------------------------
### Example: Skipping Delete and Custom Logic with callbackAfterDelete
Source: https://www.grocerycrud.com/docs/callback-after-delete
This example demonstrates how to use callbackAfterDelete in conjunction with callbackDelete to skip the actual deletion and perform custom logic. It also shows how to unset multiple delete functionality and use a custom model for operations.
```php
$crud->setTable('employees');
$crud->setSubject('Employee', 'Employees');
$crud->setRelation('officeCode','offices','city');
$crud->displayAs('officeCode','City');
// Unsetting the multiple delete for this example. If we need it we also need to
// consider to add a $crud->callbackDeleteMultiple callback as well
$crud->unsetDeleteMultiple();
$crud->callbackDelete(function ($stateParameters) {
// Making sure that we skip the delete functionality first!
return $stateParameters;
});
$crud->callbackAfterDelete(function ($stateParameters) use ($callbackDeleteModel) {
$callbackDeleteModel->deleteEmployee($stateParameters->primaryKeyValue);
return $stateParameters;
});
$output = $crud->render();
```
--------------------------------
### Full Example: Unsetting jQueryUI
Source: https://www.grocerycrud.com/docs/unset-jquery-ui
This example demonstrates how to set up a table, disable add functionality, and then unset jQueryUI before rendering. Ensure your template provides jQueryUI assets if you use this.
```php
$crud->setTable('orders');
$crud->setSubject('Order', 'Orders');
$crud->unsetAdd();
$crud->unsetJqueryUi();
$output = $crud->render();
```
--------------------------------
### Install Grocery CRUD Enterprise via Composer
Source: https://www.grocerycrud.com/docs/grocery-crud-enterprise-laravel-installation
Use this command to install the Grocery CRUD Enterprise package. You will be prompted for your username (email) and password (license key) on the first run.
```bash
composer require "grocery-crud/enterprise:^3.1" --prefer-dist
```
--------------------------------
### Full Example: Enabling Edit After Disabling All Operations
Source: https://www.grocerycrud.com/docs/set-edit
This example demonstrates how to disable all operations and then re-enable only the edit functionality using setEdit(). It's useful for granular control over user permissions.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
// Unsetting all the buttons to see the result of the set function
$crud->unsetExport();
$crud->unsetPrint();
$crud->unsetOperations();
$crud->setEdit();
$output = $crud->render();
```
--------------------------------
### Example: Using setModel() with Custom Query Logic
Source: https://www.grocerycrud.com/docs/set-model
This example demonstrates how to set a custom model and configure the CRUD instance. The custom model 'customModel' filters customers to only include those from 'USA'.
```php
$crud->setModel(new customModel($db));
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName', 'country', 'state', 'addressLine1']);
$output = $crud->render();
```
--------------------------------
### Example: Unsetting Columns in GroceryCRUD
Source: https://www.grocerycrud.com/docs/unset-columns
This example demonstrates setting a table, subject, and then unsetting specific columns before rendering the output. Notice that 'salesRepEmployeeNumber' and 'creditLimit' are hidden in the datagrid but available in forms.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->unsetColumns(['salesRepEmployeeNumber','creditLimit']);
$output = $crud->render();
```
--------------------------------
### Full Example with Custom Model and Validation
Source: https://www.grocerycrud.com/docs/callback-delete-multiple
This example demonstrates a comprehensive implementation of callbackDeleteMultiple, including setting up the table, subject, relations, and a custom delete callback. It also includes validation for the number of records to delete and uses a custom model for deletion logic.
```php
$crud->setTable('employees');
$crud->setSubject('Employee', 'Employees');
$crud->setRelation('officeCode','offices','city');
$crud->displayAs('officeCode','City');
$crud->callbackDelete(function ($stateParameters) use ($callbackDeleteModel) {
$callbackDeleteModel->deleteEmployee($stateParameters->primaryKeyValue);
return $stateParameters;
});
$crud->callbackDeleteMultiple(function ($stateParameters) use ($callbackDeleteModel) {
$primaryKeys = [];
foreach ($stateParameters->primaryKeys as $primaryKey) {
// For security reasons check if the primary key is numeric
if (is_numeric($primaryKey)) {
$primaryKeys[] = $primaryKey;
}
}
if (count($primaryKeys) > 10) {
// Custom error messages are only available on Grocery CRUD Enterprise
$errorMessage = new
GroceryCrud
Core
Error
ErrorMessage();
return $errorMessage->setMessage("For demo purposes you can only delete maximum 10 employees at a time\n");
}
if (!empty($primaryKeys)) {
$callbackDeleteModel->deleteMultipleEmployees($primaryKeys);
} else {
return false;
}
return $stateParameters;
});
$output = $crud->render();
```
--------------------------------
### Modified Grocery CRUD Enterprise Setup for Films (films.php)
Source: https://www.grocerycrud.com/docs/grocery-crud-enterprise-installation
This script is a modified version of the basic setup, tailored for managing 'films' data. It updates the include paths, sets the table to 'films', and changes the subject to 'Film'/'Films'. This is useful for creating a specific CRUD interface for a different table.
```php
setTable('films'); // And of course our specific CRUD
$crud->setSubject('Film', 'Films'); // And of course our specific CRUD
$output = $crud->render();
if ($output->isJSONResponse) {
header('Content-Type: application/json; charset=utf-8');
echo $output->output;
exit;
}
$js_files = $output->js_files;
$output = $output->output;
// The below include is not required. If you have another way to show:
// a. the output
// b. the CSS and JS files
// Then you can basically include the results of the output and the CSS/JS files to your own framework's output or template
include('view.php');
```
--------------------------------
### Full Example with Custom Model
Source: https://www.grocerycrud.com/docs/callback-insert
This example shows a complete implementation of callbackInsert, including setting up the table, subject, relations, and required fields. It customizes the 'comments' field by prepending the current date and uses a custom model (`$callbackInsertModel`) to perform the actual database insert.
```php
$crud->setTable('orders');
$crud->setSubject('Order', 'Orders');
$crud->setRelation('customerNumber','customers','contactLastName');
$crud->requiredFields(['orderDate', 'requiredDate', 'shippedDate', 'status', 'customerNumber']);
$crud->callbackInsert(function ($stateParameters) use ($callbackInsertModel) {
$stateParameters->data['comments'] = '[Insert date - ' .date('d M Y') . '] '. $stateParameters->data['comments'];
// As we are skipping the actual insert we will need to insert by our own
$insertId = $callbackInsertModel->insertOrder($stateParameters->data);
// Required
$stateParameters->insertId = $insertId;
return $stateParameters;
});
$output = $crud->render();
```
--------------------------------
### Example: Standalone Form with No 'Back to List'
Source: https://www.grocerycrud.com/docs/unset-back-to-list
This example demonstrates how to use unsetBackToList() in a typical GroceryCRUD setup. The resulting modal forms will not have 'Back To List' buttons.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
// Although there is no point to have that without the unsetList
// This is an example of how unsetBackToList will look like.
$crud->unsetBackToList();
$output = $crud->render();
```
--------------------------------
### Set Theme Example
Source: https://www.grocerycrud.com/docs/set-theme
This snippet demonstrates how to set the 'bootstrap-v4' theme for Grocery CRUD and configure basic table settings.
```php
$crud->setTheme('bootstrap-v4');
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
```
--------------------------------
### Full Example: unsetJquery with GroceryCRUD Configuration
Source: https://www.grocerycrud.com/docs/unset-jquery
This example demonstrates how to configure GroceryCRUD to not load jQuery, set the table and subject, define columns, and then render the output. It's useful for integrating GroceryCRUD into existing projects that manage their own jQuery.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
$crud->unsetJquery();
$output = $crud->render();
```
--------------------------------
### Basic Action Button Setup in GroceryCRUD
Source: https://www.grocerycrud.com/docs/set-action-button
This snippet demonstrates a full GroceryCRUD setup including the use of setActionButton to add an 'Avatar' button. The button's URL is dynamically generated based on the row data.
```php
$crud->setTable('employees');
$crud->setSubject('Employee', 'Employees');
$crud->setRelation('officeCode','offices','city');
$crud->displayAs('officeCode','City');
$crud->unsetDelete();
$crud->setActionButton('Avatar', 'fa fa-user', function ($row) {
return '#/avatar/' . $row->employeeNumber;
});
```
--------------------------------
### Full Example: Enabling Only Delete Operation
Source: https://www.grocerycrud.com/docs/set-delete
This example disables all operations and then explicitly enables only the delete functionality using setDelete(). It's useful for understanding the method's impact when starting with a clean slate.
```php
$crud->setTable('customers');
$crud->setSubject('Customer', 'Customers');
$crud->columns(['customerName','phone','addressLine1','creditLimit']);
// Unsetting all the buttons to see the result of the set function
$crud->unsetExport();
$crud->unsetPrint();
$crud->unsetOperations();
$crud->setDelete();
$output = $crud->render();
```