Create Rest Resource for GET Method in Drupal 8

In one of the earlier blog post we had explored, How to create Custom Rest Resources for POST methods in Drupal 8. Let's see how can we create Rest Resource using GET method in Drupal 8. 

RESTful services were introduced in Drupal 8 into the core, this was inspired by Drupal 7. With Drupal 8 REST, you can enable other websites or applications to view, edit or update information. REST, among other Drupal 8 web services like XML and JSON is a method to provide customizable data in the form of API. 

Normally we can use view but here we will be learning how to create drupal 8 REST using custom code.


So let’s create an example module ‘example_rest’

Module Setup :

Example_rest.info.yml

Now we will be defining the rest resource. In this we will be fetching all the existing node title in the existing drupal.

Let’s create rest resource with GET method.

src\Plugin\rest\resource\ExampleGetRestResource.php

Here in get method we will be defining the logic what we want as output. 


As example we are loading all node present in the drupal installation and return node title as key value pair. Node id will be key and title will be respective value.


Let’s  enable the module and Drupal rest api.

This module will be dependent on Rest and Drupal Rest UI module so we need to enable these two module as well. Rest is included in drupal core but drupal 8 Rest UI is a contributed module so we need to download and enable it.

Once we enable all required module we need to enable our rest api.
 1.Goto admin/config/services/rest
 2.Search for rest api (in our case its “Example get rest resource”) and enable it.
 3.Once you click on enable  it will open the setting page of the respective api we need to select Get and Supported formats as xml, Authentication providers as cookie.
 4.Click on “save config”
 5.Now goto /example-rest?_format=xml

Result :

Test Article
test article
rest test
Rest Test
Test Drupal 8

 

What are you giving back to the Community?

The Drupal Community boasts of having more than a hundred thousand active contributors to this Open Source platform. People around the globe contribute to the codebase and more teaming up together. Businesses nowadays are staying ahead of the competition by encouraging contributions. Everything is about making together and building a better place, if you are not adding value you are already out of the league.

Why should I contribute?

You may be in one of those organizations who agree to disagree with the point above and might ask “Why should I spend my time and resources for something I don’t see value in?” Well, then my friend you should be the first ones to start volunteer contributions with whatever little you can because open source is what it is going to be in future and it will open doors for you, the ones you didn’t even know exists.

It’s difficult to come by a CV of a seasoned developer without the mentions of an open source contribution because they know it matters, it makes a good portfolio of your work which you can showcase to your dream company. What is more, you can also ask your mentor in the community to vouch for you. Imagine going to work for some XYZ company and one of the project manager sends in a recommendation with a big Yes Please! If you are starting your way into the tech world, ask people who matter and have been there, they will tell you networking matters. Get to know the industry inside out and show people that you’ve got what it takes.

And what if you ARE one of those organizations who do not believe in giving back to the community? Well, you might be making money from the software, but in turn you are inflicting scars on yourself. Putting it in simple words “It impacts sales”, you are missing out on valuable and authentic advocacy and will end up beating your own drum. Who does direct marketing when the Drupal community itself shows what you are capable of? Get your bragging rights certified.

 

contributions-top-30-organizations

Image Courtesy : Dries himself!

What are we doing to build a better place?

Contribution is a good way to learn while doing for newbies and experienced professionals alike and is one of the most valuable things one can do. Recently in a write-up Dries explains about how this actually works, who funds these contributions. Also focuses on credits system and the importance of volunteer contributions. He discussed about the top 30 contributors and recognized them for putting a lot of their time and effort in developing Drupal and its contributed modules.

Among the top 25 is one of our developers from Valuebound, Rakesh. He is one of the most experienced and humble souls working and contributing in the community. Along with contributions he makes sure to document his learning and I must mention, he does that thing real nice. This doesn’t end with him here, among the top 10 we also have another awesome dev guy who has been a thorough and serious active contributors who recently left Valuebound. And I saved the best for the last, Valuebound is one among the top four organizations sponsoring these kinds of contributions and we are proud as a team.

