### Backbone.js Collection Initialization Examples Source: https://backbonejs.org/ Demonstrates various ways to initialize a Backbone.js Collection, including providing initial models, specifying a model type, and setting options like a comparator. It also shows how to define preinitialize and initialize methods for custom setup logic. ```javascript var library = new Library([ {type: 'dvd', id: 1}, {type: 'vhs', id: 1} ]); var dvdId = library.get('dvd1').id; var vhsId = library.get('vhs1').id; alert('dvd: ' + dvdId + ', vhs: ' + vhsId); ``` ```javascript class Library extends Backbone.Collection { preinitialize() { this.on("add", function() { console.log("Add model event got fired!"); }); } } ``` ```javascript var tabs = new TabSet([tab1, tab2, tab3]); var spaces = new Backbone.Collection(null, { model: Space }); ``` -------------------------------- ### Install Bootstrap via npm Source: https://getbootstrap.com/ Installs Bootstrap version 5.3.8 using the npm package manager. This command fetches the necessary files for use in a project. ```bash npm install bootstrap@5.3.8 ``` -------------------------------- ### Start Backbone History Management Source: https://backbonejs.org/ Explains how to start Backbone.history to enable routing based on hash changes or pushState. It covers options for enabling pushState, disabling hashChange, specifying a root directory, and handling trailing slashes. ```javascript Backbone.history.start(); // Or with pushState enabled: Backbone.history.start({pushState: true}); // Or with pushState and without hashChange: Backbone.history.start({pushState: true, hashChange: false}); // Or with pushState and a custom root: Backbone.history.start({pushState: true, root: "/public/search/"}); // Or with pushState and preserving trailing slashes: Backbone.history.start({pushState: true, trailingSlash: true}); ``` -------------------------------- ### Install Custom Module via Loadable Package (PHP) Source: https://context7_llms This PHP code illustrates how to define module installation parameters within a manifest file for a SugarCRM loadable package. It uses the `$installdefs` array to specify beans to be installed, including module name, class, path, and tab visibility, along with file copy instructions. ```php 'Beans_Example', 'beans' => array( array( 'module' => 'cust_Module', 'class' => 'cust_Module', 'path' => 'modules/cust_Module/cust_Module.php', 'tab' => true ) ), 'copy' => array( array( 'from' => '/Files/modules/cust_Module', 'to' => 'modules/cust_Module' ) ) ); ?> ``` -------------------------------- ### Install Bootstrap via RubyGems Source: https://getbootstrap.com/ Installs Bootstrap version 5.3.8 using the RubyGems package manager. This is an alternative method for projects using Ruby. ```ruby gem install bootstrap -v 5.3.8 ``` -------------------------------- ### Backbone Model Fetch Method Example Source: https://backbonejs.org/ Illustrates how to use the `fetch` method on a Backbone Model to update its state from the server. The example shows a recurring fetch operation to keep a model synchronized with server data. ```javascript // Poll every 10 seconds to keep the channel model up-to-date. setInterval(function() { channel.fetch(); }, 10000); ``` -------------------------------- ### Backbone.js Module Loading Examples Source: https://backbonejs.org/ Demonstrates how to load Backbone.js debug info using different module formats: browser embeds (script tags), CommonJS, and ECMAScript Modules (ESM). ```html ``` ```javascript // CommonJS require('backbone/debug-info.js')(); // ESM import debugInfo from 'backbone/modules/debug-info.js'; debugInfo(); ``` -------------------------------- ### Model Initialization with preinitialize (JavaScript) Source: https://backbonejs.org/ Demonstrates how to use the `preinitialize` method in a Backbone.js Model. This method is called before any instantiation logic runs, allowing for early setup based on initial options. ```javascript class Country extends Backbone.Model { preinitialize({countryCode}) { this.name = COUNTRY_NAMES[countryCode]; } initialize() { // ... } } ``` -------------------------------- ### Backbone.js Router Pre-initialization Source: https://backbonejs.org/ Shows how to use the `preinitialize` method for Backbone.js Routers when using ES classes. This method is called before any instantiation logic, allowing for early setup like overriding the `execute` method. ```javascript class Router extends Backbone.Router { preinitialize() { // Override execute method this.execute = function(callback, args, name) { if (!loggedIn) { goToLogin(); return false; } args.push(parseQueryString(args.pop())) } } } ``` -------------------------------- ### SugarQuery Prepared Statement Example (SQL) Source: https://context7_llms Illustrates the SQL prepared statement generated by SugarQuery after executing the PHP code for joining accounts and contacts. This shows how SugarQuery constructs the necessary JOIN clauses and WHERE conditions. ```sql SELECT jt0_contacts.salutation rel_full_name_salutation, jt0_contacts.first_name rel_full_name_first_name, jt0_contacts.last_name rel_full_name_last_name FROM accounts INNER JOIN accounts_contacts jt1_accounts_contacts ON (accounts.id = jt1_accounts_contacts.account_id) AND (jt1_accounts_contacts.deleted = ?) INNER JOIN contacts jt0_contacts ON (jt0_contacts.id = jt1_accounts_contacts.contact_id) AND (jt0_contacts.deleted = ?) WHERE (accounts.industry = ?) AND (accounts.deleted = ?) ``` -------------------------------- ### Backbone.js Collection Underscore Methods Examples Source: https://backbonejs.org/ Showcases the usage of several Underscore.js methods proxied by Backbone.js Collections for data manipulation and iteration. Examples include `each`, `map`, `filter`, `sortBy`, and `sample` for processing collections of models. ```javascript books.each(function(book) { book.publish(); }); var titles = books.map("title"); var publishedBooks = books.filter({published: true}); var alphabetical = books.sortBy(function(book) { return book.author.get("name").toLowerCase(); }); var randomThree = books.sample(3); ``` -------------------------------- ### Backbone Model toJSON Method Example Source: https://backbonejs.org/ Demonstrates the use of the `toJSON` method on a Backbone Model to get a shallow copy of its attributes, suitable for JSON stringification. This is useful for data persistence and serialization. ```javascript var artist = new Backbone.Model({ firstName: "Wassily", lastName: "Kandinsky" }); artist.set({birthday: "December 16, 1866"}); alert(JSON.stringify(artist)); ``` -------------------------------- ### Bootstrap JavaScript Plugins: Data Attribute API Example Source: https://getbootstrap.com/ Illustrates the use of Bootstrap's Data Attribute API for JavaScript plugins. This approach allows developers to enable plugin functionality simply by adding `data` attributes to HTML elements, reducing the need for custom JavaScript code. An example of a dropdown menu is provided. ```html ``` -------------------------------- ### Backbone Model Save Method Example (Wait) Source: https://backbonejs.org/ Shows how to use the `save` method with the `wait: true` option to ensure that model attributes are updated on the client only after the server has successfully acknowledged the change. ```javascript model.save(attrs, {"wait": true}); ``` -------------------------------- ### Backbone Model Defaults Example Source: https://backbonejs.org/ Shows how to define default attributes for a Backbone Model using the `defaults` property. It demonstrates accessing a default attribute and highlights the importance of using a function for defaults when dealing with object references. ```javascript var Meal = Backbone.Model.extend({ defaults: { "appetizer": "caesar salad", "entree": "ravioli", "dessert": "cheesecake" } }); alert("Dessert will be " + (new Meal).get('dessert')); ``` -------------------------------- ### Backbone Model Save Method Example (Patch) Source: https://backbonejs.org/ Demonstrates how to use the `save` method with the `patch: true` option to send only the changed attributes to the server, resulting in an HTTP PATCH request. ```javascript model.save(attrs, {"patch": true}); ``` -------------------------------- ### Utilize Underscore.js Methods on Backbone Models Source: https://backbonejs.org/ Demonstrates the use of Underscore.js utility functions proxied onto Backbone.Model instances. Examples include `pick` for selecting attributes and `keys` for retrieving model keys. ```javascript user.pick('first_name', 'last_name', 'email'); chapters.keys().join(', '); ``` -------------------------------- ### Backbone.js Collection Add Method Example Source: https://backbonejs.org/ Demonstrates how to add models to a Backbone.js Collection using the `add` method. It also shows how to listen for the 'add' event, which fires for each model added, and the 'update' event, which fires after all additions are complete. ```javascript var ships = new Backbone.Collection; ships.on("add", function(ship) { alert("Ahoy " + ship.get("name") + "!"); }); ships.add([ {name: "Flying Dutchman"}, {name: "Black Pearl"} ]); ``` -------------------------------- ### Getting Model Attributes (JavaScript) Source: https://backbonejs.org/ Demonstrates the `get` method for retrieving the current value of an attribute from a Backbone.js Model. ```javascript note.get("title"); ``` -------------------------------- ### Handle Button Clicks to Show Hidden Elements with jQuery Source: https://jquery.com/ This example shows how to attach an event listener to buttons within a specific container. When a button is clicked, it makes a previously hidden element visible. This is commonly used for interactive UI components. ```javascript var hiddenBox = $( "#banner-message" ); $( "#button-container button" ).on( "click", function( event ) { hiddenBox.show(); }); ``` -------------------------------- ### Aggregate and Join SugarQuery Output Source: https://context7_llms Presents the SQL output generated by SugarQuery for aggregate and join operations. The first example shows the SQL for counting records grouped by name, including the `WHERE` clause for deleted records. The second example shows the SQL for joining Accounts and Contacts, including conditions for both tables and deleted status. ```sql SELECT accounts.name, COUNT(0) AS record_count FROM accounts WHERE accounts.deleted = ? GROUP BY accounts.name, accounts.name ``` ```sql SELECT jt0_contacts.salutation rel_full_name_salutation, jt0_contacts.first_name rel_full_name_first_name, jt0_contacts.last_name rel_full_name_last_name FROM accounts INNER JOIN accounts_contacts jt1_accounts_contacts ON (accounts.id = jt1_accounts_contacts.account_id) AND (jt1_accounts_contacts.deleted = ?) INNER JOIN contacts jt0_contacts ON (jt0_contacts.id = jt1_accounts_contacts.contact_id) AND (jt0_contacts.deleted = ?) WHERE (accounts.industry = ?) AND (accounts.deleted = ?) ``` -------------------------------- ### Example Response for Duplicate Check API (JSON) Source: https://context7_llms An example of the JSON response received from the SugarCRM REST API's duplicate check endpoint. It lists records that match the criteria, including their IDs, names, and timestamps. The 'next_offset' indicates if there are more results. ```json { "next_offset": -1, "records": [{ "id": "7f6ea7be-60d6-11e6-8885-a0999b033b33", "name": "Test Record", "date_entered": "2016-08-12T14:48:25-07:00", "date_modified": "2016-08-12T14:48:25-07:00", "modified_user_id": "1", "modified_by_name": "Administrator", "created_by": "1", "created_by_name": "Administrator", "description": "Test Data 1", "deleted": false }] } ``` -------------------------------- ### Backbone.js View with Preinitialize for ES Classes Source: https://backbonejs.org/ Illustrates using the `preinitialize` method for Backbone.js views defined as ES6 classes. The `preinitialize` method is executed before the view's instantiation logic, allowing for early setup like setting properties based on constructor options. The `initialize` method can then conditionally set up event listeners. ```javascript class Document extends Backbone.View { preinitialize({autoRender}) { this.autoRender = autoRender; } initialize() { if (this.autoRender) { this.listenTo(this.model, "change", this.render); } } } ``` -------------------------------- ### Model Save with Callbacks and Error Handling Source: https://backbonejs.org/ Illustrates using the `save` method with optional `success` and `error` callbacks. The example shows how to handle server-side validation failures by returning a non-200 HTTP response code and an error message. ```javascript book.save("author", "F.D.R.", {error: function(){ ... }}); ``` -------------------------------- ### Get Debug Information about Backbone and Dependencies (JavaScript) Source: https://backbonejs.org/ The `debugInfo()` function, available in later versions of Backbone.js, prints detailed version information about Backbone and its dependencies to the console. It also returns this information as a JSON object for programmatic inspection. ```javascript debugInfo(); ``` -------------------------------- ### Set Custom jQuery Instance for Backbone (JavaScript) Source: https://backbonejs.org/ This example demonstrates how to assign a specific jQuery object to `Backbone.$`. This allows Backbone to use a particular jQuery instance, which is helpful if multiple jQuery versions are present or when using module loaders. ```javascript Backbone.$ = require('jquery'); ``` -------------------------------- ### Define Backbone View with Event Handling (JavaScript) Source: https://backbonejs.org/ This snippet demonstrates how to define a Backbone View with event handling using the `events` hash. It includes an example of listening for a 'keydown' event and adding data to a collection when the ENTER key is pressed. ```javascript var ENTER_KEY = 13; var InputView = Backbone.View.extend({ tagName: 'input', events: { "keydown" : "keyAction", }, render: function() { // ... }, keyAction: function(e) { if (e.which === ENTER_KEY) { this.collection.add({text: this.$el.val()}); } } }); ``` -------------------------------- ### Custom Backbone sync method for Internal API Source: https://backbonejs.org/ This example shows a custom `sync` method implementation for Backbone models and collections. It's designed to fetch news stories from an internal API, demonstrating how to override default synchronization behavior to interact with specific backend endpoints. ```javascript var SpinNews = Backbone.Collection.extend({ url: '/api/internal/news', model: Backbone.Model, sync: function(method, model, options) { if (method === 'read') { // Custom logic to fetch data from the internal API $.ajax({ url: this.url, type: 'GET', dataType: 'json', success: function(response) { options.success(response); }, error: function(jqXHR, textStatus, errorThrown) { options.error(null, textStatus, errorThrown); } }); } else { // Fallback to default sync for other methods if needed Backbone.sync(method, model, options); } } }); ``` -------------------------------- ### Backbone View with Multiple Event Bindings (JavaScript) Source: https://backbonejs.org/ This example showcases a Backbone View with multiple DOM events bound to different methods using the `events` hash. It illustrates common event types like 'dblclick', 'click', 'contextmenu', and 'mouseover'. ```javascript var DocumentView = Backbone.View.extend({ events: { "dblclick" : "open", "click .icon.doc" : "select", "contextmenu .icon.doc" : "showMenu", "click .show_notes" : "toggleNotes", "click .title .lock" : "editAccessLevel", "mouseover .title .date" : "showTooltip" }, render: function() { this.$el.html(this.template(this.model.attributes)); return this; }, open: function() { window.open(this.model.get("viewer_url")); }, select: function() { this.model.set({selected: true}); }, // ... other event handlers }); ``` -------------------------------- ### Extend Backbone.js Collections with Mixins Source: https://backbonejs.org/ Illustrates how to add custom methods to Backbone.js Collections using `Backbone.Collection.mixin`. This example adds a `sum` method to calculate the sum of a property across all models in the collection. ```javascript Backbone.Collection.mixin({ sum: function(models, iteratee) { return _.reduce(models, function(s, m) { return s + iteratee(m); }, 0); } }); var cart = new Backbone.Collection([ {price: 16, name: 'monopoly'}, {price: 5, name: 'deck of cards'}, {price: 20, name: 'chess'} ]); var cost = cart.sum('price'); ``` -------------------------------- ### Backbone.Events: Unbinding Callbacks ('off') Source: https://backbonejs.org/ Provides examples of how to remove event bindings using the 'off' method. It covers removing specific callbacks, all callbacks for an event, or all callbacks for all events, optionally with a context. ```javascript // Removes just the `onChange` callback. object.off("change", onChange); // Removes all "change" callbacks. object.off("change"); // Removes the `onChange` callback for all events. object.off(null, onChange); // Removes all callbacks for `context` for all events. object.off(null, null, context); // Removes all callbacks on `object`. object.off(); ``` -------------------------------- ### Retrieve Model by ID Source: https://backbonejs.org/ The `get` method retrieves a specific model from a Backbone.js collection using its ID, CID, or by passing a model object directly. ```javascript var book = library.get(110); ``` -------------------------------- ### Backbone.js Model Method Override with Super Call Source: https://backbonejs.org/ Provides an example of how to override a core Backbone.Model method, specifically 'set', and invoke the parent's implementation. This pattern is necessary in JavaScript when you need to extend existing functionality while retaining the original behavior. ```javascript var Note = Backbone.Model.extend({ set: function(attributes, options) { Backbone.Model.prototype.set.apply(this, arguments); } }); ``` -------------------------------- ### Backbone.js Collection toJSON and JSON.stringify Example Source: https://backbonejs.org/ Illustrates how to convert a Backbone.js Collection into a JSON string. The `toJSON` method on the collection serializes each model's attributes, and `JSON.stringify` converts the resulting array into a JSON string for persistence or transmission. ```javascript var collection = new Backbone.Collection([ {name: "Tim", age: 5}, {name: "Ida", age: 26}, {name: "Rob", age: 55} ]); alert(JSON.stringify(collection)); ``` -------------------------------- ### Manipulate HTML with jQuery Source: https://jquery.com/ This snippet demonstrates how to select an HTML element with a specific class and modify its content using jQuery's .html() method. It's a fundamental operation for dynamic web content. ```javascript $"button.continue" ).html( "Next Step..." ) ``` -------------------------------- ### Perform AJAX Request with jQuery Source: https://jquery.com/ This code snippet illustrates how to make an asynchronous HTTP (AJAX) request to a server endpoint. It sends data and updates a specific HTML element with the response. This is crucial for fetching data without page reloads. ```javascript $.ajax({ url: "/api/getWeather", data: { zipcode: 97201 }, success: function( result ) { $( "#weather-temp" ).html( "**" + result + "** degrees" ); } }); ``` -------------------------------- ### Define and Initialize a Backbone Router Source: https://backbonejs.org/ Demonstrates how to define a Backbone Router, including its constructor/initialize function and setting up routes. Routes can be defined using strings or regular expressions, with optional naming for event triggering. ```javascript var Router = Backbone.Router.extend({ initialize: function(options) { // Matches #page/10, passing "10" this.route("page/:number", "page", function(number){ // ... // }); // Matches /117-a/b/c/open, passing "117-a/b/c" to this.open this.route(/^(.*?)\/open$/, "open"); }, open: function(id) { // ... } }); ``` -------------------------------- ### Backbone.js Views: Defining Element Properties Source: https://backbonejs.org/ Demonstrates how Backbone.js views can define their root DOM element properties (`tagName`, `el`, `className`, `id`, `attributes`). If `el` is not explicitly set, the view creates its element based on `tagName`, `className`, `id`, and `attributes`. This example shows views with a specified `tagName` and `el`. ```javascript var ItemView = Backbone.View.extend({ tagName: 'li' }); var BodyView = Backbone.View.extend({ el: 'body' }); var item = new ItemView(); var body = new BodyView(); alert(item.el + ' ' + body.el); ``` -------------------------------- ### Backbone Collection Initialization and Length Source: https://backbonejs.org/ Illustrates how to initialize Backbone Collections with data and check their length. It shows the difference between standard collections and collections using a custom model that avoids ID conflicts. ```javascript var clashy = new Backbone.Collection([ {id: 'c2'}, {id: 'c1'}, ]); alert('clashy length: ' + clashy.length); var ClashFree = Backbone.Model.extend({ cidPrefix: 'm' }); var clashless = new Backbone.Collection([ {id: 'c3'}, {id: 'c2'}, ], { model: ClashFree }); alert('clashless length: ' + clashless.length); ``` -------------------------------- ### Backbone.history.start() Configuration Source: https://backbonejs.org/ Initiates Backbone's history management, enabling client-side routing. It can be configured with options like `pushState` for cleaner URLs or `silent` to prevent initial route triggering. It's crucial to call this after the DOM is ready, especially when using hash-based history in older browsers. ```javascript $(function() { new WorkspaceRouter(); new HelpPaneRouter(); Backbone.history.start({pushState: true}); }); ``` -------------------------------- ### Model Initialization with initialize (JavaScript) Source: https://backbonejs.org/ Shows how to initialize a Backbone.js Model with attributes and an `initialize` method. The `initialize` method is called after the model's attributes are set. ```javascript new Book({ title: "One Thousand and One Nights", author: "Scheherazade" }); ``` -------------------------------- ### Get Collection Length Source: https://backbonejs.org/ The `length` property returns the number of models currently contained within a Backbone.js collection, similar to arrays. ```javascript var count = collection.length; ``` -------------------------------- ### Instantiate Backbone.js View with Model and ID Source: https://backbonejs.org/ Shows how to instantiate a Backbone.js view (`DocumentRow`) and pass specific options like `model` and `id` during initialization. These options are directly attached to the view instance, allowing for data binding and unique element identification. ```javascript var doc = documents.first(); new DocumentRow({ model: doc, id: "document-row-" + doc.id }); ``` -------------------------------- ### Define Backbone.js View with Events and Lifecycle Methods Source: https://backbonejs.org/ Demonstrates creating a Backbone.js view (`DocumentRow`) by extending `Backbone.View`. It shows how to define element properties (`tagName`, `className`), declarative events, and implement `initialize` and `render` methods. The `initialize` method sets up a listener for model changes to re-render the view. ```javascript var DocumentRow = Backbone.View.extend({ tagName: "li", className: "document-row", events: { "click .icon": "open", "click .button.edit": "openEditDialog", "click .button.delete": "destroy" }, initialize: function() { this.listenTo(this.model, "change", this.render); }, render: function() { ... } }); ``` -------------------------------- ### Backbone.Events: Event Map Syntax for Binding Source: https://backbonejs.org/ Demonstrates the event map syntax for binding multiple events to different callbacks simultaneously. This provides a more concise way to set up event handlers. ```javascript book.on({ "change:author": authorPane.update, "change:title change:subtitle": titleView.update, "destroy": bookView.remove }); ``` -------------------------------- ### Backbone.js Model Basic Usage and Event Handling Source: https://backbonejs.org/ Demonstrates defining a Backbone Model with a custom method, setting an attribute, and listening for attribute changes. It sets an initial color and then prompts the user for a new color, updating the UI accordingly. This requires the jQuery library for DOM manipulation. ```javascript var Sidebar = Backbone.Model.extend({ promptColor: function() { var cssColor = prompt("Please enter a CSS color:"); this.set({color: cssColor}); } }); window.sidebar = new Sidebar; sidebar.on('change:color', function(model, color) { $('#sidebar').css({background: color}); }); sidebar.set({color: 'white'}); sidebar.promptColor(); ``` -------------------------------- ### Include All of Bootstrap's Sass Source: https://getbootstrap.com/ Demonstrates how to import all of Bootstrap's Sass files into a project. This method allows for easy customization through variable overrides and enables all Bootstrap features. It requires setting variable overrides before importing the main Bootstrap Sass file. ```scss // Variable overrides first $primary: #900; $enable-shadows: true; $prefix: "mo-"; // Then import Bootstrap @import "../node_modules/bootstrap/scss/bootstrap"; ``` -------------------------------- ### Custom Model Validation Logic Source: https://backbonejs.org/ Provides an example of overriding the `validate` method in a Backbone.Model to implement custom validation rules. It shows how to return an error message for invalid attributes and how this error is triggered during `save` or `set` operations. ```javascript var Chapter = Backbone.Model.extend({ validate: function(attrs, options) { if (attrs.end < attrs.start) { return "can't end before it starts"; } } }); var one = new Chapter({ title : "Chapter One: The Beginning" }); one.on("invalid", function(model, error) { alert(model.get("title") + " " + error); }); one.save({"start": 15, "end": 10}); ``` -------------------------------- ### Backbone.js: Loading Bootstrapped Models into Collections Source: https://backbonejs.org/ Illustrates how to efficiently load initial data into Backbone Collections when an application first loads. Instead of making separate AJAX requests, data is bootstrapped directly into the HTML, then used to populate collections via the `reset` method. This prevents extra network requests. ```javascript ``` -------------------------------- ### Load Popup Metadata via SugarAutoloader::loadPopupMeta (PHP) Source: https://context7_llms This PHP code snippet shows the usage of the `loadPopupMeta` function from the SugarCRM Autoloader. It loads popup metadata for a specified module, either using a provided metadata variable or the default 'popupdefs'. If no metadata is found, it returns an empty array. ```php $popupMetadata = SugarAutoloader::loadPopupMeta('Accounts'); ``` -------------------------------- ### Get Generated Join Name in SugarQuery (PHP) Source: https://context7_llms Demonstrates how to retrieve the auto-generated name for a join in SugarQuery using the joinName() method. This is useful for adding conditions or joining to relationships when a custom alias is not used. It requires the SugarQuery object and a Bean to be instantiated. ```php $SugarQuery = new SugarQuery(); $SugarQuery->from(BeanFactory::getBean('Accounts')); $contacts = $SugarQuery->join('contacts')->joinName(); $SugarQuery->select(array("$contacts.full_name")); $SugarQuery->where()->equals('industry', 'Media'); ``` -------------------------------- ### Backbone.js Router Route Parameter Matching Source: https://backbonejs.org/ Explains different route matching patterns in Backbone.js Routers. It covers parameter matching (`:param`), splat matching (`*splat`), optional parameters (`(/:optional)`), and handling trailing slashes. ```javascript routes: { "help/:page": "help", "download/*path": "download", "folder/:name": "openFolder", "folder/:name-:mode": "openFolder" } ``` -------------------------------- ### Register Custom Module via Filesystem (PHP) Source: https://context7_llms This code snippet demonstrates how to register a new custom module by creating a PHP file in a specific SugarCRM directory. This method is typically used for deploying custom modules. It defines module-specific variables that SugarCRM uses to recognize and load the module. ```php ``` -------------------------------- ### Model Destroy with Callbacks and Options Source: https://backbonejs.org/ Shows how to use the `destroy` method to remove a model from the server. It includes handling `success` and `error` callbacks and explains the `wait: true` option to defer client-side removal until server confirmation. ```javascript book.destroy({"success": function(model, response) { ... }}); ``` -------------------------------- ### Backbone.js API Data Population Source: https://backbonejs.org/ Demonstrates how Backbone.js automatically populates Collections and Models from JSON API responses. Collections expect an array, while Models expect an object. ```javascript [{"id": 1}] ..... populates a Collection with one model. {"id": 1} ....... populates a Model with one attribute. ``` -------------------------------- ### Backbone.View Extension Pattern Source: https://backbonejs.org/ Demonstrates the standard pattern for extending Backbone.View to create custom views. Views are designed to be flexible and can be used with any JavaScript templating library, organizing the UI around models. ```javascript Backbone.View.ext ``` -------------------------------- ### Extending Bootstrap Utility API with Custom Utilities (Sass) Source: https://getbootstrap.com/ Shows how to extend Bootstrap's Utility API using Sass. This involves importing Bootstrap's core styles and then merging a new utility, such as 'cursor', into the `$utilities` Sass map. This allows for the creation of custom utility classes with responsive variants and custom values. ```scss @import "bootstrap/scss/bootstrap"; $utilities: map-merge( $utilities, ( "cursor": ( property: cursor, class: cursor, responsive: true, values: auto pointer grab, ) ) ); ``` -------------------------------- ### Bootstrap Collection with JSON Data Source: https://backbonejs.org/ This snippet demonstrates how to initialize a Backbone.js collection by replacing its existing models with a new list, often used for bootstrapping data during initial page load. It triggers a single 'reset' event. ```javascript var accounts = new Backbone.Collection; accounts.reset(<%= @accounts.to_json %>); ``` -------------------------------- ### Load Metadata via SugarAutoloader::loadWithMetafiles (PHP) Source: https://context7_llms This PHP code snippet demonstrates how to use the SugarCRM Autoloader's `loadWithMetafiles` function. It returns the path to a specified metadata file for a given module, such as 'editviewdefs'. This function does not load the metadata content itself but provides the file path for further processing. ```php $metadataPath = SugarAutoloader::loadWithMetafiles('Accounts', 'editviewdefs'); ``` -------------------------------- ### Listen to Backbone.js Router Route Events Source: https://backbonejs.org/ Demonstrates how to listen for route events fired by a Backbone.js Router. When a route is matched, an event like `route:actionName` is triggered, allowing other parts of the application to react. ```javascript router.on("route:help", function(page) { // ... }); ``` -------------------------------- ### Retrieve First Record with SugarQuery Source: https://context7_llms Demonstrates how to retrieve the first piece of data from the first record of a SugarQuery result set using the `getOne()` method. This is useful for fetching specific fields like 'name' for a record identified by its ID. ```php $SugarQuery = new SugarQuery(); $SugarQuery->select(array('name')); $SugarQuery->from(BeanFactory::newBean('Accounts')); $SugarQuery->where()->equals('id',$id); //Get the Name of the account $accountName = $SugarQuery->getOne(); ``` -------------------------------- ### Authenticate with SugarCRM REST API (Bash) Source: https://context7_llms Provides a cURL command to authenticate with the SugarCRM REST API and obtain an OAuth2 access token. This is the first step for making authenticated API requests. It requires the site URL and user credentials. ```bash curl -X POST -H Cache-Control:no-cache -H "Content-Type: application/json" -d '{ "grant_type":"password", "client_id":"sugar", "client_secret":"", "username":"admin", "password":"password", "platform":"custom_api" }' https://{site_url}/rest/v11/oauth2/token ``` -------------------------------- ### POST /oauth2/token Source: https://context7_llms Authenticates a user and obtains an access token for subsequent API requests. ```APIDOC ## POST /oauth2/token ### Description Authenticates a user and obtains an access token for subsequent API requests. This is the first step in interacting with the Sugar REST API. ### Method POST ### Endpoint /rest/v11/oauth2/token ### Parameters #### Request Body - **grant_type** (string) - Required - The grant type for authentication, typically 'password'. - **client_id** (string) - Required - The client ID, usually 'sugar'. - **client_secret** (string) - Optional - The client secret. - **username** (string) - Required - The username for authentication. - **password** (string) - Required - The password for authentication. - **platform** (string) - Required - The platform identifier, e.g., 'custom_api'. ### Request Example ```json { "grant_type":"password", "client_id":"sugar", "client_secret":"", "username":"admin", "password":"password", "platform":"custom_api" } ``` ### Response #### Success Response (200) - **access_token** (string) - The authentication token. - **token_type** (string) - The type of token, typically 'bearer'. - **expires_in** (integer) - The time in seconds until the token expires. - **refresh_token** (string) - The refresh token for obtaining a new access token. - **refresh_expires_in** (integer) - The time in seconds until the refresh token expires. #### Response Example ```json { "access_token": "{access_token}", "token_type": "bearer", "expires_in": 3600, "refresh_token": "{refresh_token}", "refresh_expires_in": 86400 } ``` ``` -------------------------------- ### Create a Backbone.js Collection Model Source: https://backbonejs.org/ Demonstrates how to create a new model within a Backbone.js collection. The `create` method triggers 'add', 'request', and 'sync' events. Use `{wait: true}` to defer adding the model to the collection until the server responds. ```javascript var Library = Backbone.Collection.extend({ model: Book }); var nypl = new Library; var othello = nypl.create({ title: "Othello", author: "William Shakespeare" }); ``` -------------------------------- ### Define Backbone.js Router Routes Source: https://backbonejs.org/ Shows how to define routes for a Backbone.js Router. Routes map URL fragments to specific action functions. Supports parameterized routes like `:query` and splat routes like `*splat`, as well as optional parameters. ```javascript var Workspace = Backbone.Router.extend({ routes: { "help": "help", // #help "search/:query": "search", // #search/kiwis "search/:query/p:page": "search" // #search/kiwis/p7 }, help: function() { // ... }, search: function(query, page) { // ... } }); ``` -------------------------------- ### Backbone.js Model Extension for Inheritance Source: https://backbonejs.org/ Illustrates how to extend Backbone.Model to create new model classes. It shows defining properties like 'initialize', 'author', 'coordinates', and 'allowedToEdit' in a base 'Note' model. A 'PrivateNote' model then extends 'Note', overriding the 'allowedToEdit' method to add specific logic. ```javascript var Note = Backbone.Model.extend({ initialize: function() { ... }, author: function() { ... }, coordinates: function() { ... }, allowedToEdit: function(account) { return true; } }); var PrivateNote = Note.extend({ allowedToEdit: function(account) { return account.owns(this); } }); ``` -------------------------------- ### Load Extension Path via SugarAutoloader::loadExtension (PHP) Source: https://context7_llms This PHP code snippet demonstrates how to retrieve the path for a specific extension using the `loadExtension` function from SugarCRM's Autoloader. It takes an extension name (e.g., 'logichooks') and an optional module name. It returns the file path or false if the extension does not exist. ```php //The list of extensions can be found in ./ModuleInstall/extensions.php $extensionPath = SugarAutoloader::loadExtension('logichooks'); ``` -------------------------------- ### Backbone Router Navigation Source: https://backbonejs.org/ Shows how to use the `navigate` method on a Backbone Router to update the browser's URL. Options like `trigger` and `replace` can be used to control navigation behavior. ```javascript openPage: function(pageNumber) { this.document.pages.at(pageNumber).open(); this.navigate("page/" + pageNumber); } // Or ... app.navigate("help/troubleshooting", {trigger: true}); // Or ... app.navigate("help/troubleshooting", {trigger: true, replace: true}); ``` -------------------------------- ### Emulating HTTP Methods in Backbone Source: https://backbonejs.org/ Enables emulation of HTTP methods like PUT, PATCH, and DELETE as POST requests for legacy servers that don't support them directly. This is achieved by setting the `X-HTTP-Method-Override` header. If `emulateJSON` is also enabled, the method is appended as a `_method` parameter. ```javascript Backbone.emulateHTTP = true; model.save(); // POST to "/collection/id", with "_method=PUT" + header. ``` -------------------------------- ### Backbone.js RESTful API Mapping Source: https://backbonejs.org/ Illustrates the direct mapping between Backbone.js Collection/Model methods and RESTful API endpoints for common operations like fetching, creating, updating, and deleting. ```javascript GET /books/ .... collection.fetch(); POST /books/ .... collection.create(); GET /books/1 .... model.fetch(); PUT /books/1 .... model.save(); DEL /books/1 .... model.destroy(); ``` -------------------------------- ### Backbone.js View: Rendering with a Template Source: https://backbonejs.org/ Shows a common convention in Backbone.js for views to have a `template` function (often using Underscore.js) for rendering HTML. The `render` method then uses this template, populates it with model data, updates `this.el`, and returns `this` for chaining. ```javascript var Bookmark = Backbone.View.extend({ template: _.template(...), render: function() { this.$el.html(this.template(this.model.attributes)); return this; } }); ``` -------------------------------- ### Backbone.Events: Basic Event Binding and Triggering Source: https://backbonejs.org/ Demonstrates how to mix Backbone.Events into an object to enable custom event binding and triggering. Events can carry arguments, and callbacks are executed when the event is fired. ```javascript var object = {}; _.extend(object, Backbone.Events); object.on("alert", function(msg) { alert("Triggered " + msg); }); object.trigger("alert", "an event"); ``` -------------------------------- ### SQL Output from Aggregate SugarQuery Source: https://context7_llms Shows the resulting SQL query when using `setCountQuery()` and `groupByRaw()` in SugarQuery. This output, `SELECT accounts.name, COUNT(0) AS record_count FROM accounts WHERE accounts.deleted = ? GROUP BY accounts.name, accounts.name`, is useful for understanding how the fluent interface translates to actual SQL statements. ```sql SELECT accounts.name, COUNT(0) AS record_count FROM accounts WHERE accounts.deleted = ? GROUP BY accounts.name, accounts.name ``` -------------------------------- ### Fetch Collection Models from Server (JavaScript) Source: https://backbonejs.org/ Retrieves a set of models for a Backbone.js collection from a server. This method uses `Backbone.sync` for persistence and can accept options like `success` and `error` callbacks, as well as `reset: true` to replace existing models. It's intended for lazy-loading data, not initial page load. ```javascript Backbone.sync = function(method, model) { alert(method + ": " + model.url); }; var accounts = new Backbone.Collection; accounts.url = '/accounts'; accounts.fetch(); // Example with options: // accounts.fetch({remove: false}); // Add/change models without removing others // Documents.fetch({data: {page: 3}}); // Fetch specific page of paginated collection ``` -------------------------------- ### Include Specific Bootstrap Sass Components Source: https://getbootstrap.com/ Shows how to selectively import Bootstrap's Sass components. This approach is useful for building lean CSS by including only the necessary parts of Bootstrap. It involves importing functions, variables, mixins, and then specific components like grid and reboot. ```scss // Functions first @import "../node_modules/bootstrap/scss/functions"; // Variable overrides second $primary: #900; $enable-shadows: true; $prefix: "mo-"; // Required Bootstrap imports @import "../node_modules/bootstrap/scss/variables"; @import "../node_modules/bootstrap/scss/variables-dark"; @import "../node_modules/bootstrap/scss/maps"; @import "../node_modules/bootstrap/scss/mixins"; @import "../node_modules/bootstrap/scss/root"; // Optional components @import "../node_modules/bootstrap/scss/utilities"; @import "../node_modules/bootstrap/scss/reboot"; @import "../node_modules/bootstrap/scss/containers"; @import "../node_modules/bootstrap/scss/grid"; @import "../node_modules/bootstrap/scss/helpers"; @import "../node_modules/bootstrap/scss/utilities/api"; ``` -------------------------------- ### Backbone.js: Extending Models and Views with Custom Logic Source: https://backbonejs.org/ Highlights that Backbone.js is designed to be extended. Developers are encouraged to add methods to `Backbone.Model.prototype` or create custom base subclasses to augment functionality. This approach allows for tailored application foundations. ```javascript // Example of extending Backbone.Model (conceptual, not directly shown in text) // var MyCustomModel = Backbone.Model.extend({ // myCustomMethod: function() { // // ... custom logic ... // } // }); // Example of creating a custom base subclass (conceptual) // var BaseModel = Backbone.Model.extend({ // // ... shared logic ... // }); // var SpecificModel = BaseModel.extend({ // // ... specific logic ... // }); ``` -------------------------------- ### Backbone.js Collection Extension Source: https://backbonejs.org/ Defines a new Backbone.Collection class by extending 'Backbone.Collection'. Allows providing instance 'properties' and optional 'classProperties' for the constructor. This is the standard way to create custom collection types. ```javascript var MyCollection = Backbone.Collection.extend({ // Instance properties model: SomeModel, url: '/api/items' }, { // Class properties someClassMethod: function() { /* ... */ } }); ``` -------------------------------- ### Backbone.js Custom Event Binding Source: https://backbonejs.org/ Shows how to define and bind custom events using Backbone.Events. This allows for flexible communication between different parts of your application by triggering and listening to specific event strings. ```javascript model.on("selected:true") model.on("editing") ``` -------------------------------- ### Backbone.Events: Triggering Events with Arguments Source: https://backbonejs.org/ Demonstrates the 'trigger' method for firing custom events and passing additional arguments to the associated callbacks. These arguments are received by the callback functions. ```javascript object.trigger(event, [*args]); ``` -------------------------------- ### Backbone jQuery integration: Backbone.setDomLibrary Source: https://backbonejs.org/ Backbone now supports specifying which version of jQuery to use when multiple versions are present on a page via 'Backbone.setDomLibrary'. This ensures Backbone utilizes the intended DOM manipulation library. ```javascript // Assuming jQuery 1.8.0 is available at '/lib/jquery-1.8.0.js' Backbone.setDomLibrary(jQuery180); // Or if you have it globally accessible Backbone.setDomLibrary($); ``` -------------------------------- ### Backbone Views: Cached $el and setElement Source: https://backbonejs.org/ Introduction of $el and setElement in Backbone Views for efficient DOM element handling. $el provides a cached jQuery (or Zepto) reference, and setElement simplifies updating the view's element and re-delegating events. ```javascript var MyView = Backbone.View.extend({ initialize: function() { // $el is a cached jQuery reference to this.el this.$el.addClass('initialized'); }, setElement: function(element) { // Use setElement to update the view's el and $el this.setElement(element); // Re-delegates events on the new DOM element } }); ``` -------------------------------- ### Backbone.js Model Cloning Source: https://backbonejs.org/ The 'clone' method returns a new instance of the model with identical attributes. This is useful for creating a copy of a model without affecting the original. ```javascript var clonedModel = originalModel.clone(); ``` -------------------------------- ### Backbone.js: Initialize Mailbox Model with Message Collection Source: https://backbonejs.org/ Demonstrates how to define a Backbone.Model for a Mailbox, initializing it with a `Messages` collection. It sets the collection's URL and attaches an event listener for the 'reset' event to update counts. This pattern enables lazy-loading of messages. ```javascript var Mailbox = Backbone.Model.extend({ initialize: function() { this.messages = new Messages; this.messages.url = '/mailbox/' + this.id + '/messages'; this.messages.on("reset", this.updateCounts); }, // ... other methods }); var inbox = new Mailbox; // To fetch messages when the inbox is opened: inbox.messages.fetch({reset: true}); ``` -------------------------------- ### Backbone.js Management Interface (CoffeeScript) Source: https://backbonejs.org/ This snippet illustrates the use of Backbone.js as the primary framework for rewriting a management interface. It's written in CoffeeScript and utilizes Eco for templates, Sass for stylesheets, and Stitch for CommonJS module packaging, highlighting a modern JavaScript development stack. ```coffeescript # Example Backbone Model in CoffeeScript class Stripe.Models.Account extends Backbone.Model urlRoot: '/api/accounts' defaults: name: '' email: '' # Example Backbone View in CoffeeScript class Stripe.Views.AccountView extends Backbone.View template: JST['app/templates/account_show.jst'] # Assuming JST is precompiled templates render: -> @$el.html(@template(@model.toJSON())) @ # Example of using the model and view # account = new Stripe.Models.Account(id: 'acc_123') # view = new Stripe.Views.AccountView(model: account) # $('#account-container').html(view.render().el) ``` -------------------------------- ### Check for Duplicate Records using SugarCRM REST API (Bash) Source: https://context7_llms Demonstrates how to use the SugarCRM REST API's duplicate check endpoint to identify potential duplicate records within a module, such as 'Accounts'. This command requires a valid OAuth access token obtained from the authentication step and the module name. ```bash curl -s -X POST -H OAuth-Token:{access_token} -H Cache-Control:no-cache -H "Content-Type: application/json" -d '{ "name":"Test Record" }' https://{site_url}/rest/v11/Accounts/duplicateCheck ``` -------------------------------- ### Setting Model Attributes (JavaScript) Source: https://backbonejs.org/ Shows how to use the `set` method to update one or more attributes on a Backbone.js Model. This can trigger 'change' events for the model or specific attributes. ```javascript note.set({title: "March 20", content: "In his eyes she eclipses..."}); book.set("title", "A Scandal in Bohemia"); ```