Let's say that it's a WhatsApp-like, a decoupled, Drupal 8-backed, real-time chat platform that you're building. One using Node.js. In this case, implementing field autocomplete functionality becomes a must, doesn't it? But how do you add autocomplete to text fields in Drupal 8?
Needless to add that such otherwise "basic" functionality — implemented on fields like node reference and user/tags — would instantly:
improve the user experience
increase the level of user interactivity and engagement
Users would group around different "channels" and be able to easily add new members. The auto-complete text fields will make the whole “new member coopting” process conveniently easy:
Users would only need to start typing and an array of name suggestions (of the already existing team members) would spring up.
But let's see, specifically, what are the steps to take to implement autocomplete functionality in Drupal 8:
1. The Drupal Autocomplete Form Element: Adding Properties to the Text Field
The first basic step to take is to define your form element. The one that will enable your app's users, on the front-end, to select from the suggested team members' names. For this:
navigate to “Form” (you'll find it under “Entity”)
scroll the menu down to ”NewChannelForm.php”
Note: using “#autocomplete_route_name element”, when defining your form element, will let Drupal know that it should ignore it on the front-end.
And now, let's go ahead and assign specific properties to your form's text field! For this:
define “#autocomplete_route_name”, so that the autocomplete JavaScript library uses the route name of callback URL
define “#autocomplete_route_parameters”, so that an array of arguments gets passed to autocomplete handler
$form['name'] = array(
'#type' => 'textfield',
'#autocomplete_route_name' => 'my_module.autocomplete',
'#autocomplete_route_parameters' => array('field_name' => 'name', 'count' => 5),
);
And this is how you add #autocomplete callback to your fill-in form's text field in Drupal 8!
Note: in certain cases — where you have additional data or different response in JSON — the core-provided routes might just not be enough. Then, you'll need to write an autocomplete callback using the “my_module. autocomplete“ route and the proper arguments (“name” for the field name and “5” as count, let's say).
And here's specifically how you write a custom route:
2. Add Autocomplete to Text Fields in Drupal 8: Define a Custom Route
How? By simply adding the reference to the route — where data will get retrieved from — to your “my_module.routing.yml file”:
my_module.autocomplete: path: '/my-module-autocomplete/{field_name}/{count}' defaults: _controller: '\Drupal\my_module\Controller\AutocompleteController::handleAutocomplete' _format: json requirements: _access: 'TRUE'
Note: remember to use the same names in the curly braces (those that you inserted when you defined your “autocomplete_route_parameters”) when you pass parameters to the controller!
3. Add Controller with Custom Query Parameters
In the custom route that you will have defined, you'll have a custom controller AutocompleteController, with the handleAutocomplete method.
Well, it's precisely this method that makes sure that the proper data gets collected and properly formatted once served.
But let's delve deeper into details and see how precisely we can generate the specific JSON response for our text field element.
For this, we'll need to:
set up a AutoCompleteController class file under “my_module>src>Controller > AutocompleteController.php"
then, extend the ControllerBase class and set up our handle method (the one “responsible” for displaying the proper results)
it's the Request object and those arguments already defined in your routing.yml.file (“name” for the field name and “5” for the count, remember?) that will pass for your handler's parameters
the Request object will be the one returning the typed string from URL, whereas the “field_name” and the “count” route parameters will be the ones providing the results array.
Note: once you get to this step here, as you add autocomplete to text fields in Drupal 8, remember that you should be having data in “value” and “label” key-value, as well:
Next, you'll set up a new JsonResponse object and pass $results, thus generating a return JsonResponse.
Summing Up
That's pretty much all the “hocus pocus” that you need to do to add autocomplete to text fields in Drupal 8. Now the proper data results should be generated.
Just reload your app's form page and run a quick test:
Try to create a brand new channel in your app and to add some of the already existing team members.
Does the text field have autocomplete functionality added to?
RADU SIMILEANU / Jul 18'2018
Let's say that you need to spin up a new Drupal environment in... minutes. To quickly test a new patch to Drupal core, maybe, or to switch between 2 or more clients on the same day and thus to run multiple copies on several websites... In this case, how about taking the quick and easy way and set up a local Drupal site with Lando?
"What is Lando?" you might legitimately ask yourself.
A DevOps tool and Docker container-based technology enabling you to spin up all the services and tools that you need to develop a new Drupal project in no time.
"Why would I choose Lando as a method to set up a local Drupal site?"
Let me list here some of the strongest reasons:
it makes setting up a local Drupal site unexpectedly easy (and I'm talking about "minutes" here)
it makes getting started with Docker container technology a whole lot easier
it enables you to share your Drupal site's configuration within your team right on your Git repository (taking the form of a YAML file)
it puts several development environments (LEMP, MEAN, LAMP) at your disposal
Are these reasons strong enough for you?
If so, here's a quick step-by-step guide on how precisely to set up a Drupal site with Lando:
Step 1: First, Make Sure You Meet the System Requirements
If, as a web developer, you're not efficient with using the command line... well... then there are high chances that you find this tutorial here a bit discouraging.
And if being more than just familiar with the command line is not a strict requirement, then the following system requirements () are:
macOS 10.10+
Linux (with kernel version 4.x or higher)
Windows 10 Pro+ (or equivalent) with Hyper-V running
These are the 3 operating systems that Lando's currently compatible with. Now, let's move on...
Step 2: Download and Install Lando and Docker
Go to Lando releases on Github and download the latest version for your OS. Just run the installer and let it "do the job" for you:
install Docker for Windows, Docker for Mac, Docker CE
install Lando: for Mac run brew cask install Lando and for other OS download the .rpm, .dmg, .exe or .deb
Step 3: Create a New Drupal Project
Luckily for you, there are several ways to get a Drupal codebase. Pick the one that you're most comfortable with as you set up a local Drupal site with Lando:
install Drupal 8 the standard way (the first step there being "Get the Code"); next, grab the latest version of Drupal 8 navigating to "Download & Extend"
or use Composer to create your new Drupal project: composer create-project drupal-composer/drupal-project:8.x-dev my_drupal_project --stability dev --no-interaction
or just navigate somewhere on your PC and use GIT to clone it: git clone --branch 8.6.x https://goo.gl/Q3MoVu lando-d8
Step 4: Set Up a Local Drupal Site with Lando: Extract Drupal
To extract Drupal just:
open up your terminal window
enter the commands here below:
cd Sites
tar xzf /tmp/drupal-8.5.1.tar.gz
mv drupal-8.5.1 drupal-lando
cd drupal-lando
And thus set up the Sites/drupal-lando/ directory inside your home directory
Step 5: Set Up Lando
Now's time to initialize Lando and enable it to create a basic configuration file for you.
And, again, you have more than just one option at hand:
while still in your terminal window, run the following command and specify the Drupal 8 recipe and your web root as web, next name it "drupal-lando": lando init --recipe drupal8 --webroot=. --name="drupal-lando"
or just launch the interactive session: run "lando init" interactively
Next, it's the following YAML file/ ".lando.yml", that it will create:
name: drupal-lando
recipe: drupal8
config:
webroot: .
Note: feel free to ignore the "lando init" step and to jump straight to copying and pasting this file here.
Step 6: Start Your Environment & Wait for Your Docker Containers to Get Set Up
And here you are now, at that step from the whole process where you set up a local Drupal site with Lando where you start your Docker engine.
For this, just run the following command in your terminal window:
lando start
If everything goes according to plan, this is where Lando starts Docker and sets up 2 containers.
Next, feel free to run:
lando composter install
It's going to use PHP/Composer inside the newly created Docker container for building Drupal's Composer dependencies.
Step 7: Browse to Your Site's URL and Walk Through the Drupal Installation Process
Time to install your new clean Drupal 8 site now.
Just visit your local site in the web browser and walk through the Drupal wizard install process (since your new site starts with an empty database, you will be automatically directed to the Install page)
Once you reach the step where you need to configure your database, enter these options here:
Database host: database
Database name, username, password: drupal8
Next, unfold the "Advanced Options" drop-down menu and:
replace "localhost", currently showing up in the "Host" field, with "database"
hit the "Save and Continue" button and let the Drupal installation process carry out
You'll set up a local Drupal site with Lando in... minutes! A brand new website that you can then easily:
test
debug
manage with Composer
Optionally, you can add a new service of your liking (e.g. MailHog, for catching outbound mails) and custom tune your setup right from your .lando.yml.file.
The END! And this is how you do it... Told you it was just a matter of a few easy steps!
RADU SIMILEANU / Jul 10'2018
Oops! The worst has happened: your Drupal site has been hacked! Maybe it was precisely one of those critical vulnerabilities, that the Drupal security team has been drawing attention to these last months, that the attacker(s) exploited?
Now what? What to do?
Should you be:
rushing to restore your website to a healthy, good-working state (that, of course, if you do have a clean and recent backup available)?
starting to rebuild it?
investigating how your Drupal site got contaminated in the first place: where's the “open door” that the attackers used to get in?
focusing on closing any backdoors that could make new attacks possible?
Now “tormenting” yourself with too many questions simultaneously will only distract you from what should be your main objective: cleaning up your website (and preventing further hacks I should add).
So, let's go about it methodically, step by step:
Step 1: Write Down Issues, Steps to Take, Preventive Measures to Apply
Keep your cool and go for a methodical approach to crisis management:
Just open up a document and start... documenting:
the issues and any suspicious activity that you identify on your site
all the steps that your strategy for removing malware and restoring your site should include
the preventive security measures you commit to taking for preventing such a scenario from happening again the future
Step 2: Make a Forensic Copy of Your Drupal Site
Before you start running your “investigations” on the attack, on how your Drupal site has been hacked, and way before you get to rebuild anything:
Make a forensic copy of all your files, you database and your operating system environment!
Note: go with an external storage medium for these copies and store them offsite.
As you're scanning through your files, detecting viruses and malware and having them cleaned up, feel free to make new and new “working backups”. And to store them in a different directory (from your regular backup files, I mean).
“But why bother? When will these backups turn out particularly useful?”
when you call out to a third party to assist you with the troubleshooting process; these “working” backups will then provide a clear picture of the site before you started “malware detecting” on your own
when you try to fix the issues you detect, but instead you make them worse; then, you can easily roll back those changes
Step 3: Scan Your Servers and PC for Malware, Malicious Code Injections, Viruses
Before you rush to change all the passwords on your site, pause for a moment to think through your next “move”:
What if the attack has been “programmed” so that the attacker should get notified once you change your password(s)? And what if it's precisely your PC or one of your servers that's got infected? Then storing a clean backup of your site precisely there would only make it even more vulnerable.
So, how do you prevent that? You give both your PC and your servers a deep scan before making any change.
And, thank God, you sure aren't nickel and dimed in anti-malware tools and anti-virus software: AVG, BitDefender, Malwarebytes, ESET, AV-Comparatives etc.
Step 4: Detect & Remove the Backdoors
One of the crucial steps to take, once you realize that your Drupal site has been hacked, is to “close” all the backdoors.
These could easily turn into hackers' access ticket into your site even after you've removed malware and restored it to its healthy state. But, for closing them you first need to... find them right?
So, where to look?
Here are a few key places on your site that you should focus your “searches” on:
access logs: while scanning them, be vigilant and look for PHP scrips and POST requests added to directories that have writable access
eCommerce set up: check all the payment methods, shipping addresses, credit card addresses, linked accounts, looking for any suspicious, newly added data
passwords: FTP passwords, admin passwords, control panel passwords
email rules and filters: check that the answers to the security questions are “legitimate”, that messages are being forwarded to correct email addresses etc.
Step 5: Consider Taking Your Site Offline
And your decision depends greatly on the nature of your site:
If it's a hacked eCommerce Drupal site that we're talking about here, then don't wait even one more minute: take your site down (along with the internal network and servers) and install a placeholder!
This way, you'll prevent:
malware from being further distributed
spam from being sent to your online store's customers
Note: do keep in mind that taking your site offline will instantly let the attackers know that you've detected the malware that they've “infiltrated” and that you are about to “take action”.
If you decide not to take your Drupal site offline at the web server level, ensure that you've got your clean forensic copy at hand before deleting all the sessions.
Note: have you detected suspicious changes of the passwords? If so, use this query here for updating them (Drupal 7):
update users set pass = concat('ZZZ', sha(concat(pass, md5(rand()))))
As for the users, they can easily use the reset password tool for updating their passwords.
Word of caution: mind you don't take "Drupal on maintenance mode” for “offline Drupal". They're 2 completely different things! Once your Drupal site has been hacked, the malware could be of such nature that it allows the attacker to infiltrate as long as the site's online.
Step 6: Notify Your Hosting Provider That Your Drupal Site Has Been Hacked
They should be informed about the breach and about your site being taken offline (if it's the case) immediately.
The sooner the better, this way they can:
start scanning their own systems for incursions
get ready to assist you with your site recovery and securing process
Step 7: Handle Client Data with Extra Precaution
And these are the specific scenarios where you'll need to take extra precautions when handling client information:
your Drupal site stores client information on the web host
… it leverages the data POST method for sending form data via e-mail
… it doesn't integrate with a 3rd party payment gateway, but manages the payment processes itself
If one of these 3 scenarios suits your case, then here are some of these extra precautions that you need to make to ensure the private user data doesn't get exposed:
update your SSL certificate
re-check all logfiles (have any of the hosted client information been copied, updated or downloaded?)
implement AVS (address verification system)
add CVV (card verification value)
encrypt connections to back-end services used for sending confidential user data
Step 8: Investigate the Attack: Identify the Source(s) of Infection
No matter how much pressure you might find yourself under to get your site back online ASAP, don't let take control over your site's restoring process!
Not until you've detected the main source of contamination on your site. The key vulnerability that attackers exploited, the key reason why your Drupal site has been hacked in the first place.
That being said, make sure that:
you first audit, on a staging server, that “clean” backup of your site that you're planning to get online; this way, you track down and remove infected files, unauthorized settings, malicious code
you compare pre- and post-hack files, looking for any suspicious changes
Now if you have a clean (and recent) backup at hand for running this comparison, the problem's almost solved. Just use the right tools to compare your files and track down discrepancies.
But if you don't have a backup at hand, then there's no other way but to:
Manually inspect your files and databases to identify any suspicious changes that have been made.
look for any suspicious iframe or JavaScript at the end of the files (if detected, save the code in an external file)
look for any sources of “Drupal site hacked redirect”; for links to external URLs
Now, as for the places that you should be running your investigations on, let me give you just a few clues:
.php files, .html files
sessions table
newly modified/created files
new/updated user accounts
in writable directories and database
Step 9: Do a Full Restore of Your Site
So, you've noticed that your Drupal site has been hacked, you've assessed all the damage caused, removed malware and even detected the vulnerability that hackers exploited to get in, not it's only but logical to:
Try to repair your website, right?
Word of caution: never ever run your changes on your production site; instead, fix all detected issues on a staging site. Also, once you've cleaned it all up, remember to run the latest Drupal security updates, as well!
Now, getting back to repairing your site, you have 2 options at hand:
you either restore a clean backup, if you know the date and time that your Drupal site has been hacked and you're also 100% sure that none of the system components, other than Drupal, got contaminated
or you rebuild your Drupal site
The latter method is, undoubtedly more cumbersome, yet a lot more cautious. Go for it if:
you do not know the precise date and time when your site's got contaminated
you do not have a clean (and recent) backup available to restore
you've evaluated the damages as being already too widespread
Step 10: Give Your Restored Site a Full Check Before Going Live
Do remember to give your newly recovered site a final audit before getting it back up:
remove all malicious code detected
suspicious files
unauthorized settings
And, most of all:
Close all the backdoors!
Final Word
A pretty long, complex and discouragingly tedious recovery process, don't you think?
So, why wouldn't you avoid all these steps that you need to go through once your Drupal site has been hacked?
Why not avoid the risk of finding yourself forced to take your website offsite for... God knows how long, risking to impact your site's reputation and to drive away users/online customers?
Don't you find it wiser to:
be prepared instead?
opt for ongoing Drupal maintenance and support services?
make a habit of regularly backing up your website?
keep your system and software up to date (and to install all the recommended patches)?
stop underrating the security advisories that the Drupal team makes?
RADU SIMILEANU / Jun 25'2018
“Learn from your mistakes” should be every developer's life mantra. But that doesn't mean that they should be all your mistakes, right? With a list including the most common Angular mistakes at hand, you'd get to narrow down the number of possible pitfalls that you risk falling into to the... uncommon, the less predictable ones.
So, what are the traps that Angular developers fall into most often as they build their applications?
We've run our own "investigations" for you:
gone through the code examples on the web
ran an inventory of the most frequent questions on StackOverflow
looked over some of the issues that we've knocked our heads against while working on our own Angular projects
… and trimmed down our list to 5 most frequent mistakes that Angular developers make:
1. ngOnChanges vs ngDoCheck: Misunderstanding When the ngDoCheck Gets Triggered
"I have used OnPush strategy for my component and no bindings have changed, but the ngDoChecklifecycle hook is still triggered. Is the strategy not working?"
I bet that you've stumbled across this question (maybe put into different words) on various developer forums. It could easily win any “popularity” test there since it keeps coming up again and again.
But, before we give it a straight answer and settle this matter for good, let's focus on these 2 “change detecting” lifecycle hooks in Angular. And see where the problem stems from:
As you well know it, AngularJs has the watch feature, which “alerts” you whenever a value changes. Angular, on the other hand, has replaced the watch and scop feature with component inputs as properties. Moreover, it has added the ngOnChanges lifecycle hook, as well.
And here's where things get “tricky” and risk to turn into the trap that many Angular developers fall into:
The OnChanges event doesn't emit if/when a deep field of the input property changes. Hence, the value of the input is the reference of the object.
How do you approach this problem? You have several methods at hand, in fact, but I'm going to focus on the most common one:
Using the ngDoCheck lifecycle hook once you run the change detection process!
Now here's the answer that I've promised, to the above-mentioned common developer question:
The onPush strategy for detecting changes in Angular does work: the hook is triggered by the design itself!
Note: another ridiculously frequent mistake that developers make is to take "Angular" for "AngularJS"! Be better than that: the term "AngularJS" should be used only when you refer to the old Angular and to Angular 1, while Angular 2/2+ 4 and 5 is just... "Angular". Mind you don't delve deep into this confusion yourself, too!
2. Forgetting to Unsubscribe: One of the Most Common Angular Mistakes
“Forgetting” or simply ignoring this issue.
And you have no “excuse”, you know, for overlooking to clean up your subscriptions in Angular. Considering that there are methods and libraries developed precisely for handling these unsubscriptions once you've finished using an event or an observable in JavaScript.
Why does this “clumsiness” risk to grow into a major issue? Because lingering subscriptions cause memory leaks in your system.
And when it comes to the unsubscription process, there are 2 scenarios:
you trigger the OnDestroy lifecycle hook if it's in a component that you've subscribed in
you initiate the lifecycle hook yourself if it's a service that you've subscribed in (since, in this case, there's no available hook for you to fire)
To recap: Remember to unsubscribe when you no longer use a service/component!
3. The Wrong Use of Providers
One of Angular's (compared to AngularJS) key improvements is its Hierarchical Dependency Injection, agree?
This means that now you're free to instantiate a service several times (services used to be singletons back in the AngularJS's “glory days”, remember?).
Now that being said, let's have a look at a more than likely scenario:
Imagine yourself fetching your heroes using a heroes service:
@Injectable()
export class HeroesService {
heroes: Hero[] = [];
constructor(private http: Http) {
this.http.get('http://give-me-heroes.com').map(res => {
return res.json();
}).subscribe((heroes: Hero[]) => {
this.heroes = heroes;
});
}
getHeroes() {
return this.heroes;
}
}
Nothing unexpectedly wrong till here:
the data is being fetched in the constructor
there's also a getHeroes method for retrieving the heroes
Now, let's take a look at the hero component, too:
@Component({
selector: 'hero',
template: '...',
providers: [HeroesService]
})
export class HeroComponent {
constructor(private heroesService: HeroesService) {}
}
@NgModule({
declarations: [HeroComponent]
}
export class HeroesModule { ... }
As you can see, first the HeroComponent declares the HeroesService provider in the @Component.providers array, next it incorporates it in the constructor.
All well and good till you realize that each HeroComponent instance instantiates a new instance of the HeroesService.
To put it more simply:
Your HeroesService will be fetching the data (by HTTP request) several times, for each and every HeroComponent instance!
And this is due to the Hierarchical DI in Angular.
The solution for avoiding this issue — no doubt one of the most common Angular mistakes?
Declaring the service in the @NgModule.providers instead:
@Component({
selector: 'hero',
template: '...'
})
export class HeroComponent {
constructor(private heroesService: HeroesService) {}
}
@NgModule({
declarations: [HeroComponent],
providers: [HeroesService]
}
export class HeroesModule { ... }
There! The provider will now be instantiated once and for all. “For all” the HeroComponent instances I mean.
“How come?” You might ask yourself.
Because the provider (declared in the NGModule now) is a singleton now. Therefore all the other modules can use it.
4. Manipulating the DOM Directly
Although I've already said this about another mistake from this list, I now tend to consider this one here instead as being one of the most common Angular mistakes:
Manipulating the DOM directly; oftentimes from the controller itself!
And this is one of those top 10 Angular mistakes that any developer stands a high risk of making. Since manipulating the DOM is such a common task when using this platform:
you might need to render SVG
you might need to refresh a page's title based on a context change
you might need to set the focus on a control after a validation error
… and the list of possible situations goes on
Then... you fall right into it: you take the easy way out and hack the DOM directly!
Now what I feel like pointing out it here is that:
Angular's grown from a web framework into a platform!
And this can only mean that you're now free to decouple your Angular application's codebase from the renderer and:
have your app executed in on the server
… in the browser
… as a native app
And decoupling opens the door to other possibilities for you to explore and to tap into, such as using web workers or AOT (ahead of time compilation).
Speaking of the latter:
AOT enables you to compile your app's templates in the build time of your server. Moreover, you won't need to use the oversized @angular/compiler package in your bundle, which leads to a lower size and load time.
Yet, for future-proofing these “facilities” that Angular provides, you'll need to abide by... some sort of rules at least. And one of them is:
Restraining yourself from manipulating the DOM directly, using jQuery, the global document object or the ElementRef.nativeElement.
Instead, use the Renderer2 service (or Renderer for Angular 2):
It's 2 things that this wrapper to the view mutation layer will enable:
for the default layer to be used in the browser
for the renderer to get replaced with a more suitable one whenever your Agular app runs on another platform (e.g. a phone)
In short: Resist “temptation” and never ever touch the DOM directly!
5. Declaring The Same Component in More than Just One NgModule
And declaring a component in multiple NGModule-s is one of those most common Angular mistakes that end up throwing an error “at” you.
“Why, so?”
Because you need to declare each component in its own NgModule — and to list it in the @Ngmodule.declarations array — in order for it to be available for the views.
If you do need to declare the very same component in multiple modules, you'll need to consider the relationship between those modules:
Is it a parent-child one, maybe?
If this is the case, then:
use the child's NGModule.declaration to declare the HeroComponent in the child module
use the chid's NGModule.exports array to... export the HeroComponent
use the parent's NGModule.imports array to import the child module
If not (if we can't be talking about a parent-child module relationship), then you'll need to declare another NgModule as the module of the shared data.
Final Word
It's only by knocking your head against unexpected issues while building your projects on this platform, that you'll get to grow as an Angular developer.
And still, instead of embracing the “fail fast, fail often” concept, wouldn't it be best if you:
learned from other developers' mistakes, thus knowing what the most common Angular mistakes are
ensured that you failed "rarely" instead?
RADU SIMILEANU / Jun 05'2018
Building a web app using React for the first time? Then it must be a simple "Hello World" type of app that you're planning to set up. One that would guarantee you a smooth first-hand experience with React.js...
So, you're wondering:
"What's the fastest way to build a basic app in React?"
A question then followed by a... myriad of other questions:
"What dependencies should I use?"
"What React stack should I go for if it's just a simple web app that I want to create?"
Now it's about time that you moved from questioning yourself to code writing, don't you think? Here's a simple and easy-to-follow tutorial on how to create a React app from scratch.
1. Create a New React Project Folder
The very first step to take is to start a new React project. Obviously!
Note: Make sure you have NPM and Node installed in your environment first things first!
For this, just run the command here below:
npm install -g create-react-app
Tada! Your React boilerplate app creator has just bee installed!
Now the second code that you'll run is going to create your "Hello World" React app itself:
create-react-app hello-world
Running an imaginary magnifying glass across your app's structure you can't help not noticing the 3 major file types there:
public/index.html files
src/index.js files
src/App.js files
And scanning your app's backbone a little deeper you'll spot:
a div with the id root
this piece code here below in the index.js.file:
ReactDOM.render(, document.getElementById(‘root’));
If we were to translate this code segment into plain language it would go something like this:
React injects your app component into the div by using the root id.
2. Write the Simplest React Component
"But what is an app component more precisely?"
Take it as React's convention to use the same names both for JavaScript files and the component.
And now the code for your more-than-basic component would look something like this:
import React, { Component } from 'react';
class App extends Component {
render() {
return (
<div className="greeting">
<h1> Hello World! </h1>
</div>
);
}
}
Feel free to create a JavaScript class for it and to extend it from the Component class.
Next, implement the render () method, which will return a whole suite of elements (unlike prior to React 16, when one had to return a single element per each render method that was being implemented).
Then, running the npm start command in your app's directory, you'll see the "Hello World" text message displayed at http://localhost:3000.
Hello World!
3. Building a Web App Using React and JSX
And I feel that I should start by defining JSX, right? Before I go ahead and delve into details on how to use it with React:
An extension to the JavaScript language — therefore a template language — with a structure similar to HTML. One that makes a great team with React.
Its true "power" is that it... empowers you to write your HTML components and React components in an HTML-like tag:
<HelloWorld />
And here's JSX "in action", right in this "Hello World" app that we're building here:
The following code:
const element =
(
<h1 className="greeting">
Hello, world!
</h1>
);
... gets compiled to the familiar JavaScript code here below:
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);
See? A familiar HTML-tag language that makes structuring an app's code a whole lot easier for any developer!
And this is JSX's main role and the very reason why it works perfectly with React.
4. How to Use State vs Props in React.js
How about creating another component as we're building a web app using React?
Let's name it "Mary":
import React, { Component } from 'react';
class Mary extends Component {
render() {
return (
<div>
<h2> Hi, I am Mary </h2>
</div>
);
}
}
export default Mary;
Bravo! Next, we can include it, as a child component, into our existing React App component:
import React, { Component } from 'react';
import Mary from './Mary';
class App extends Component {
render() {
return (
<div className="greeting">
<h1> Hello World! </h1>
<Mary/>
</div>
);
}
}
export default App;
Note: Noticed the import statement for our "Mary" component? It plays a key role since without it our React app wouldn't work. And this because React wouldn't be able to identify, all by itself, the component that corresponds to the Mary tag.
Curious now how you could manipulate your "Mary" component? How you can control its behavior?
By manipulating its... state object, that's how!
Note: each React component comes with its own state object.
import React, { Component } from 'react';
import Mary from './Mary';
class App extends Component {
constructor() {
super();
this.state = {
greeting: "Hello World!"
}
}
render() {
return (
<div className="greeting">
<h1> {this.state.greeting} </h1>
<Mary/>
</div>
);
}
}
export default App;
See the "greetings" property — having the "Hello World" value — that corresponds to the state object? Remember that you're free to add as many properties as needed.
Next, how about trying to pass data from our App component into its child one, Mary:
import React, { Component } from 'react';
import Mary from './Mary';
class App extends Component {
constructor() {
super();
this.state = {
greeting: "Hello World!",
parentMessage: "Hello Mary!"
}
}
render() {
return (
<div className="greeting">
<h1> {this.state.greeting} </h1>
<Mary newMsg={this.state.parentMessage} />
</div>
);
}
}
export default App;
Noticed the "newMsg" key there? It's precisely this key that's responsible with the data transfer.
Now, as for the child component "Mary":
import React, { Component } from 'react';
class Mary extends Component {
constructor(props) {
super(props)
this.state = {
greeting: props.newMsg
}
}
render() {
return (
<div>
<h2> {this.state.greeting} </h2>
</div>
);
}
}
export default Mary;
If you're willing to give this piece of code a deep scan, you'll notice that there's a "props" method argument in there.
Keep in mind that it's precisely this object that stores all the data transferred from the parent component to the child React component.
Also, another "detail" that you should be able to detect is the "newMsg" property (transferred from the parent/App component); we've used it to initialize the state of the Mary component.
5. How to Use The React (Component) Lifecycle Hooks
I won't get into too many details, since React's documentation is already more than "enlightening" when it comes to:
the different lifecycle methods (or hooks) to be invoked for each state of a React component
the precise times in the development process for triggering each hook
Nevertheless, I'll briefly add that all these methods to be used across your React components' lifecycles fall into 3 main categories:
mounting hooks: use them at the very start, when your React component is being rendered in the browser page
updating hooks: fire them when your component gets re-rendered on the web page. And this happens if/when changes are made to the state/props objects
unmounting hook: invoke the componentWillUnmount() hook shortly after your component gets removed from the DOM
Note: Since React 16, the collection of hooks has enriched with a brand new one: componentDidCatch()! Fire it whenever you're dealing with an exception during the other lifecycle methods of your component.
In other words: invoke it whenever a component fails to function as it should when you're building a web app using React!
As for the specific way that React manipulates DOM via the Virtual DOM that it creates, feel free to have a look at our post precisely on this topic: How React Virtual DOM Works!
The END!
Your turn now: go through all the steps included here and, step by step, set up your first basic React application!
RADU SIMILEANU / May 31'2018
About to build your very first Angular app? Then you must be planning to create an Angular project with Angular CLI, right? The much-acclaimed tool that the Angular team built precisely to jumpstart the whole development process.
… to have a simple app scaffolded, generated and deployed in no time, by entering just a few commands (so they say, at least).
And since I'm sure that you don't want to waste these bundles of convenience by letting yourself tangled up in overly complex explanations instead, I've kept things simple with this guide.
So, here's how you create and run your first Angular project via the Angular command-line interface:
1. But How Precisely Can Angular CLI Jumpstart Your App's Development Process?
Take this command-line interface as a starter kit “present” that the Angular team has nicely wrapped for you:
it's practically geared at empowering you to get up and start developing a new Angular app in no time
it takes just one short command to generate a default Angular project that would include all the needed dependencies (in the node_modules folder), as well as testing files for each component
Now, this is what I call a major kickstart! It's got you covered from the stage of setting everything up, to creating the Angular project itself, to testing it and finally deploying it.
Other key usages of the Angular CLI that we're not going to focus on in this tutorial here are:
real-time server maintenance and support
building applications for production
adding new features to your existing app
running tests on your application units
2. Setting It Up: Install Angular CLI Globally
Before you jump to the part where you create an Angular app using Angular CLI, you need to install the command-line interface itself. Globally!
And this is the “power” command to enter in your terminal with the npm installed:
npm install -g @angular/cli
Notes:
if you already have the CLI installed, make sure it's the latest version
if you need to update it, these are the commands to enter:
npm uninstall -g angular-cli
npm uninstall --save-dev angular-cli
And there's more! A few more must-have dependencies that you need to make sure that are already installed and upgraded to their latest versions:
Node.js: v6.9.x +
npm: 3.x.x +
3. Create an Angular Project With Angular CLI
With your command line interface ON, use it to enter THE one and only command that will generate a new Angular project for you. One incorporating, by default, all the needed dependencies:
ng new ng-yourproject
Tada! A “yourproject” named directory has just been generated. That's where your new Angular project — along with all the requested dependencies — gets stored.
Eager to test it out? Just run the following command in your terminal:
ng serve
Your Angular app will then get built and served up to localhost:4200. Feel free to open this URL in your browser and it's the here-below screen that you should be able to see:
Basically, it's the default application shell itself rendered by the CLI.
4. “Deconstructing” Your New Angular Project: What Does It Include?
Now, before you go ahead and do your “tweaking” on your newly created app, let's see what you've got in there! What are the elements that the CLI has generated for you to help you jump to development right out of the box?
For this quick “scan”, open your Angular project in your IDE of choice and start “exploring” your src/folder:
src/*
styles.css
any styles that you'll plan to apply globally, it's this file that you can add them to; and it's here, as well, that you can import new .css files (Bootstrap or any other styling frameworks of your choice)
index.html
where your Angular app gets started
src/app/*
app.component.ts
this is where your app's one and only (for now at least) component gets stored
app.module.ts
the modules Angular needs for managing your app's components
note: @NgModule marks the class file as a module and this is what makes it similar to @Component
5. Create a New Component
Remember your “one and only component” that I mentioned during the previous “inventory” of all the “bunch of stuff” that CLI has generated in your project?
Well, how about creating a new one now? One that would load under that root component?
Just run the following command to generate it:
ng generate component the-quote
Next, time to “show it off” in your browser:
<h3>{{myQuote.quote}}</h3>
<small>- {{myQuote.by}}</small>
Add the app-the-quote selector to the root component that the CLI generated in your Angular project:
<h1>
{{title}}
</h1>
<app-the-quote></app-the-quote>
6. Apply External Styling
Now you do agree that when you create an Angular project with Angular CLI applying styling is a key step.
So, let's add your favorite CSS framework to your new application!
Me, it's Bulma that I'll be using in this tutorial here:
npm install bulma --save
With our CSS framework installed, we'll need to enable it to load the CSS file into our Angular app. For this, just place the relative path within the .angular-cli.json file., to the file in the styles array more precisely.
...
"styles": [
"../node_modules/bulma/css/bulma.css",
"styles.css"
],
...
“Tempted” to display some icons now, as well? Then go ahead and add the font-awesome library as cdn link.
For this, just include the stylesheet right into your index.html:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
Et voila! This is how you create an Angular project with Angular CLI!
What do you think? Is the Angular command-line interface an extremely useful tool to jumpstart your project with or did you expected your “starter kit” to include, right out-of-the-box, more elements to get you started?
RADU SIMILEANU / May 25'2018
Just imagine: a user asks Amazon Alexa to read out loud to him/her the headline of your latest blog post! Or maybe to look for a specific section on your Drupal site! Or, even better: quit imagining this and start implementing it instead! Right on your website. And here's how you integrate Alexa with your Drupal 8 website via the Alexa integration APIs.
A 7-step tutorial:
on how to get Alexa to “talk to” your site users/online customers
on turning your site's content into the needed “raw material” for setting up your custom Alexa skills
on how you can leverage Drupal 8's outstanding third-party integration capabilities to “fuel” your implementation plan with
So, here's how it's done:
But Why Precisely Amazon Alexa over Other Voice Assistants?
Because Amazon Alexa stands out with its top notch integration capabilities.
Its integration APIs make it possible for this particular voice service to be “plugged into” various devices and web services.
As simple as that! Alexa's more than just a voice assistant making voice (obviously!) interaction possible:
It's a voice service that empowers you to integrate it even with your Drupal 8 website quickly and smoothly, via its own built-in APIs!
Introducing Alexa: The Drupal Module for Amazon Alexa Integration
With Alexa “doing its own part” and the voice service bringing its Alexa integration APIs into the equation, it was only fair that the Drupal community should play their own part, as well.
The result of their sustained efforts? The Alexa Drupal module:
which provides an endpoint for your Drupal 8 website, where it would receive the vocal user requests “stored” in the Alexa Skills
"user requests” which get converted into text strings before getting sent over to the Alexa module on your Drupal site
Note: do keep in mind that the Alexa module is still under development, but with a more than promising, long-term future ahead of it.
For now, it offers basic integration with Amazon's Alexa. And this is precisely why you'll need to build a custom module, as well, to integrate Alexa with your Drupal 8 website.
But more details on this, in the tutorial here below:
Integrate Alexa With Your Drupal 8 Website: A 7-Step Guide
Step 1: Make Sure Your Site Uses HTTPs
In other words: make sure your Drupal 8 website's “easily detectable” by Amazon's servers!
The very first step to take will be to switch your site over to an HTTPs domain (a step you can skip if your site's already on HTTPs)
Step 2: Install the Alexa Module
Go “grab” the Alexa Drupal module and get it installed and enabled on your website.
Step 3: Set Up Your Alexa Skill
With your dedicated Drupal module ON, it's time to focus on all the needed setting up to be done on the Amazon Developer site. And the very first step to take is to create your own new Alexa Skill in the Skills Kit there.
Step 4: Copy & Paste Your Application ID
And this is no more than a quick 2-step process:
first, you copy the Application ID provided in your “Skill information” section, on the Amazon developer site
then you submit it to your website's configuration at /admin/config/services/alexa
Step 5: Configure Your New Alexa Skill
A key 3-part step to take when you integrate Alexa with your Drupal 8 website, where you:
give a name to the Alexa skill (in the Alexa app) to be triggered
set up an Invocation Name for your users to utter for “activating” your newly created Alexa skill
set up the custom vocal commands or “intents” that Alexa will need to respond to
For this, you'll need to go to the Amazon Development website again and access the “Skill Information” section.
Note: maximize the odds that it's precisely those intents that your users will utter by adding more phrasings of the very same question/vocal command.
Another note: this flexibility proves that you get to harness the power of... variables when setting up your custom intents. “Variables” that you'll use with the custom module that you're going to build at the following step of the process:
Step 6: Create a Custom Module for Triggering The Right Responses to Your Intents
What should happen when your custom intents get invoked and sent through to your Drupal 8 website?
You'll need to create a custom Drupal 8 module that would handle responses.
For this, insert the following info in the demo_alexa.info.yml file:
name: Alexa Latest Articles Demo
type: module
description: Demonstrates an integration to Amazon Echo.
core: 8.x
package: Alexa
dependencies:
- alexa
Note: Do keep in mind to add the Alexa Drupal module as a dependency!
Now, time to build the custom module itself:
create a file at src/EventSubscriber/
name it RequestSubscriber.php
As for the code that will “populate” your module, first of all it's the namespace and use statements that you'll need to create:
namespace Drupal\demo_alexa\EventSubscriber;
use Drupal\alexa\AlexaEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\paragraphs\Entity\Paragraph;
Then, you'll need to set up your main class, as well as a function to trigger the event:
/**
* An event subscriber for Alexa request events.
*/
class RequestSubscriber implements EventSubscriberInterface {
/**
* Gets the event.
*/
public static function getSubscribedEvents() {
$events['alexaevent.request'][] = ['onRequest', 0];
return $events;
}
Next, set up the function “responsible” for giving responses to each one of your custom intents.
With the code for your responses at hand, the very last file that you'll need to focus on is the demo_alexa.services.yml:
services:
alexa_demo.request_subscriber:
class: Drupal\demo_alexa\EventSubscriber\RequestSubscriber
tags:
- { name: event_subscriber }
Note: Remember to enable your demo Alexa module, then to navigate to the Amazon Developer site once again!
Step 7: Test Out Your New Alexa Skill
Another essential step to take when you integrate Alexa with your Drupal 8 website is testing your newly created Alexa skill.
And there's even a Test tab on https://developer.amazon.com for that!
Click on this specific tab, ensure that your new Alexa skill is enabled and thus ready to be tested and... see whether you'll get the right responses!
The END! This is the “how it's made” for getting Amazon Alexa to “talk to” your Drupal 8 website via:
the Alexa integration APIS
the Alexa module
a custom-built Drupal 8 module
RADU SIMILEANU / May 18'2018
It's undebatable: Node.js has practically laid the foundation of the real-time web! The real-time, two-way connection web apps have revolutionized the old web response paradigm. The one where it was just the client who could initiate communication, never the server, as well. Even so, there are certain cases when using Node.js is not the best decision you could make.
Specific use cases for which the otherwise flexible and revolutionary web server technology turns out not to be... unsuitable. So:
“When shouldn't I use Node.js?”
You might legitimately ask yourself.
Here are the 3 bad use cases for this JavaScript runtime environment. Scan them through, take note all the factors that I'll be outlining and think them through before rushing to use Node.js to power your next project with.
1. A CPU-Heavy Application: Using Node.js Is Simply a Bad Idea
Face it, deal with it and... adjust your decisions to it:
There are plenty of better solutions (other than Node.js) for powering your CPU-intensive app. It's just not the best technology at hand when it comes to heavy computation.
Now here's why, by using Node.js, you'll only end up “sabotaging” its very advantages, instead of turning it into a true “horsepower” for your app, as you might expect:
Node.js leverages an event-based, non-blocking I/O model, using a single CPU
hence, all that intense CPU-processing activity will actually block the incoming requests
… since the thread will get “held up” with number-crunching
The direct effect of “exploiting” Node.js in the context of heavy server-side computation?
The very benefits of its event-driven, non-clocking I/O model would get practically... nullified in the context of CPU-intensive operations.
Given this, why would you stubbornly stick to Node.js, when there are other technologies more suitable for building your CPU-heavy software with? With better results?
2. A Simple CRUD (or HTML) Application
No need to get your hopes high when using Node.js with a basic CRUD or HTML application:
It might turn out to be just “slightly” more scalable, yet don't expect a traffic flood just because it's Node.js-powered.
In short: use cases like this one, where data's provided, straightforwardly, by the server and where there's no need for a separate API, render Node.js superfluous.
There are other frameworks suited specifically for this type of projects (take Ruby for instance).
Using Node.js in this case would be like driving a Formula 1 car while... stuck in rush hour traffic.
3. A Relational Database-Backed Server-Side App
Why isn't Node.js your best choice for a relational data access type of project?
Because its relational database tools aren't as reliable, robust and easy to work with as other frameworks' toolboxes (take Rails for instance!).
Rails, for example, would “spoil” you with:
already matured Data Mapper and Active Record data access layer implementations
out-of-the-box data access setup
DB schema migrations support tools
… and the list goes on
In short: if there already are frameworks perfectly “equipped” for this type of project “scenarios”, why would you stick to using Node.js? Since its relational DB toolbox is not (yet) as advanced?
In Other Words...
With these 3 “bad” use cases for Node.js “exposed”, allow me to put together a short “inventory” here, one including all the “gotchas”, aspects to consider before kicking off your Node.js project and limitations to be aware of:
Node.js hasn't been built with the “solving the compute scaling” issue in mind
… but it has been created to solve the I/O scaling issue instead
excepting contexts of CPU-heavy operations, Node.js still is the best technology at hand for powering your real-time, scalable web apps with
do reconsider your decision of using Node.js if for developing your piece of software you depend on some kind of threading model
there are also poor quality packages available in npm, free to use in your Node.js application; do keep this in mind as you dig deep into the “load” of Node.js packages
Node.js will never be “the best choice” for event loop-blocking use cases (take asynchronous parsing XML, for instance)
… nor for powering apps relying on intense computation
Node'js “worker” is geared at solving HTTP server calling issues (rather than intense computing issues)
The END!
RADU SIMILEANU / May 17'2018
Not exactly the “jumping on the latest trend" type? Therefore, you're still a bit hesitant to get on the Node.js bandwagon? And this because you still haven't got some crystal-clear answers to your “What is Node.js used for?” question?
You're legitimately hesitant then! For everyone's gone crazy over it these days, but you know that there must be certain factors to consider.
Specific use cases for Node.js, as well as cases when... well... it just isn't the best idea.
You're well aware that there are some particular applications that call precisely for this JavaScript runtime environment. And you need to be 101% sure that your project fits the “profile”. One of the “best use cases of Node.js”.
But let's not meander any longer and get you some clear answers to your questions instead:
Why should you even consider Node.js one of the possible technologies to choose from for your next project?
Which are the ideal use cases for Node.js?
1. Why Would You (Even) Consider Node.js for Your Project?
Why should Node.js be on your list of... options, in the first place? On your shortlist of technologies that might power your next project?
There must be some “bundles of convenience”, some major benefits that you can “reap” from using it, right? Benefits that make it worth building your project using this specific environment.
Well, let us shed some light on these clear advantages of developing your application in Node.js:
it's a Google JavaScript engine (a runtime environment) which, translated into clear benefits, means that: it's fast and scalable web apps that you'll build using it
speaking of its scalability: Node.js's built to scale on individual process basis and to leverage multi-core processing on modern servers (via its Cluster module)
it's JavaScript-based... so the “pool” of developers with some kind of JS knowledge/expertise is conveniently large: 99,9% of them know at least “some” JavaScript
… no to say that this turns Node.js into the perfect choice if there are beginner developers in your team (even junior developers are at least familiarized with JS)
any developer will be able to gain a quick understanding of your Node.js app's codebase
it speeds up developers' work with a collection of modules (Grunt, NPM, etc.)
it provides your development team with a great package manager, npm, with a widely available and increasingly heavy “load” of open-source tools
it's backed and actively maintained by an ever-growing community ready to... support you; the knowledge base that your development team needs to get a grip on Node.js is accessible and... free
it's open-source: you'll benefit from a single, free codebase
it's just... fast, there's no point in debating over this: the event loop and Google's innovative technologies are “turbocharging” it
it cuts down costs, as simple as that: Node.js enables your team to use the same language on the front-end and on the back-end, which translates into boosted efficiency, cross-functionality and implicitly... reduced costs
you're “tempted” with a whole range of hosting options to select from
it supports native JSON: it's in this specific format that you'll get to keep your data stored in your
database
Now if I was to trim this list to just 3 answers to your “what is Node.js used for?” dilemma, it's these 3 key benefits that I'd stubbornly stick to:
performance: Node.js is simply... fast, faster than other JS languages; moreover, as a runtime language it has enhanced JavaScript with new capabilities
versatility: from backend to front-end apps, to clips to... pretty much everything in between, Node.js enables you to build any kind of project that you have in mind; as long as it's written in JavaScript, of course
agility: regardless of your/your team's level of JavaScript expertise, Node.js empowers you to kick-start your project, to get it up and running in no time; it's developer productivity-oriented (just think same language for both back-end and front-end!!!), with a low learning curve
2. What is Node.js Used for? 7 Great Use Cases
Now back to the very question that started this post:
“What exactly is Node.js good/used for?”
There are specific app projects that this server-side JavaScript technology makes the best choice for:
2.1. Chat servers
And generally speaking any type of fast-upload system challenged to respond, in real-time, to an “avalanche” of incoming requests.
2.2. Real-time apps
This is the use case that Node.js “rocks at”. Where you get to make the most of its capabilities.
Apps geared at processing high volumes of short messages, where low latency becomes critical, make the best possible answer to your “what is Node.js used for?” question.
Here's why:
it enables sharing and reusing Node.js packages that store library code
it processes ideally fast: quick data sync between the client and server
it's perfectly “equipped” to cope with multiple client requests
In short: if scalability and real-time data processing are 2 critical factors to consider when choosing the best technology for your project, think Node.js!
It's built to suit specifically those situations that are “overly demanding” of our servers.
2.3. Video conference apps
...applications using VoIP or specific hardware.
Projects involving intense data streaming — audio and video files — make the best use cases for Node.js.
2.4. Instant-messaging, live-chat apps
2.5. Highly scalable apps
Think Trello or Uber-alike apps, that depend on a server-side server technology enabling them to scale out on multi-CPU servers.
Node.js, thanks to its cluster-based architecture, will always make the best choice for apps depending on a technology that would spread out the load across a multi-core server.
Note: speaking of scalability requirements, should I also mention that Node.js is... conveniently lightweight, too?
2.6. eCommerce transaction software and online gaming apps
“What is Node.js used for?”
For powering apps for which online data is of critical importance. Like these 2 examples here!
2.7. Server-side applications
Being an event-driven model of programming, the flow is determined by messages, user actions, and other specific events of this kind.
3. Afterword
Does this clear the picture for you a bit more?
As a conclusion or “final” answer to your “what is Node.js used for?” type of dilemma, the key takeaway from this post here is that:
Node.js is used primarily for web applications, but it's starting to get used more and more often for developing enterprise apps, too, thanks to its versatility.
What does the future have in store for this increasingly (still) popular technology:
rising potential for Node.js to be used for building IoT solutions
…. for “experimenting” with enterprise data
more and more big names (adding to Netflix, IBM, Amazon, Uber, LinkedIn, etc.) choosing it over legacy languages such as Java or PHP
RADU SIMILEANU / May 10'2018