There are two sides to this coin as well, givers and takers and we make sure to be a part of both the sides of the coin and in turn be a part of the larger initiative run by this awesome community.

What to contribute? Tech & Non-Tech

A contribution in a tech community isn’t necessarily tech oriented. Look at Mozilla’s contribute guideline. It is one of the best places to explore what contributions can mean for a non-tech contributor. Drupal’s contribution page on their website paints a complete picture on how to go about making a contribution and getting involved.

There are tons of things you can do. All those non-geeky folks around, there is a lot of stuff you can do too! Ranging from Documentation, Translations, Testing to Marketing and even Donations. Yes, everything helps and we kid you not.

To quote Drupal.org “We depend on our diverse community of passionate volunteers to move the project forward by working on not just web development and user support but also many other contributions and interests (such as marketing, organising user groups and camps, speaking at events, maintaining documentation and helping to review issues)”.

Yes we know you could if you would have had the time. Oh wait, there is something you can do too! Yep, in 30 minutes that too, isn’t that great?

How to Contribute?  

Drupal had started out as 100% volunteer contributed and now it turns out that 69% of the contributions are sponsored.With more than twenty five thousand websites using Drupal as  falling into the top 1 Mil, it is time to rethink what we are giving back to the community for this open source platform which helps us earn our bit from it.  

So what if your organization doesn’t have a working plan in place yet? We had chalked out a process flow sometime ago which helped us to get things going with our team, works well with your remote team too.  

There is of course a possibility of you working in an organization which doesn’t believe in contributions. In such a case drupal.org has explained in depth what to do and there is a whole section dedicated just for someone like you. That’s the power of this community!

Build relationships

Get to know your teammates well, grab a cup of coffee or handout with a mug of beer. Talk work and non-work banter. Get to know what works and what doesn't. I’m sure that shouldn’t take a long time since you have already been colleagues. For a new employee or colleague it will just be like a regular work norm that is a part of the work and shouldn’t be difficult because it is a part of what’s expected. Find out how can he or she be of help.

Branch out

Find out what your community needs, which are the most critical projects and the most important issues. Work on them, help out another dev team in need. Most of the issues are detailed, pick out one and start working on it. If you happen to get stuck, read blogs, reach out to your mentor ping other contributors and go over to IRC channels. Ask. Do not stop yourself if you find it difficult at first, people are helpful that is what a community is for. Find it difficult? Start with something easier.

Encourage volunteering

It boosts the morale of an employee to build and work with a collaborative and constructive team. When your employees or colleagues love what they do, you won’t need to see anymore grumpy faces on Monday mornings. Each day will be a celebration and fill the workplace with lots of positivity. And nope this ain’t philosophical, it matters. Those dirty looks you get at times when you tell a no to a raise will stop. They will know what matters and they will work to get shit done, cuz they love what they do, with whom they do, for what they do.

Put it into schedule

It is not always possible that someone volunteers and things fall into place. More than often that will happen, sprints will get rescheduled and it will do more harm than help. Why I know? Cause, been there, done that!

And then we restructured our plan, we evaluated our employee strength and put things into a well documented rock solid plan. But does that mean it won’t ever fail? It might, at least now we know we have put some effort and we know who’s accountable for what. Figure out how much time your employees can devote through the business on a quarterly basis, taking into account your operational needs.

Recognize : Let the world know

Once things have fallen into place and you have successfully made your first plan a success,make it a part of conversation.Let your customers know, especially let the community know. Yes, you have earned the bragging rights! And did I tell you you would get free marketing and that too vouched? Wow! Isn’t it?

Make it a part of respect giving. Set examples. Showcase talents. Mark an email to all other employees. Do it often and do it regularly. What’s worse than not contributing is giving a sudden and permanent halt to whatever you have done. Shows you are irresponsible, period.

What do you get?        

You’re well respected, your customers are loyal and your employees are happier because you might not be aware of corporate social responsibility but your consumers sure are.

Are you doing your bit? Help us help you!

Image Courtesy : http://garfieldtech.com/

Most Commonly Used hooks in Drupal 7

Before I begin with hooks, I am sure that you must be aware of the Drupal hook system. What is hook? How modules interact with the core code of Drupal? How hooks make it possible for a module to define pages, content, bundle, entity, menu, region, table, url etc? In this article I will be re-introducing you to the hooks and if you are looking for more information on the hook system then my suggestion is to go through Understanding hook system for Drupal module

First, I would like to give a small summary on hooks. A hook is a way to place a piece of your own custom code to be run by Drupal. Using hooks, you can ask Drupal to run a piece of code when a node is viewed/edited/deleted. hooks are conceptually related to method. They represent standard ways of interacting with data structures. Also many hooks are state aware, and do different things depending on what exactly is happening at the time the hook is called. 

What Drupal's Hooks API does: 

A Hook is a PHP function in a custom module that executes code. 
The Hooks API allow you to create your own hooks that other modules can access. It provides a common naming standard for hooks and allows modules to interact with other modules. 

As a Drupal Developer, you come across plenty of hooks used in core , contributed & custom module very often. 

There are hooks that are used more often,These common hooks include:

hook_help - Create help text associated with your custom module. 

Description: This hook provides the necessary help and information about module. To implement this hook, you need to replace “hook” with your module’s name and create a function in the module file with that name. The page-specific help information appears on help page. The module overview help information is displayed by the Help module. It can be accessed from the page at admin/help or from the Modules page.

hook_help($path, $arg)

Parameters 

$path: The router menu path, defined in hook_menu(), for the help that is being requested; e.g., 'admin/people' or 'user/register'. 

$arg: An array corresponds to return value of the arg() function, for modules that want to provide help that is specific to certain values of wildcards in $path. 

hook_permission - Create permissions associated with your module. 

Description: This hook gives permissions to the module, so they can be selected on the user permissions page and used to Allow or Restrict access to the module so that certain roles can access pages, i.e. the 'Administrator' to change settings or certain role to view the page. It returns nested array.

hook_menu - Define menu items and page callbacks. 

Description: Adding a module configuration page to Drupal menu is an important task.This hook enables modules to register paths for URL handling. They can be used to register a link to be placed in a menu. A path and its attributes called as "menu router item". This hook is rarely called (for example, when modules are enabled), and its results are cached in the database. 

hook_menu_alter - Alter the data being saved to the {menu_router} table after hook_menu is invoked. 

Description: This allows us to alter elements in Drupal's menu system. The primary links, secondary links, tabs and page callbacks can be altered in this way. 
Alter the data available in {menu_router} table after hook_menu is invoked. 
The menu definitions are passed in by reference. Each element of the $items array is one item returned by a module from hook_menu. 

hook_cron - Used for carrying out actions when the cron runs. 

Description: hook_cron() provides a powerful, simple, and useful tool for background task processing independent of page requests. 
The Drupal will call this hook whenever a cron run happens.Tasks managed by hook_cron() are database maintenance, backups, recalculation of settings or parameters and automated mailing.

Short-running tasks can be executed directly whereas Long-running tasks could time out, so that we should use queue API instead of executing the tasks directly. To do that first we need to define one or more queues via hook_cron_queue_info(). Then, add items that need to be processed to the defined queues.


hook_form_alter - Perform alterations before a form is rendered. 

Description: Changing / Adding  element to the existing form structure is One of the popular use of this hook, the node object can be accessed at $form['#node']. One of the benefits of using the Form API to construct forms is that any module can alter any other modules form. 


hook_form_alter(&$form, &$form_state, $form_id) 

Parameters 

$form: Nested array of form elements. 
$form_state: Current state of the form. 
$form_id: String representing the name of the form itself.
 

hook_form_FORM_ID_alter - Provide a form-specific alteration instead of the global .

Description: This  hook can do similar task as compared to hook_form_alter, only difference is that instead of making global hook_form_alter(), it uses form specific hook. Applied only to specif form. Rather than checking form id or using long switch statement to alter individual form.

Parameters 

$form: Nested array of form elements. 
$form_state: A keyed array containing the current state of the form. 
$form_id: String representing the name of the form itself.

hook_theme - Register a module (or theme's) theme implementations. 

Description: Reason behind implementing hook_theme under a custom module or theme is to register theme implementations which specify how a particular array should be rendered as HTML.

We've now hooked our module into the theme system. Let's look at what these items do: 

'my_custom_template' => array(): This is the name of Template. 
'template' => 'custom-page': This key-value pair will call to a new template file that will look like this: 'custom-page.tpl.php'.

hook_theme($existing, $type, $theme, $path)

Parameters 

$existing: An array of existing implementations that may be used for override purposes. This is primarily useful for themes that may wish to examine existing implementations to extract data (such as arguments) so that it may properly register its own, higher priority implementations. 
$type: Whether a theme, module, etc. is being processed. 
$theme: The actual name of theme, module, etc. that is being being processed. 
$path: The directory path of the theme or module.

7 Things you need to know before expanding to a Multilingual Website

For a Digital Media website, expanding business to another language is a quite challenging and tough task to deal with. It makes you re-evaluate your CMS . A lot of questions come forward while you take the decision. Firstly Why? But now that you know you want to translate, you think, What all should we translate? How will we handle pages in default language? What components do we add? What services to use and how to maintain pages?

A major chunk of content these days is written, managed and stored with the help of a CMS or Content Management System (CMS). Selecting the right CMS at the beginning of expansion into a multilingual site ensures that the website and its contents are effectively managed and displayed right from the beginning.

# 1 What  is the potential of a Multilingual Website?

It is no more a shocker that the global organizations which manage Digital Properties support multiple websites in multiple languages which is much more difficult done than said. In today’s market there exists a lot of choices for one to select a CMS,but very few which allows easy editing of content and full edit options, most importantly ease of use for the users. Drupal comes with powerful multilingual feature.

#2 When is Drupal the right fit for your need?

Drupal 8 comes with a ton of features to perfectly suit your best needs, it has evolved over time and has solved a lot of complexities from Drupal 7 and its Multilingual capabilities are come in-built in core. In my previous blog post, we discussed about the need of Multilingual website and the right time to go for it. In short When you have a media website with visitors from language background other than your default, it’s best to switch to a multilingual website to ensure you do not lose your business and have a continuous growth.

#3 Why Drupal is exactly what you need?

With a website which has the capability to shape itself to the language of choice across any platform is the need of the hour. Drupal 8 comes with this powerful feature which will enable your business to reach to a larger audience. It comes with a powerful multilingual feature which helps translation into regional content and local languages and can be easily implemented. The multilingual feature comes with more than 90 languages and is applicable to all fields, forms and messages. Not only this but it also comes with a built-in translational core. Assets, like files or images, can have be assigned to a language or shared.

The challenge with translating sites with Drupal is none. It requires very less manual work. Once you add more content, all of it is scalable, it can cope and perform under a demanding workload. A system which scales well will be able to maintain or even expand its level of performance or experience when tested by larger operational demands which media sites go through more often than any other sites.             

Multilingual Site

 

#5 What makes Drupal special for Multilingual Websites?

It is quite different than the popular CMS translation plugins. It doesn't make you waste time on creating new pages, new menus and so on. It also doesn't only translate "content", it lets you translate all things that you "see" on the front-end of your site (including text,forms, error messages and more). Drupal 8 hands out extensive multilingual features right out of the box. The admin interface has built-in translations.             

Translate all things

Translate all things

It is Multilingual first: Auto-detection of language and auto-downloading latest interface translations             

Multilingual first

 

# 6 What things allow translation?

Drupal 8 allows all components from configuration settings to menus, views and field values.  It allows user to select operations based on language options.            

Translatable entities

For content entities like taxonomy, nodes and users it is also possible to change visible language selector options to default or of another language.

#7 What are the Key Features?

Improved functionality of Multilingual is the another feature of Drupal8. With Drupal8 you can:

  • Multi-Translate all things in the system which has built-in user interfaces.

  • Build web pages with Views language filtering and block visibility.

  • Get automatic software translation updates from the Drupal community.

  • Add a language selector to your site

  • Auto-determine the visitors language.

  • Choose what not to translate

  • Install in 94 languages

  • Overview screen for translators, contextual translation tabs for site builders

  • Protected local, custom translations which are exportable

  • English can be removed, no more to be default

Having a website work it’s inside out in Multiple languages has never been smarter and more user - friendly

The team at Valuebound has experience of working on high-traffic multilingual Drupal websites. If you're looking for getting an understanding of how your website will do in Multilingual, let us know.

 

Learning about Form & Field Validation in Drupal 7

This article is to share my experience with Drupal CMS. It will be helpful , particularly for novice/beginner level Drupal programmers to build their knowledge block on Drupal framework. Even though you might be aware of a few functionalities mentioned, this article will guide you on the basics of ‘what should be used’, ‘when to be used’ and ‘why to use’.

I have started blogging again after a brief break to share my knowledge of Drupal. Before getting into any of the technical aspects, I would suggest you to try and understand the ‘How & why?’. This will help you concrete you knowledge about any form of technology. So let’s begin with a functionality instance of Drupal called “validation”. 

Terminology will be used in most of the forms where the end user has  the required data with self and is ready to validate the same before submission. It gives assurance that the data posted to table does not have any miscellaneous data. Proper validation of form data is important to protect your form from hackers and spammers.

Types of validations that we can perform on form:

Validate Drupal form using validate function

hook_form_alter() : By implementing hook_form_alter to the specific bundle and calling $form['#validate’][], it will list all of the validation functions for a given form. Here we can add our custom validation to the validation handler array using $form['#validate'][].

When you hit the node/add/* , you will find node_form_validate(), which is the core validator for node forms.

form validation tutorial 0

The above validate_handler would be useful when it comes to an existing node type, where the developer has full access to insert validation for a form using custom module.

Validate only Drupal form field element using custom function:

We don't need to add an entire form validation every time. We can add a validation handler for an individual form element using #element_validate. We can also construct our own element validators. 

To validate a specific field, we can use #element_validate, with the element specific validation function which will pass $form_state and $element.

Use a pre-defined validation handler to validate numbers/integers.

form validation tutorial 1

Instead of handling the entire form, #element_validate helps to trigger a specific field  validation and displaying custom error message.

Validate Only Individual form element with pre define validation handler:

Drupal has a lot of pre define validators. The only thing is that either we are not aware of it or we haven't used it before.
When you want to validate a number with a predefined handler, you don’t have to add the validation function as it already exists.

Drupal has already defined a handler that validates if the data is a number, called element_validate_number. So we need to add the following to our form element:

Just one line of code can handle validation. Here is a list of  pre-defined validation handlers.

  • date_validate - Validates the date type to prevent invalid dates (e.g., February 30, 2006).
  • element_validate_integer -Form element validation handler for integer elements.
  • element_validate_integer_positive - Form element validation handler
  • for integer elements that must be positive
  • element_validate_number - Form element validation handler for number elements.
  • password_confirm_validate - Validates a password_confirm element.


     form validation tutorial 2

     

An individual form element handler with pre define core function, does not allow you to write custom error messages. As of now there are a list of functions available to execute basic validation over form.

Validate function using _form_validate from drupal API

We can add custom handler to validate the data entered into the field.
NOTE: Name of the function. It is simply the name of the form followed by '_validate'. This is always the name of the default validation function.

form validation tutorial 3

Default drupal core provides hook to handle field validation. And the pattern is form_id_validate() where we can set our own message. 


Conclusion: Above methods are small pieces of validation towards entity and bundle field. Based on best practice and specific project requirement validation, handler should be used. 


GIT Source Code: https://github.com/xaiwant/D7validation/tree/master/article_rule

6 things to consider before you switch over to your new ECM system

Organized management and a good visual of your content gives you an edge over your competitors and this feeds the concern over when you should migrate to your new Enterprise Content Management (ECM) System . The whole process requires a huge capital investment and do not forget disrupting your business which can in turn spoil your customer’s digital experience. Before you go looking for a new ECM system to develop your new platform, you should consider an assessment of your current system that takes a comprehensive view of your current tools and processes. This assessment will cover a similar ground as the ECM system selection process and also gives the possibility that the best platform may be the one you already have.

If you go to a grocery store hungry, you will end up buying things you don’t actually need. Most smart people avoid this by making a list of essentials. When it comes to selecting a new ECM system, documenting your needs is an absolute necessity. Comparing your existing ECM system to the functionalities  you are hoping for, is a matter of magnitude. By considering each area carefully, your organization can make the best strategic decision possible and get the most value from the ECM system you implement. Now assessing the implementation is the matter of measuring this magnitude which we cover in the following six points:

  1. Integration of ECM system with your Business process

    The main aim of integrating your business with an ECM system would be to content-enable the business applications so that the latest and most accurate information is readily available.

    Unstructured content can be scattered across various repositories which can happen due to individual applications having their own stores for related information.

    Significant cost savings can be achieved when the core business applications are organized and content enabled. This improves efficiency(Fig 1.1) and reduces reliance on paper and also lowers physical storage.

    Business drivers for document and record management

    Fig 1.1: The most significant business drivers for document and records management (Source: AIIM, State of the ECM Industry 2011)

    Although the ability to organize and structure pages is not required now, it might be needed in future. Always look out for CMS which do not allow flexibility for such core tasks.

  2. Core ECM Capabilities

    As the company grows, so does the variety of content that needs to be archived and content that needs to be disposed off. A good ECM system should be able to manage the entire lifecycle of various content types and support other processes like search, retention and rendering associated with the content types and also let you define each step of the content’s lifecycle.

    Records Management and retention policies helps control the creation, classification, declaration, retention, and destruction of content and records, resulting in improved compliance, minimum litigation risk, and lower storage costs.

    Basic functionalities to consider include:

    • Search- full-text search, filtered search results for end-users to quickly find what they have authorized access to, and advanced search capabilities like custom search forms and metadata search.

    • Metadata, Classification and Taxonomies- Support for automated, manual and inherited metadata values on all types of content and classification of content based on these values.

    • Versioning-automatic tracking and storage of each file version along with auditing, archiving and the ability to revert to a previous version of a document if needed.  

    • Rendition support-the ability to automatically generate content in other formats (PDF, XML, HTML).

    • Compound document support – to allow smaller documents to be incorporated within a master or parent document.

  3. Ease of Access (multi-channel content creation & consumption)

    A good ECM system allows your employees or users to access information from various devices. These days it is important to make your information accessible through mobile devices. Whether it is for intranet, ethernet or mix of both, access to content in this context adds significant value.

    A CMS implementation has three primary requirements: developer’s needs, user experience and the content author’s needs to maintain the user experience.

    The user’s and developer’s needs usually become the focus of an ECM System implementation, but the process doesn't end when it goes live.

  4. Content Authoring Workflow

    The CMS of choice should also have expandable workflow capacity to meet the future needs of your business. Analyzing the workflow of your organization helps you select a better suited ECM System.

    If your authors face difficulty  working with your new ECM System, it’s implementation might not serve your purpose well. A discontent from the author community will affect the business as your system is starved of new content  and you might go through another cycle of a new CMS implementation.

    Encourage author adoption of the new ECM System by both training and considering various functionalities of your new ECM System that your authors require.

    These functionalities can be types of content that can be submitted, provision of author tools (eg: SEO, spell check, standard taxonomies, compliance tools, auto-complete of metadata items), a suitable permission model to hide irrelevant features from the author etc.

  5. Enterprise-Class Capabilities

    The ability of an ECM System to grow and adapt to your business’s growing needs in a way that it does not bring up limitations is one critical factor to be considered. Also, it should not add significant support costs in  future.

    You new ECM system is going to be the information backbone of your company and should meet certain requirements:

    • Scalability- It should be able to scale thousands of users and billions of content types and also manage the lifecycle of these information efficiently.

    • Security- Admin’s ability to define access to various types of information based on the type of user, different groups across the organization or an end user. A good ECM System will have data encryption and restrictions on database access to provide optimum level of security.

    • Managing,Auditing and Reporting- A unified administration has better manageability and lower costs. Having a lone platform that allows an admin to manage all the information, services and reports and logs from a single console reduces staffing requirements and improves compliance by eliminating the creation and enforcement of redundant policies and procedures.

    • Multilingual support- To reach the world wide audience an organization requires localization support for a number of languages and the ability to adapt to different time zones.

    • Service Oriented Architecture (SOA)- The ECM System’s ability to integrate with various types of systems is essential to ensure that your content is readily available across the enterprise.

  6. Strength of Vendor

    You ECM system provider should have the commitment, longevity and the financial strength to be your business partner for years to come. While evaluation a suitable vendor, you should consider:

    • The available educational and training materials
    • Training personnel
    • Availability of global tech support.
    • Ability of address issues in a timely manner.
    • Availability of other implementation partners and subject matter experts globally.

Conclusion

Whether you are considering an upgrade to your current ECM System, a replacement of an older system or the purchase of a completely new ECM System, there are many important criteria involved in electing the best content management system suited for your organization. Apart from the 6 points mentioned here there might be other requirements which will build your list further. We hope you find this useful and consider Valuebound to build your future. More information on our work is available at Valuebound.

Valuebound sponsoring BAD Camp 2016

BADCamp is a Drupal conference for the people. It’s an annual celebration of open-source software in Berkeley CA. We at Valuebound, are thrilled to be sponsoring BADCamp this year, to be held on October 20-23. We are excited to welcome more people be a part of BADCamp inspiring sessions and community!

 

Badcamp VB

How to Create Custom field in Drupal 8 (Part -1)

In a recent project we had to create a section that is having range  with the select list for the unit. It had to be usable in different sections of the layout and work the same. For this we came up with a pretty nifty (we think) solution of creating a custom field that solved this particular problem for us. I will walk you through how to create a custom field/widget/formatter for Drupal 8. There are Drupal console commands for generating boilerplate code for this…

To Create Custom field we need to create 

  1. Field Type
  2. Field Widget
  3. Field Formatter


This is the folder structure for creating the same

Temperature Range

  • temperature_range.info.yml
  • src/
    • Plugin/
      • Field/
        • FieldType/
          • TemperatureRangeItem.php
        • FieldFormatter/
          • TemperatureRangeFormatter.php
        • FieldWidget
          • TemperatureRangeWidget.php

Field Type creation
First, we need to create our own custom module, we can use drupal console for creating new module, then 

The namespace of that class should be \Drupal\MODULE_NAME\Plugin\Field\FieldType
In our example \Drupal\temperature_range\Plugin\Field\FieldType\BazItem

To create a field type, you need a class with the FieldType annotation.

The annotation above the class, within the doc comment, should include a unique id, and a label.

Then provide a schema for the field. This will be the properties that we have created above.

Then provide the field item’s properties and this will be the properties which we created

In the forthcoming blog, we will see how to create field widget and field formatter which both will complete the custom field creation

Get your Drupal8 Development platform ready with Drush8!

As we all know, we need Drush8 for our Drupal8 development platform. I have tried installing Drush 8 using composer, but sometimes it turns out to be a disaster, especially when you try to install Drush 8 on the Digital Ocean Droplet having Ubuntu 16.04.

I have faced the same issue in the last few months to get the Drupal8 development platform ready with Drush8. So I have decided to find a solution to fix that forever. Well, finally found one which are the following lines of commands.

cd  ~
php -r "readfile('http://files.drush.org/drush.phar');" > drush
chmod +x drush
sudo mv drush /usr/bin
drush init

If you are still facing any issue, please leave a comment, We will help you out to get your platform ready with Drush8.

When should your Digital Transformation journey include a Multilingual Website?

When you have a media website with visitors from a language background other than your default, it’s best to switch to a multilingual website to ensure you do not lose your business and have a continuous growth.   

Do you have website visitors from non-English speaking countries?

Do you know there are more than 40 Million native Spanish speakers in the USA out of which 72% prefer websites in their native language?  Then there is Chinese, French and so on to name some of the most popular language based users which add up to 75% with English being only one-fourth. What are you doing to target these 75%? Why not zoom in on the less focused and make loyal customers out of them? To them, you are not just another digital media company delivering the same old content from places they don’t relate to, to them you are more of their national daily.

How do you cater to your web visitors if they are non-English Speaking users?

Do you display the content in the same default language? You might have translated the content but then there is page layout, word spacing and expansion and contraction per language requires you to have a site which can handle such flexibility

Are you equipped to make changes for every new language that you add to your list?

Adding a new language to your website comes with challenges. Are you looking for answers that handle the complexity of language translation requirements? Are you thinking how to organize your content? You have blogs, headlines which link other articles together, out of that what all can be translated and shown to the users? All of it or only the basic content?

Will it affect to have an interface that speaks the language of your target market?

Of course, your website does not target people of one language. And having a monolingual website gives you a limited audience, which is a loss for your business. Hence it is about time for you to customize your website to accommodate new languages

What factors are keeping you from growing your business?

One aspect of getting feedback or suggestions is through forms. Forms are a critical part of your website through which users can connect with you, having a form page that displays only in one language is going to hamper business for you. It is, therefore, important that the forms are easy to use and presented in the user's’ native language.

With the boom of devices and screens available to consumers, people now have unhindered access to every content they want, the way they want, with a special focus on their favorite brands and sites. This sets the standard higher and creates a necessity for the brands to deliver the best of experiences — with no regards whatsoever to the device, size, screen, mobility or any other point of contact, here the experience matters because your customer’s expectation is high. As a matter of fact, the standard keeps getting higher and higher that it because some of the brands like yours have been setting an example for the others to follow.

Why do you need Multilingualism?

With the internet crossing the 10k day this past week, from the time it was invented the world of publication likewise has undergone drastic changes, we swipe our finger to turn the next page of a book and scroll the site to take a look at the news headlines. It is no more limited to one part of the world and people from all regions and languages have access to what you write.

Writing is digitally accessible and digitally published. Businesses are gearing up to reach and penetrate through every corner of the world and here is where localization comes into the picture. Your diversified and multilingual global society has immensely added to the importance of translation in the publishing industry. Media and publication industry needs to reach out to various geographical regions having its own distinct language.

The world of media and publishing witness rapid changes and is regularly making way for a broader audience. Most multinational media companies are already on the path of this transition to secure an international foothold. Whether you choose to go down this path now or later is the only question.

The team at Valuebound has experience of working on high-traffic multilingual Drupal websites. If you are still wondering if Multilingual is the right way to go, we can help you make this decision.

References -

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch