How to use DI with simple objects? I have a simple class to which I am providing some values via constructor and I would like to use DI. This class has no relation to Drupal(not a plugin, form, entity,...).

It serves as a wrapper for dataset where I need to do some data manipulation by using few services.

I wanted to use the ContainerInjectionInterface but it only has the create() method and it does not look like it can be used for this purpose.

Can the DI in D8 even be used for this purpose?

Yes. Just require the services you need in your constructor, and wherever you create your object, pass them in.

That is the very definition of dependency injection.

The container/services are just a way to describe your dependencies to the environment/Drupal so it can do that automatically but that is in no way a requirement.

What you probably want to do is to use the factory pattern, so that you have a factory, which you can define a service, which offers a method to get your value object with the necessary services injected. Drupal 8 has various examples for the, for example KeyValueDatabaseFactory (keyvalue.database), which has a get($collection) method. Each call creates a new object, passes the dependencies that object needs to it and then returns it.


How can I add a CSS class to a View Field programmatically? Using template_preprocess_field doesn't work, I assume, because this is a field from a View, not a node.

I've looked at this answer however that only seems to apply to the field value not the markup and styles surrounding it.

For example: The output of the field in markup is currently:

        Active

I'd like to conditionally add classes:

        Active

You can add any css class, HTML tag to any field through views admin UI, why don't you add the class from there?

UPDATE

Because you need add the css class based on some condition, you have to use the following preprocess function. your code is going to be some thing like this (maybe a few modification will be needed )

function mytheme_preprocess_views_view_field(&$vars){
     $view = $vars['view'];
    if($YOUR_CUSTOM_CONDITION == TRUE && $view->name == VIEW_NAME)
           $vars['classes_array'] = 'my-conditionally-added-class';
}

because you output the content on views you have to use mytheme_preprocess_views_view_field function.

For more information visit Themeing Views field output with Preprocess function.


Why would a view be displayed differently in different software? Using Drupal 7 and the Views PDF module, I have created a PDF output that looks perfect when opened in a browser, but is inconsistent everywhere else: On Chrome, Firefox, and Edge it is displayed exactly as designed; on
Acrobat Reader, it shows only a table background color, the rest is blank, and there is no text; on iPad and Outlook, it displays a blank white screen.

What would cause the PDF to display perfectly in a browser and horribly in everything else?

Ironically, the PDF document format was designed to display the same everywhere ... but that's an overly ambitious goal.

First note that "in the browser" isn't especially meaningful - different browsers, with different configurations, will use different engines to display the pdf.

Your different experiences are due to those different engine(s) in your browsers vs. the acrobat reader engine, which is perhaps also used for your ipad and outlook.

My best guess is that your browsers have access to some non-standard fonts that you're using in the output, but the other engines don't. Getting the views pdf to embed those fonts, or using standard fonts instead, will probably fix it.


How do I append something to a node when it's in detail page I'm writing a module that appends content to a node. I'm doing this using hook_process_node :

function mymodule_preprocess_node(&$variables) {
  $variables['content']['body'][0]['#markup'] .= '
My content
';
}

How can I put a condition here to tell Drupal to only append content when the node is being displayed on a detail page, i.e. not in an index page?

If by "detail page" you mean the full node page, you can check the current view mode:

if ($variables['view_mode'] == 'full') {
  // ...
}


Does drupal_get_path_alias only work if you are requesting a page, or can it also work if you are requesting a form? Does drupal_get_path_alias only work if you are requesting a page, or can it also work if you are requesting a form? For example:

drupal_get_path_alias(node/1);

works fine, but the below doesn't

drupal_get_path_alias(node/1/edit);

so the user sees a mixture of aliased and normal paths. Could I have:

content/todays-news

and

content/todays-news/edit

Thanks

For Drupal 6 there was a Sub-path URL Alias module.

  The Drupal Path module matches only full URLs when creating SEO-friendly aliases. This module extends that behavior by also matching known sub-paths and replacing them with their respective alias. For example, if node/1 is aliased to content/alias, this module rewrites the link to the node edit page node/1/edit to use the aliased URL content/alias/edit instead. This also includes Views URLs taking a node as argument (node/%/yourview), in short, every URL that is based on, or extends, an existing alias. In combination with the Pathauto module it is possible to get rid of all remaining exposed internal URLs.

I'm not sure if there is any for D7. If not porting it would be the option to go for.


Can this be achieve by attributes? I am thinking of setting a product that is only valid from a period of time eg:

product a from 15january2016 til 15january 2018, upon this setup it will be available from that period of time.

also when creating the product a, I can set the time of the product available more of like a timeslot like :
9:00am - 10:00am - 3booth
10:00am -11:00am - 3booth
etc

user will be able to choose more than one.

example :

A buy 9am-10am - 3booth
A also buy 10am-11am - 1booth

so A can buy 3stock from a timeslot and also buy another timeslot with only 1 stock. and how do we proceed with this option? can product attributes help?

this product is going to be available daily.

more of like selling practice session.

my question are :
can this be achieve by attributes? for timeslot? and since there is only 3 classes, and this each class can only be taken by one person 1hour, is there any solution for validation of stock?

I am brainstorming of doing custom attributes but can not get away of thinking how to handle the stock of the class available or not?

some ideas would be great

thank you!

The following four fields would be easily possible for making "timeslot" products:

Start - date field, single date (not a range)You want a single date field because views will be more straightforward when not dealing with ranges on one field. It's much easier to do two fields and have two filters than it is to have one field with a range filter (date supports both use cases).
End - date field, single date (not a range)
Timeslot - Product title would be easiest OR taxonomy reference The taxonomy route would allow you to make the timeslots fieldable and help you connect products of the same timeslot (if it is helpful to have all 9am - 10am products in a single list).
Stock - You could use commerce_stock to create a single stock availability OR you could just disable the product on checkout.

So, the simplest route would only include a "start" and "end" date field with the product title being the "timeslot" and using the "status" of products as a simple "single availability" flag.

Hope that helps!


How to disable "Plain text" for a specific role? I see that from admin/config/content/formats/plain_text I can not disable it for a individual role. How can I do this?

UPDATE:
I can change the attributes of the format and rename it, however I see no way to change the machine name of the format. It should be a better way to achieve this.

Better Formats module will allow you to select the default input format per role, and disable the formats selection part of the node edit form http://drupal.org/project/better_formats


How are hooks implemented? Are hooks a thing in their own right, or are they actually implemented as events under the hood?

Hooks aren't Symfony events. They are PHP functions with a specific name that Drupal calls in very specific cases.

For example, hook_cron() is invoked when Drupal cron tasks are executed, from Cron::invokeCronHandlers(), which uses the following code.

  // Iterate through the modules calling their cron handlers (if any):
  foreach ($this->moduleHandler
    ->getImplementations('cron') as $module) {
    if (!$module_previous) {
      $logger
        ->notice('Starting execution of @module_cron().', [
        '@module' => $module,
      ]);
    }
    else {
      $logger
        ->notice('Starting execution of @module_cron(), execution of @module_previous_cron() took @time.', [
        '@module' => $module,
        '@module_previous' => $module_previous,
        '@time' => Timer::read('cron_' . $module_previous) . 'ms',
      ]);
    }
    Timer::start('cron_' . $module);

    // Do not let an exception thrown by one module disturb another.
    try {
      $this->moduleHandler
        ->invoke($module, 'cron');
    } catch (\Exception $e) {
      watchdog_exception('cron', $e);
    }
    Timer::stop('cron_' . $module);
    $module_previous = $module;
  }

A module whose machine name is spam_checker could implement this hook adding the following function to its code.

function spam_checker_cron() {
  // Delete the nodes from the list of nodes to check after 96 hours are passed.
  Drupal::database()
    ->delete('spam_checker_list')
    ->condition('timestamp', REQUEST_TIME - 3600 * 96, '<')
    ->execute();
}


How to export complete products data to csv file We have a Drupal Commerce site, and need to dump all the products data into another CMS. I checked the question, How to export drupal commerce products?

After trying the Views Data Export module, I didn't find any option for CSV, Excel in the display.

What am I doing wrong?  I would like to export data to a CSV file or any other document so that I can easily import those products into Magento.

Try Views Bonus Pack module too. You can see an option "Data Export" while adding a display in the view.


Entity_Token breaks token my tokens I've got an issue after I installed entity_token module (Drupal 7)

Now I can't really open admin interface in Drupal that contains tokens.

That is how tokens are displayed without entity_token

That what happens after I install this module

I've google a bit about it and what I only found is that:
https://www.drupal.org/node/1203018
https://www.drupal.org/node/1058912
https://www.drupal.org/project/token_tweaks - sounds like a module that fix this issue (which logically for me sounds really wrong, module that fix another module).

My question is what to do :)
Please suggest if I've to go with module or patch or there is better way to fix it.

I ended up with decreasing Token's limit (see images below)


Webform table element and Webform I am trying to create a form with essentially form elements stored inside a table. After digging around,  have two alternatives:

1) Install Webform module along with the Webform Table Element module. Now both modules have been enabled and have cleared the caches for the heck of it. I can make the Webform alright, but I don't know how to make use of the Webform table element module and make the webform contents appear within a table. So I am not sure how to go about doing this

2) (SIDE QUESTION):  The other alternative is to create a custom module that would let me build my own form with tables and all that jazz. But I am keen on learning the Drupal way although I always prefer hand-coding my challenges.

Drupal has theme() which can be used to create a table in a form. Your theme function must be registered with hook_theme().

function MODULE_NAME_theme() {
  return array(
   'MODULE_NAME_header_menu' => array(
     'arguments' => array(
       'form' => NULL,
      ),
   ),
}

function theme_MODULE_NAME_header_menu($form) {
  $rows = array();
  foreach (element_children($form) as $key) {
    if (is_numeric($key)) {
      $wt = $form[$key]['weight' . $key]['#value'];
      $menu_title = drupal_render($form[$key]['title' . $key]);
      $row[] = array('data' => $menu_title);
      $href = drupal_render($form[$key]['href' . $key]);
      $row[] = array('data' => $href);
      $weight = drupal_render($form[$key]['weight' . $key]);
      $row[] = array('data' => $weight);
      $remove = drupal_render($form[$key]['remove' . $key]);
      $row[] = array('data' => $remove);
      $rows[$wt] = array('data' => $row);
      unset($row);
    }
  }
  // Individual table headers.
  $header = array();
  $header[] = array('data' => t('Title'), 'class' => 'menu-title');
  $header[] = array('data' => t('URL'), 'class' => 'menu-href');
  $header[] = array('data' => t('Weight'), 'class' => 'menu-weight');
  $header[] = array('data' => t('Remove'), 'class' => 'menu-remove');

  $output = theme('table', $header, $rows, array('id' => 'header-menu-table'));
  $output .=  drupal_render($form);

  return $output;
}

This creates a table with three columns (if the form has three numeric array keys: "title", "href", and "weight") plus a fourth column with a "remove" link.


Variable saved as string, not as integer I have a problem when updating a variable with return system_settings_form($form) - Basically, I store a variable as an integer, but when I press Save configuration, it works very well except that it saves the variable as a string, not an integer.

Here's my function:

function my_module_settings() {
  $form['my_variable'] = array(
    '#type' => 'select',
    '#title' => t('My module variable'),
    '#description' => t('Update my module variable.'),
    '#options' => array(
       1 => t('Set it to 1'),
       2 => t('Set it to 2'),
       3 => t('Set it to 3'),
    ),
    '#default_value' => variable_get('my_variable', 3)
  );
  return system_settings_form($form);
}

So, if I select "Set it to 2" in the select list and hit save, I'll be getting number 2 surrounded by quotes ("2"). I've confirmed with PHP gettype that there's indeed a change of data type.

I wonder if it's related to the select list or something foolish I'm doing? I've tried using a checkbox instead and data type is correctly updated as an integer.

I've been scratching my head without finding a correct solution. Any idea what's going on?

It probably has to do with how php handles POST values.

That is just generating a form element, which when the form is saved will get sent to the server as a string. Here's an attempt at phpfiddle to show you what's going on: http://phpfiddle.org/main/code/dmk-npy.

Basically you're either going to have to intercept the form submit and cast the variable to (int) there, or you'll need to cast it to an int when you're pulling the variable out.

Edit: Though I have no idea why your checkbox would be saving it as an integer.


Aegir no longer seems to be adding SSL info to apache config files for sites I am using hostmaster 7.x-3.171 and I am using the legacy SSL option (apache SSL - not apache HTTPS)

When i check the apache entry for the site in question at

/var/aegir/config/server_master/apache

it is missing the 443 entry and only has an entry for port 80 stuff.

I have double checked the site settings in aegir and SSL is enabled and a certificate is selected. I have tried to verify the site and no errors are presented. This seems to happen only if I try to verify a site that has SSL enabled. Maybe an update broke this somehow? I haven't done anything to mod the aegir set up that i can think of.

Has anyone had a similar problem recently in aegir? Any help would be appreciated!

Is there any particular reason why you're using the legacy option, and not Aegir HTTPS?

The legacy option is no longer supported so my recommendation would be to follow the documentation to switch.


Admin Module with highly customized UI I have a web app with a complex database that I created for a previous project. I'd like to integrate that old project into my new drupal site. I don't need it to be fully drupal-ized, but I need to at least leverage drupal's user authentication.

I'm trying to find a good tutorial about creating a module which provides an admin page and has a very customized UI. I don't need drupal to create form items for me. Any suggestions?

My UI fetches and updates all of its info via AJAX, so I need each of those AJAX calls to be at least minimally managed by drupal for user authentication purposes.

Does that make sense? Any suggestions?

Have a look at hook_menu(). It's the cornerstone to define pathes and who has access to them.

In drupal you define a path by implementing hook_menu in a custom module. There you define what php functions are called and what user roles do have access to it. This way you can route your AJAX calls through drupal autentication and authorisation.


Alter login form redirect doesn't work I have user login block on custom page, I try:

if ($form_id == 'user_login_block') {

    $form['#redirect'] = '/';//or <front>

}

But I am redirecting always to the same page.

The user login block form is a special case.  You will see that in the #action property, it defaults to /node?destination=node.  The "destination" is the important piece, as it will override many of the normal avenues you would take to redirect the form including a $form_state['redirect'] in a submit handler.  The code below is an example of how you can redirect the user_login_block form by modifying the #action property.

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ('user_login_block' == $form_id) {
    $path = 'path/i/am/redirecting/to';
    $form['#action'] = url($_GET['q'], array('query' => array('destination' => $path)));
  }
}

Also, take a look at hook_form_FORM_ID_alter(), which is the preferred method for altering the form for performance reasons.


Drupal fancybox views gallery - display only first item of attached images I have multiple images attached to a node that act as a gallery using fancybox.
In views I am attempting to only display the first attached image.

The idea is to only display the first image then when clicked, fancybox will go into gallery mode displaying all subsequent attached images.

I have tried the 'Group multiple values' showing '1value' starting from 0.

This works for only displaying the first item, but unfortunately when clicked fancy box does open but not in gallery mode. It just displays the first item.

What i need to do its open all attached images as a fancybox gallery but from only the first item.

Any help or ideas would be much appreciated.

Use the display CSS properties.

.field-content ul li{
    margin:0;padding:0;
    display:none;
}

.field-content ul li:first-child{
    display:block;
}


Dates disappear on 'Edit' We are still on Drupal 6 which has worked fine for years, and I have not done any updates.
We have Date/Time boxes on our "Events" items with pop-up boxes (see image).
But since recently the when you 'Edit' an event the dates/times go blank, but they didn't use to.
We've done nothing to alter the setup at all!

It is not only annoying, but as the 'Front Page' is set to Chronological order, if the date is blank the event disappears (past it's date presumably), so the author can't even see it to notice & correct it!

There is another question similar "when using Scheduler......"
The only answer was "it must be a bug - report it"  BUT it used to work fine, and we have not changed or updated anything (I don't know how to!)
Apart from this the site works fine!

I am not a Drupal programmer so don't ask me to update any code!
I presume it must be a 'setting' somewhere, or could it be to do with lack of memory????

one image is date/time boxes as they appear on editing, the other image is how they look when the event is first posted (or when dates re-entered)

Mike

Try looking at yoursite.ca/admin/build/themes/settings.

When there, check that under "Display post information on" that your content type is checked.

After looking at this, it seems like a bug in the date module. Try updating the date module, but make sure that you have a backup of the site before doing so.

You should also soon upgrade to Drupal 7 or 8, as Drupal 6 sites risked being hacked.


Setting up subdomains, confused on "Settings.php" / "web.config" setup First, I'm using shared hosting.  I've set up the DNS so I have one.example.com, two.example.com, etc.  Each subdomain works properly, but they use the default page.tpl.php/look exactly the same as my front page.  I'm assuming the next step is to configure the settings.php, web.config, and to create preprocessed theme hooks.  Is there a good D7 tutorial on how to do all of this via "subdomains"?

Also, I'm planning on using the "Domain" module.  I've got it properly configured.  But, don't really see a point in using it until the above mentioned is setup properly.

Instructions for multisite installations are in sites/default/settings.php. To quote from that file:

  For example, for a fictitious site installed at http://www.drupal.org/mysite/test/, the 'settings.php' is searched in the following directories:

  sites/www.drupal.org.mysite.test
  sites/drupal.org.mysite.test
  sites/org.mysite.test
  sites/www.drupal.org.mysite
  sites/drupal.org.mysite
  sites/org.mysite
  sites/www.drupal.org
  sites/drupal.org
  sites/org
  sites/default

  If you are installing on a non-standard port number, prefix the hostname with that number. For example, http://www.drupal.org:8080/mysite/test/ could be loaded from sites/8080.www.drupal.org.mysite.test/.

The lookup can be changed as described in sites/example.sites.php:

  This file allows you to define a set of aliases that map hostnames and pathnames to configuration directories. These aliases are loaded prior to scanning for directories, and they are exempt from the normal discovery rules. The aliases are defined in an associative array named $sites, which should look similar to the following:

$sites = array(
  'devexample.com' => 'example.com',
  'localhost.example' => 'example.com',
);

  The above array will cause Drupal to look for a directory named "example.com" in the sites directory whenever a request comes from "example.com", "devexample.com", or "localhost/example".

BTW: multisite installations are usually done to facilitate using different databases.


Using Migrate API, is it possible to UPDATE entities on subsequent imports? I am using Migrate API with Migrate Plus, Tools and Source CSV to create Commerce Products from a CSV file. The CSV file will be updated daily where the product info (prices, stock level, etc) may change. As far as I can tell, Migrate doesn't recognize changes to the source of existing content once it's been imported.

Is there a way to re-import a file and pull changes to the file (source)

Got the answer:

add --update to your drush command (drush mi your_migration --update)


What field is Views using to determine the pager 'offset'? When I use Views > pager > 'items to display' and set the offset value ... what field is Views using to determine the pager 'offset'? Is it 'post date'?

How can I change the offset to use a different date field that I've created?

It offsets by row.

If offset = 5, it will skip the first 5 rows of your view result.

By default, the View SORT is using Post Date.

Remove Post Date and add the desired field to the SORT area. (when adding, look for your custom date field that you created.)


Adding a jQuery UI widget in the administrative front-end I have created a form within the administrative front-end in my Drupal 7 site to allow administrators to change some configuration options. I've defined the path to it in the following way (in hook_menu):

$items['admin/config/system/my_site_name/status'] = array(
  'title' => 'Change site status',
  'description' => 'My description',
  'access arguments' => array('administer site configuration'),
  'page callback' => 'drupal_get_form',
  'page arguments' => array('my_form_name'),
  'file' => 'forms_file.inc',
);

I want one of the items in this form to be a jQuery UI slider, bound to a hidden select element that has its same value, which is then fetched in the form's submit method (pretty much like in here: http://jqueryui.com/slider/#hotelrooms) by creating a .js file with the following.

(function ($) {
  Drupal.behaviors.site_status = {
    attach: function(context) {
      var select = $("#edit-site-status");
      var slider = $( "

" ).insertAfter(select).slider({
        min: 0,
        max: 4,
        range: "min",
        value: select[0].selectedIndex,
        slide: function( event, ui ) {
          select[0].selectedIndex = ui.value;
        }
      });
      $( "#edit-site-status" ).change(function() {
        slider.slider( "value", this.selectedIndex);
      });
    }
  }

})(jQuery);

However, I've been unable to load the widget, as it seems the whole jQuery UI js file is missing.

  TypeError: $(...).insertAfter(...).slider is not a function

According to http://redhotchilliproject.com/blog/jquery-and-jquery-ui-in-drupal-7, I should manually load the jQuery file in some preprocess function, like this.

function MY_THEME_preprocess_page(&$variables, $hook) {
  drupal_add_library('system','ui.slider');
}

However this method doesn't get called from the page that contains my form. I've even tried to load the jQuery library in MY_THEME_preprocess() without any luck.

I don't want to include the file in the my_module.info file, as I only need the slider to be in the administrative front-end and most users won't need it.

How can I get this slider to show up?

drupal_add_library() can be called from pretty much anywhere, including your form function:

function my_form_name($form, &$form_state) {
  drupal_add_library('system','ui.slider');

  // Build and return the form.
}


Warning: explode() expects parameter 2 to be string, array given in menu_node_submit() I get the above error after a creating a new content type.

  Warning: explode() expects parameter 2 to be string, array given in menu_node_submit()

The function which gives error is shown below :

function menu_node_submit($node, $form, $form_state) {
  // Decompose the selected menu parent option into 'menu_name' and 'plid', if
  // the form used the default parent selection widget.
  if (!empty($form_state['values']['menu']['parent'])) {
    list($node->menu['menu_name'], $node->menu['plid']) = explode(':', $form_state['values']['menu']['parent']);
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Adds menu options to the node type form.
 */

The line that is throwing the error is in the core menu.module. The arguments that are getting passed to it are not valid. To troubleshoot it you would have to backtrace what is getting passed to it to see what is malforming the data or not creating proper data in the first place. If you use debug_backtrace you should be able to find where the bad data is originating from.

Specifically $form_state['values']['menu']['parent'] should be a string (to have explode work on it) but at that time, it is an array.


What can I use to layout the content type form input when creating content? I have created a content type with about 15 fields.

I'd like to improve the layout of the form for creating content of this content type.

Currently all the input fields are listed one after the other which means a lot of vertical scrolling and not everything can be seen on one page.

I looked at the Display Suite module ( http://drupal.org/project/ds ) but I could only see how to layout the resulting content not the input form used to create it. (UPDATED: answer below from Елин Й. says that display suite can actually layout the input form)

Another option would be to create a theme with form layout (good question - and answers here: How to a use a template file to theme a form? ). That's fine, but before I do that I wanted to look at other options available (don't wish to re-invent the wheel.)

Or should I use entities and EntityForm instead if that provides better layout options.

Finally, I'd prefer not to use webform module as EntityForms and ContentTypes provide better integration with built in Drupal features, so I've read.

Display Suite is capable of formating form layout, as well.

  Modules included:

Display Suite: The main module to rearrange your fields.
Search: extend the search results for Drupal core or Apache Solr.
Extras: extra functionality like semantic fields, region to block, hide page title etc.
Forms: style the layout of forms.
Format: provides a PHP filter with entity context (only 7.x-2.x and higher)
UI: Manage custom fields, classes and view modes through UI (only 7.x-2.x and higher)

You should enable the Display Suite Forms module, which is shipped with DS.

Under the 'manage fields' tab of your content type

admin/structure/types/manage/your_content_type/fields

At the bottom, you have an option to select a layout for the form.


How should I implement hook_menu()? What are the fundamentals of implementing hook_menu()?

I would like to see the basics covered in a single question, to avoid having to answer the same similar but different questions over and over.

This information is valid for Drupal 6 and 7. In Drupal 8, hook_menu() has been replaced by new routing system. Below we implement hook_menu() in three simple steps.

Step one

Create an empty module following the instructions in How to create an empty module. In the code shown here, it's assumed the module is named helloworld.

Step two

Add the following code to the module file.

/**
 * Implements hook_menu().
 */
function helloworld_menu() {
  $items['hello'] = array(
    'title' => 'Hello world!',
    'page callback' => 'helloworld_page',
    'access callback' => TRUE,
  );

  return $items;
}

/**
 * Page callback for /hello.
 */
function helloworld_page() {
  return 'Hello world!';
}

Step three

Enable the module, and visit http://example.com/hello. (Replace example.com with the domain name for your server.)
You should see the message "Hello world!". That's it! You have a fully working hook_menu() implementation. What follows are various more advanced topics regarding hook_menu(). In particular, you may want to read about permissions, as the page above will be viewable by anyone.

Arguments

If you want to pass more data to the page callback, you can use page arguments to achieve this. Page arguments should be an array of arguments to pass on to the page callback. If an integer is used as an argument it will represent a part of the URL, starting from 0, incremented once for each slash (/). In the following example, this means the 0 will be turned into 'hello'.

function helloworld_menu() {
  $items['hello'] = array(
    'page callback' => 'helloworld_page',
    'page arguments' => array(0),
  );

  return $items;
}

function helloworld_page($argument1) {
  return $argument1;
}

Strings will be sent on verbatim, so array(0, 'world') could be used to get hello world out again.

function helloworld_page($argument1, $argument2) {
  return $argument1 . ' ' . $argument2;
}

"Wildcards" can be used to accept arbitrary data from the URL.

function helloworld_menu() {
  $items['hello/%'] = array(
    'page callback' => 'helloworld_page',
    'page arguments' => array(1),
  );

  return $items;
}

function helloworld_page($argument1) {
  return $argument1;
}

Visiting hello/world, $argument1 will equal world.

Argument autoloading

Often a URL argument will be the number identifying, for example, an entity. To avoid duplicating code that converts this ID into its corresponding object, Drupal support autoloading for "named" wildcards. When a named wildcard is used, Drupal will check for a function with the same name as the wildcard, suffixed by _load. If such a function is found, it will be called with the value of the value in the URL, and whatever is returned by the loader function will be passed to the page callback in place of the original value. Since Drupal already has such a function for loading nodes, node_load(), we can get nodes autoloaded and passed to the page callback.

function helloworld_menu() {
  $items['hello/%node'] = array(
    'page callback' => 'helloworld_page',
    'page arguments' => array(1),
  );

  return $items;
}

function helloworld_page($node) {
  return t('Hello node (ID = !nid)', array('!nid' => $node->nid));
}

Advanced autoloading

Sometimes, it will be necessary to auto-load more based on more than one argument. Since only the named argument is passed to the loader by default, one needs to explicitly tell Drupal which extra load arguments should be passed on to the loader. For example, to load a specific revision of a node, it is necessary to pass to node_load() a node ID and a revision ID. That can be accomplished by the following code.

function helloworld_menu() {
  $items['hello/%node/revision/%'] = array(
    'page callback' => 'helloworld_page',
    'page arguments' => array(1),
    'load arguments' => array(3),
  );

  return $items;
}

function helloworld_page($node) {
  return t('Hello node (ID = !nid, revision ID = !rid)', array('!nid' => $node->nid, '!rid' => $node->vid));
}

Permissions

'access callback' => TRUE, is necessary to make the simple example above viewable at all, but it's hardly ideal, as it allows no control what so ever. Anyone that tries to visit /hello will be granted access. The easiest way to provide some measure of control, is to provide a access callback, much like the page callback from above. The following code still allows access to anyone, but shows how to move the logic to a function called at access time, thereby allowing more complex logic.

/**
 * Implements hook_menu().
 */
function helloworld_menu() {
  $items['hello'] = array(
    'page callback' => 'helloworld_page',
    'access callback' => 'helloworld_access',
  );

  return $items;
}

/**
 * Access callback for /hello.
 */
function helloworld_access() {
  return TRUE;
}

This isn't necessarily the best way, as using a custom function will often needlessly duplicate code. A better way will be, most of the time, to use user_access(). Together the access callback it is possible to set access arguments. It is possible to require the page to be viewable from the users with the access user profiles permission with the following code.

/**
 * Implements hook_menu().
 */
function helloworld_menu() {
  $items['hello'] = array(
    'page callback' => 'helloworld_page',
    'access callback' => 'user_access',
    'access arguments' => array('access user profiles'),
  );

  return $items;
}

Since the access callback by default is user_access, it can be left out, as in the above code.

More advanced topics

The official hook_menu() documentation provides a lot more information about the most complex use-cases for the hook.


How can I change URL of 'Add new comment' link on teaser? Currently, I have a list of teasers and they have a comment count and an 'Add new comment' link.

That link goes to a dedicated comment page with a URL of the form "/comment/reply/19#comment-form".

However, I want it to go to the actual node which has the comment form at the bottom (eg. "/node/19#comment-form").

Maybe this can be done is the template.php or some other way. Any ideas would be greatly appreciated.

Go to the admin page for your content type

  /admin/structure/types/manage/page

and check Show reply form on the same page as comments under Comment settings.

If you look at comment_node_view() in the comment module, you can see where the comment link is added to teasers.

    if (user_access('post comments')) {
      $links['comment-add'] = array(
        'title' => t('Add new comment'),
        'href' => "comment/reply/$node->nid",
        'attributes' => array('title' => t('Add a new comment to this page.')),
        'fragment' => 'comment-form',
      );
    }

To alter the link you can use hook_node_view_alter() in your module.

function MODULE_node_view_alter(&$build) {
  $node = $build['#node'];
  if (isset($build['links']['comment']['#links']['comment-add'])) {
    // Alter the 'Add new comment' link.
    $build['links']['comment']['#links']['comment-add']['href'] = "node/$node->nid";
    // Fragment is the '#comment-form' part of the url.
    $build['links']['comment']['#links']['comment-add']['fragment'] = 'comment-form';
  }
}


How to display a field before node title? I'm looking to render a certain field before the node's title when displaying a teaser in D7.

Effectively I want to go from this to this.

I have looked into updating the node.tpl.php but I notice that it separates $title from  $content so I'm unsure how to approach this. After some searching I have found that people have suggested using CCK and ConTemplate modules to get around this in Drupal-6 but I'm wondering if there is a more Drupal-7 solution.

Any suggestions?

This is really quite simple with Drupal 7.

With render and hide you know have the posibility to control the placement of a single element in $content without having to print out all the items yourself like was needed in Drupal 6.

A simplified node template looks like this:

<?php print $title; ?>

    <?php print render($content); ?>

A little modification would handle your needs:

  <?php print render($content['field_name_of_image']); ?>

<?php print $title; ?>

    <?php print render($content); ?>

Using render, you can output an element. This is more clever than simply printing stuff, as Drupal will keep track of what has been rendered, to avoid the same thing being printed twice on the place. When rendering the field above the title you are also removing for what's rendered when $content is rendered.


Are there alternatives for striptags filter? When printing a text field we just want to display the value. When printed as is in a twig template ({{ content.field_subtitle }}) we get the following output.

Currently we are attempting not to use the |raw filter so we are just using {{ content.field_subtitle|render|striptags }}.

Are there alternatives to this approach without having to create another twig template for the field? We are having a hard time finding an alternative.

Setup:

Basic page content type has field field_subtitle where type is text(plain)
no twig template has been created on the field, only the content type node--page.html.twig

Current setup in twig template

  {{ content.field_subtitle|render|striptags }}

Current output:

Intrinsicly harness interactive functionalities.

Desired output:

  Intrinsicly harness interactive functionalities

I am vehemently against things like render-array|render|striptags etc. It feels very unnatural and un-Drupal. What you should do is create a field template that has no markup.

For example, either in field.html.twig which would affect all fields, or in field--field-name.html.twig or more specific variants, you can do this:

{#
/**
* @file
* Theme override to remove all field markup.
*/
#}

{% spaceless %}
{% for item in items %}
  {{ item.content }}
{% endfor %}
{% endspaceless %}

This will always render that field with no markup.


Make CSS classes styled in WYSIWYG How can I make CSS classes that can be added to content in a WYSIWYG style in the edit view?

I've added the following 'CSS classes' and I've used my site's normal CSS to float them left and right respectively and give them a width of 51%:

Left=div.posLeft
Right=div.posRight

When I save the node this works fine. However in the editor the styles are not shown. How can I make them show up?

As @tenken says, on the WYSIWYG profile edit page, under the 'CSS' panel, in the 'CSS path' filed you can link to a CSS file to be used on the edit view.

/admin/config/content/wysiwyg/profile/PROFILE-NAME/edit


Quick Start site is not reachable I'm trying to launch a Quick Start distro on macOS with MAMP:

[519] : php core/scripts/drupal -vvv --verbose  quick-start

 Select an installation profile [Install with commonly used features pre-configured.]:
  [standard  ] Install with commonly used features pre-configured.
  [minimal   ] Build a custom site without pre-configured functionality. Suitable for advanced users.
  [demo_umami] Install an example site that shows off some of Drupal’s capabilities.
 > demo_umami

Creating file: sites/default/settings.php
18/18 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓]
Congratulations, you installed Drupal!
Username: admin
Password: hIuWCqqnaD-TostT
Drupal development server started: <http://127.0.0.1:8888>
This server is not meant for production use.
One time login url: <http://127.0.0.1:8888/user/reset/1/1560664888/oDldybNCOH_0nRc1n4YXZWm2NwEehXnN63rWHq_Isqo/login>
Press Ctrl-C to quit the Drupal development server.
Browser command: open 'http://127.0.0.1:8888/user/reset/1/1560664888/oDldybNCOH_0nRc1n4YXZWm2NwEehXnN63rWHq_Isqo/login?destination=%2F'
Server command: '/Applications/MAMP/bin/php/php7.2.1/bin/php' '-S' '127.0.0.1:8888' '.ht.router.php'

Unfortunately the given URL returns with HTTP error code 500. Also I added -vvv and --verbose no additional error messages are visible.

When I change from MAMP to OS X standard PHP installation the browser shows:

Warning: Unknown: failed to open stream: No such file or directory in Unknown on line 0

Fatal error: Unknown: Failed opening required '.ht.router.php' (include_path='.:') in Unknown on line 0

Actually there's no .ht.router.php from where I started the quick-start command.

Any ideas?

Well that was a nasty one. I downloaded and unpacked the latest Drupal version as instructed. But then made a copy using Finder. Unfortunately this leaves out the all files starting with a ..

After copying the files on the comannd line everything works as ecpected. Thanks to @leymannx for pushing me into the right direction.


Theming logo and site name I am using Corporate Clean theme and I want to make some changes to how the logo and site name are displayed. What file would do that in? Sorry, newbie here!

find page.tpl.php file in theme's root folder (sites/all/themes/corporateclean/page.tpl.php).

You'll see that this file defines how and where variables and regions get printed. You can make changes right there.

What you're looking for is $logo and $site_name variables.


htaccess www redirect not working correctly? I have this line in my htaccess file:

  RewriteCond %{HTTP_HOST} ^www.mysite.com$ [NC]

  RewriteRule ^(.*)$ http://mysite.com/$1 [L,R=301]

And it works for the most part. But if you go to www.mysite.com/pagetitle, it redirects you to mysite.com/index.php?q=pagetitle. Why would it not redirect you to mysite.com/pagetitle? Is there another portion of code I need to insert into the htaccess file? I do already have search engine-friendly URLs enabled.

Your RewriteConditions says if starting with www.mysite.com then redirect to http://mysite.com

This rule is not affecting clean urls. Clean urls must enabled at http://mysite.com/admin/settings/clean-urls


How to add extra new term into multiple nodes I got 100 nodes. They all have Term reference field. 50 nodes are set to term 'A' and other 50 to term 'B'. So with that it helps me to filter those nodes via Views to display A nodes in one page and display B nodes in other page.

So now there's an update needed to be done. All those 100 nodes has to have a new term selected 'C' (A and B stays selected as it is). So all A's has to have now C and same with B's.

So how do I do that instead of going through all 100 nodes single by single and selecting it manually?

Install the Views Bulk Operations module.
Create a view and add a filter to view nodes having term a and b.
add    a Bulk operations: Content field and in the field  settings under    SELECTED BULK OPERATIONS select  Modify entity values.
Save the view and from the Operations list, select Modify Entity
Values.    Choose the term field you want to add the terms to,
and then    select the terms you want to add
Select the Add new
value(s) to    FIELD, instead of overwriting the existing values
check box and Submit the form.


Can theme() call a theme function from another module? In a module I created, can I add a call to theme() similar to theme('example_def', $var) where example_def is a theme function defined from another module?

function def_theme() {
return array(
  'example_def' => array(
    'arguments' => array('nid' => NULL)
  ));
}

function theme_example_def() {}

Yes, a module can call, with theme(), a theme function that is defined from another module. If it were not so, no module could use theme_link(), since that is defined as one of the System module theme functions. This is contrary to Drupal philosophy; limiting a module to use the theme functions it defines would not make sense.

See system_theme() which calls drupal_common_theme() to add link to the theme function it implements.

function drupal_common_theme() {
  return array(

    // From theme.inc.
    'html' => array(
      'render element' => 'page',
      'template' => 'html',
    ),
    'page' => array(
      'render element' => 'page',
      'template' => 'page',
    ),
    'region' => array(
      'render element' => 'elements',
      'template' => 'region',
    ),
    'status_messages' => array(
      'variables' => array('display' => NULL),
    ),
    'link' => array(
      'variables' => array(
        'text' => NULL,
        'path' => NULL,
        'options' => array(),
      ),
    ),
    // …
  );
}

Notice that the correct theme function definition that works for Drupal 7 is the following one; the one you are using is only for Drupal 6 or previous versions.

function def_theme() {
  return array(
    'example_def' => array(
      'variables' => array('nid' => NULL)
    )
  );
}

Since your example of calling the function is theme('example_def', $var), I take you are using Drupal 7, for which your definition would not work.


Theme import not changing the color scheme I created a new theme in d8 and modified some color schemes.

Then I ported that theme to another site and placed in /var/www-
drupal/themes and enabled it.

The theme is ported. But the changes made to
the color scheme is not ported. Any idea how to import the color scheme?

Its still in the default color scheme.

You have to export the color configuration from the old site and import it to the new site.

You can do this in UI. Go to /admin/config/development/configuration/single/export, select configuration type Simple configuration and the configuration name color.theme.mytheme. Copy and paste the color configuration to the new site. Use here the single item import section.

If you want to do this automatically when installing the theme you can place the file color.theme.mytheme.yml in the /config/install folder of the theme.


How to format Start + End Dates without using PHP I have a content type with a start date, and an option for an end date. When this field is displayed in a view, I would like to see

1 May 2012
2-3 May 2012

(etc...)

At the moment, I can only adjust the format to display

2 May 2012 - 3 May 2012

I've also learnt that even though an end date may not be provided, it defaults to the start date, so I can't use any rewrite rules in Views module to get around this.

Is there anyway to adjust the Date format when using a start and end date?

You can coax something out of Views without PHP (see Partial Solution below) but not, I think, quite what you want. A module or - against your team policy Views PHP - may be required.

Discussion

Part of why some of the usual Views workarounds won't solve this problem is the edge cases. If we knew that ranges of dates would always be within the very same month, then this could be done in Views without PHP using the approach outlined below. But that seems unlikely! You need to consider what you want to do when you get cases such as 31 May 2013 to 2 Jun 2013 or 28 Dec 2012 to 4 Jan 2013. What do you want displayed? If you want '31 May - 2 Jun 2013' and '28 Dec 2012 - 4 Jan 2013' respectively, but in non month-crossing cases '2 - 3 May 2012', then some code is going to need to be involved somewhere.

Partial Solution

A partial solution can be massaged out of Views. It will avoid repeating the year but not the month. So you get, e.g. '2 May to 3 May 2012', '28 Dec to 4 Jan 2013', '31 May to 2 Jun 2013' from it. Just possibly this might be close enough for some use cases.

The strategy is to add the date field twice (excluding it from display) and apply different formats / configurations. You can then use Global: Custom text fields to join the results together.

Create two date formatters. One to give '12 Mar' when given 12th March 2012 (j M) and one to give '2012' when give 12th March 2012 (Y).
Add the date field (and exclude from display). Set it to show both the START and END dates using the '12 Mar' format. When both START and END are present this will yield '3 Mar to 6 Mar' etc. When only START is present, it will yield '3 Mar'. Recommendation use the 'Administrative title' in the 'More' section to document this, e.g. 'Date or range without year'. This helps at the final step.
Add the date field (and exclude from display). Set it to show just the END date. Use the '2013' format. When an END date isn't present, Views will fall back to using the start date. Recommendation use the 'Administrative title' in the 'More' section to document this, e.g. 'Year'. This helps at the final step.
Add a Global: Custom text field and use 'Replacement Patterns' to output the 'Date or range without year' followed by the 'Year'. (Easy if you've documented with the 'Administrative title' - trial and error if not.)

Note: If you want to detect the absence of an end date at step (3), Views will do this if you make use of the No Results area. It only defaults to the Start Date if the No Results area is not used. That gives some, albeit, limited scope to vary formatting depending on the presence of absence of an end date.


How can I disable future dates? I am developing a custom module, where I need to disable future dates in the date pop-up. How can I do this?

This can be achieved by adding an attribute max

$form['date'] = [
  '#title' => $this->t('Date'),
  '#type' => 'date',
  '#attributes' => [
    'type' => 'date',
    'min' => '-25 years',
    'max' => 'now',
  ],
  '#date_date_format' => 'd/m/Y',
];

Reference: https://api.drupal.org/comment/61733#comment-61733


Generating internal URL/redirect by path> In the past I could set up redirects with drupal_goto using a simple path (i.e., node/1).

Is this not possible at all in Drupal 8? Everything I've seen relies on a route name but that requires either generating a page in a module or keeping a static note of a node id, which seems backwards.

If I use Url::fromUri(), I can't seem to use getRouteName() since it interprets that as an external URL (even though the domain is the Drupal install).

What is the best way to get the route name of an internal path?

drupal_goto is removed in favor of RedirectResponse (record).

  As of Drupal 8 drupal_goto() has been removed in favor of
  RedirectResponse which comes together with the Symfony HttpFoundation.

  hook_drupal_goto_alter() was also removed as well, in favor of just
  using an event listener on kernel.response

Drupal 7

<?php
function my_menu_callback_foo() {
  //....
  drupal_goto('user');
}
?>

Drupal 8 (procedural)

<?php
function my_menu_callback_foo() {
  $url = Url::createFromPath('node/1');
  return new RedirectResponse($url->toString());
 //Or try this:
 return new RedirectResponse('node/1');
}
?>


Unable to access translated node content After performing a Drupal core update on my site today I've found that I can no longer access translated content. When I try to view or edit the translation, I only see the default language content.

I created a short GIF you can view here:

via GIPHY

As you can see, I'm editing the node for Canada and the US translation is showing instead. Translations were working fine with Drupal 8.6.2 but began to do this in 8.6.3. I have now done the following with no success:

Updated to the latest Drupal core 8.7.2
Updated all installed modules
Created a new Drupal site with 8.6.3 and 8.7.2, but this issue does not exist
Disabled Workbench moderation for a given content type, but that doesn't fix the issue

I'm really not sure where and or how to troubleshoot this issue. Where would you start?

I'm thinking I could start by uninstalling modules to see which is possibly causing the issues. I'm not sure if that is the right approach given that this issue began when I updated the Drupal core, not the modules.

Thank you for any feedback!

Turns out this issue was due to my settings on the Detection and selection page at /admin/config/regional/language/detection. I reordered URL to be above User and the translations are now showing.

Hopefully, this is able to help someone else in the future.


Confused about installing Apache Solr This is pretty embarrassing but I gotta start somewhere, right? This concerns about installing Apache Solr.

I've seen the instructions when trying to install Apache Solr and each one starts off with installing Java. I'm confused since I'm using Bluehost for webhosting (http://drupal.org/hosting). Does that mean I need to install Java on my server? There's also the thing about the terminal but I've never seen the terminal in my hosting's Cpanel. Help.

Edit: By terminal does that mean SSH? Because I can have that enabled in cPanel. It would be nice if there were a simple tutorial for cPanel's users like me. :-)

Yet that's true. If you want to use apachesolr for your own you have to run a java server.

Alternative there are some services which you can pay to host apachesolr for you.
Some examples:

acquia
drupalconcept


How to get the path to a node I'm using a view template to override how a field is displayed.

I want to include a link to the node in the field.

Given a node, how do I get the URL (relative is fine) for a node?

I've got the node in the overridden template, but not sure where to go from there:

$node = node_load($row->{$field->field_alias});
$wrapper = entity_metadata_wrapper('node', $node);

$path_to_node = ???

?><a href="<?php print $path_to_node ?>">Go to Node

You don't need entity_metadata_wrapper in this case.
You can get path of node using url() function.

$node = node_load($row->{$field->field_alias});
$nid = $node->nid;
$path_to_node = url("node/$nid");

And I agree with Елин Й's answer. You can use l() function. It already uses url() function. So you can build link with node pathauto alias using:

$node = node_load($row->{$field->field_alias});
print l(t('Go to Node'), 'node/' . $node->nid);


How to display specific button for certain user? I have a simple Drupal 7 page with 3 buttons. Page is only accessible by logged-in users.
I have 3 roles - role 1, role 2 & role 3
What I would like to do is to show only button 1 when a user with role 1 logged in, hide the other 2.
How can I achieve this, please?

To hide and show buttons by role you can use the $GLOBALS to get the user and check on user role, something like.
 <?php if (in_array('role 1', $GLOBALS["user"]->roles)): ?>
    <button value="button 1">button 1</button>
  <?php else: ?>
    <button value="button 2">button 2</button>
    <button value="button 3">button 3</button>
  <?php endif; ?>


Using Migrate API to select items from a JSON array I have a module pulling a JSON feed into Drupal 8 using the Migrate API. However, one of the values in the JSON is an array.

For example, coordinates:

{
    "data": [
        {
            "id": "id:1",
            "position": {
                "coordinates": [
                    24.932974,
                    60.168495
                ],
                "type": "Point"
            },
            ...
        },
        {
            "id": "id:2",
            "position": {
                "coordinates": [
                    24.94416,
                    60.18831
                ],
                "type": "Point"
            },
            ...
        },
...

What sort of field selector is needed to get coordinates?

If I use selector: position/coordinates I get 24.932974.

How would I get the second one: 60.168495?
Should the extract plugin be used here?

First, use a selector like this:

-
  name: position
  label: 'Position'
  selector: position

Then use this for the first value:

field_description:
  plugin: extract
  source: position
  index:
    - coordinates
    - 0

And this for the second value:

field_description:
  plugin: extract
  source: position
  index:
    - coordinates
    - 1


Colorbox Slideshow not Working on Mobile Devices I have a Colorbox slideshow that doesn't want to work on mobile devices. Instead of opening up the slideshow modal on an image click, the browser opens the image in a new tab.

The default behavior of Colorbox is to disable mobile functionality when the device's max width exceeds 480px. This functionality can be disabled with the Mobile detection option in Configuration > Media > Colorbox > Advanced settings.


how to use image for next previous link in pager in drupal 7 I am woking on drupal 7 I want to change link text and replace them with image. How can I achieve following:

Is there any function in template.php to do so?
Is there any way to overridden template to pager in custom theme?

In template.php

function THEMENAME_pager($tags = array(), $limit = 10, $element = 0, $parameters = array()) {

}

http://api.drupal.org/api/drupal/includes!pager.inc/function/theme_pager/7

For api please check above link you can overridden.   also check below link.

In drupal 7, How to override theme_pager?


calculated field in views based on another view i have a view with items and prices, each item has an id, another view taken from a different content type also shows items and their base price the id of the item will be the same (basically one list is items containing seller prices and another is the market price, there can be many sellers but only one market price).

now i want to show in the first view a calculated field that will display the difference between the seller price (price of an item in first view) and the market price (the price of the item containing the same id in the second list).

is there a way to do it? if so how?

One way to do this would be to create a field template for that specific field.  Then you could first print the value of the seller price, and then do the calculations in php and print the difference.

You can specify that the field template only be used for a specific field in a specific display of a specific view by naming it correctly.  You'll find the pertinent names in your view edit page under Advanced -> OTHER -> Theme: Information.  The default contents of a template file are also available there by clicking on the field name.


Multiple checkboxes in an AJAX calls I've been developing this phonegap app and I'm stuck with a few things and one of them is multiple checkboxes - I hope you can help.

I've got the below code

HTML

<input type="date" id="date" />
<input type="hidden" id="hidden">
<fieldset id="oyuncuKategori">
    <legend>Kategori</legend>

        <input type="checkbox" id="oyuncu" name="kategori" value="oyuncu" class="squareTwo" />
        Oyuncu

        <input type="checkbox" id="yardimci_oyuncu" name="kategori" value="yardimci_oyuncu" class="squareTwo" />
        Yardımcı oyuncu

        <input type="checkbox" id="cocuk_oyuncu" name="kategori" value="cocuk_oyuncu" class="squareTwo" />
        Çocuk oyuncu

        <input type="checkbox" id="stand_hostesi" name="kategori" value="stand_hostesi" class="squareTwo" />
        Stand hostesi

</fieldset>

JavaScript

$("input[type='date']").on("change", function () {
    // var checkbox = $("#oyuncuKategori").serialize();
    var checkboxes = '';
    $('input[name=kategori]:checked').each(function(i, e) {
        checkboxes += '&node[field_kategorisi][und][value]='+$(this).val();
    });
    console.log(checkboxes);
    monthNames = [
        "Oca", "Şub", "Mar",
        "Nis", "May", "Haz", "Tem",
        "Ağu", "Eyl", "Eki",
        "Kas", "Ara"];
    date = new Date($("input").val());
    day = date.getDate();
    monthIndex = date.getMonth();
    year = date.getFullYear();
    finalDate = day + ' ' + monthNames[monthIndex] + ' ' + year;
    $.ajax({
        url: 'http://www.rejicast.com/services/node.json',
        type: 'post',
        dataType: 'json',
        data: 'node[type]=oyuncu&node[title]=testnomikos456&node[language]=und'+ checkboxes +'&node[field_dogum_tarihi][und][0][value][date]=' + finalDate +',
        success: function (data) {
            console.log(JSON.stringify(data));
        },
        error: function (xhr, status, message) {
            console.log(xhr);
            console.log(status);
            console.log(message);
        }
    });
});

The thing is, this code works for creating a node but and inserts values for field_kategorisi overwriting other values, thus always the last checked box is there, while trying with [und]['+i+'][value] gives me 406: An illegal choice has been detected. Please contact the site administrator. and something like Illegal choice Array in field_kategorisi (I don't remember the English wording) on the server side. I'm really stumped. Can you give me any ideas?

UPDATE: When I make an ajax call, my POST looks like this.

  http://www.rejicast.com/services/node.json?node[type]=oyuncu&node[field_kategorisi][und][0][value]=stand_hostesi&node[field_kategorisi][und][1][value]=yesilcam

Edit: Just looked at the code more closely, and saw this was the Services module.

From https://www.drupal.org/node/1971484#comment-7318114:

  For those of you who will probably have the same problem, here is the correct way to handle LIST type fields (in ex. below field_mosaic_bu):

{
  "type":"TEST",
  "title":"TITLE",
  "uid":"1",
  "field_mosaic_bu":{ "und": ["bu name"] },
  "field_mosaic_var1":{ "und": [{ "value":"test1" }] },
  "field_mosaic_var2":{ "und": [{ "value":"test2" }] },
  "field_mosaic_var3":{ "und": [{ "value":"test3" }] },
  "field_mosaic_image":{ "und": [{ "fid":"4" }] }
}

  Hope this helps someone. Took me a lot of time to figure this out.

When you get that message from Drupal, it generally means that you have tried to set a form value to a non-allowed value from the perspective of the field configuration. So, for example, field_kategorisi might be a Term Reference field. If you try to set it to a tid that isn't allowed according to the Drupal field configuration, that happens.

If it's a simple checkbox field, then adding the value you want to set to the Allowed Values in the field configuration should solve the issue.

If this doesn't help, please provide more information about the Drupal-side field configuration and whether you are using the form Drupal generates or not. It embeds various things like the form ID, form build ID, and so on into its form markup, so if problems persist, it could be related to it not receiving something it's expecting.


Date format - @ symbol has unexpected behaviour I created a date format , then added that date format to a field within a view. But the @ symbol is automatically appending to the end of the date format (even though i specified it to go into the middle of the date format, and is reflected correctly in the preview). I used PHP:date - Manual as my reference.

My date format: l, F j @ g:ia and it displays as: Wednesday, June 17 @ 4:32pm

Now when I select that date format for my date field within my view, it outputs the said date as: Wednesday, June 17 4:32pm @.

I'm confused because whenever I have put other characters before, it always outputted what I wanted. I've also tried using the html equivalent of &#64; but it outputs the @ symbol at the end of the format as well.

I'm just wondering if this is a views, php, or date issue? And is there anyway I can output this date as: Wednesday, June 17 @ 4:32pm from a date format?

I was having the same issue and was able to get this working by escaping the @ symbol.

Example: 'M j, Y \@ G:i'


Custom Page inside Module I'm trying to embed custom content (custom javascript, paragraphs etc) with a Drupal Form. I'm wondering whats the best way to do it in module?

Something like this:

function wow_page() {
    drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
    $output = 'teasdasdst';
    $output = '

';
    $output .= drupal_get_form('wow_cake');
    return array('#markup' => $output);
}

ok add hook_menu that call this function

if you have module called wow

function wow_menu() {
  $items = array();
  $items['home'] = array(
    'title' => '',
    'page callback' => 'wow_page',
    'access callback' => TRUE,
  );
  return $items;
}


How to add a class to more link of a view? I want to add a class to a views more link available under pager section using template_preprocess_views_view().

You can do it by implementing template_preprocess_views_view() in your theme under THEMENAME.theme file as shown below:

/**
 * Implements template_preprocess_views_view()
 * @param array $vars
 */
function THEMENAME_preprocess_views_view(&$vars){
  if(YOUR CONDITION FOR ADDING A CLASS){
    $vars['more']['#options']['attributes']['class'] = array(
      ENTER YOUR CLASSES AS ARRAY ELEMENTS
    );
  }
}

Reference: http://www.drupalthemez.com/blog/d8-adding-class-more-link-view


"Illegal choice full_html in Text format element" when submitting form programatically Im trying to create a block programatically. I have created a function, which does the work for me.

function _create_footer_contact() {

  form_load_include($form_state, 'inc', 'block', 'block.admin');

  $form_state = array();
  $form_state['values'] = array(
    'machine_name' => 'footer_contact',
    'title' => 'TITLE',
    'info' => 'INFO',
    'body' => array(
      'value' => 'BODY TEXT',
      'format' => 'full_html',
    ),
    'regions' => array(
      'mytheme' => 'footer',
      'myadmintheme' => '-1',
    ),
    'visibility' => '0',
    'pages' => NULL,
    'custom' => '0'
  );

  drupal_form_submit('block_add_block_form', $form_state);
}

The problem is the 'format' value, which throws an error if it is set to anything but 'plain_text' (if format is set to 'plain_text' the form submits nicely and a block is created).

WD form: Illegal choice full_html in Text format element.
An illegal choice has been detected. Please contact the site administrator.

To debug I have tried to examine the $form_state of 'block_add_block_form' using hook_form_alter and dpm(). When I manually submit a block the 'format' is set to 'full_html'.

So... how do I submit a form programatically with full_html set as format?

You can try this.It works i think so

$form['formItem'] = array(
     '#type'=>'text_format',
     '#title' => t('Field Label'),
     '#value' => 'This is my value',
     '#format'=>'full_html',
);


Get Relationship for the Author of the Latest Comment In a Node view, I am trying to group the latest comments by the author's field_last_name, but I am having difficulty adding this field.

I tried using the the "Last comment" and "Last comment author" relationship, but they both don't appear to work. (Neither exposes the user fields or the "Comment: Author" relationship.)

Am I missing something here? Or must I switch my Node view into a Comment view?

I'm going to assume here that field_last_name is a field you added yourself to the account fields. I tested using just the user name, and got it to work fine using the following relationships (starting from a Node):

From the node to all comments: was called "Comments of the node using field: comment" here
And then from the comment to the author: just called "Author" here in the Comment category

Then I added the "Name" field (User category), and Bob was my proverbial uncle.


How can I have a view reset when an exposed title filter is emptied? I have a view that simply lists content. I have one exposed filter "Title" for users to filter content that "contains" and text they insert. I have set the exposed filter to Autosubmit as they type with ajax turned on. The problem is that if the user deletes what they have added to the exposed title filter, the view isn't reset. It stills shows the results of their previous submission. I can of course add a reset button but is there any way to have the view reset itself when the exposed title filter is emptied by the user?

You would need to add jQuery to listen on the textfield change event, or similar. If value is empty then set location to current path without querystring. YMMV


Use condition in my views I have a content type "event".I show all my events rejected or validated. Now in my view I want to show fontawesome icon like "cancel" to signal that the event is rejected and another fontawesome icon like "okey" to signal that the event is validate. How to use Global text to make it? I don't like to use page.tpl.php. But if there are a solution base it I can accept it.

Assuming you have a boolean field which stores if event is rejected or validated, you can read this information from PHP and print the fontawesome icon based on a condition.

The standard way in Drupal 7 would be to use Views PHP module and do something like:

if ($data->field_field_event_validated['0']['raw']['value'])
  echo '';
else
  echo '';

This module still isn't ported to Drupal 8, and actually it's really bad in terms of security and stability to use this module as this article states. The same article describes how to include PHP in your views. In resume you have to create a module, generate a custom views field with the PHP code printing your icon and use this module in Views.


Drupal 7.14 - grouping site links on search engines I am trying to get my sites links, ie. about us, to appear as sublinks of the sites main page. For eg. When you google Drupal, the Downloand & Extend as well as Modules links appear grouped under the main Drupal.org link.

Is there a module that can do this? Thanks in advance.

These are generated by google, not by any module inside of drupal.  googling 'sitelinks' will show you more information about how google creates them for popular sites.

http://support.google.com/webmasters/bin/answer.py?hl=en&answer=47334 from google is a good start.


Within a field template, how can I print the value of another field from the same node? I have an email field that I would like to present on the node as a name that links to the email address. As such, I am trying to edit the email field template to embed the name from a text field. However, I'm having difficulty figuring out how to access the content of this text field. I've gotten as far as figuring out that twig(_context['element']['#object']) will give me some info about the node object, but I cannot figure out how to access the field values. Am I even in the right ballpark for accessing this data?

This is the node object that you have found in the field template.

You can access the field values like this:

{{ element['#object'].field_field1.value }}


How to create a filter condition autocomplete for entity reference field or normal? I am trying to create a filter condition for entity reference field in views, i tried by using rendered entity option it is showing dropdown for filter condition. I need autocomplete or it should be without dropdown and autocomplete (plain filter field).

It should apply after giving full value in filtercondition?

Any suggestions..

/* Filter criterion: Content: Cage ID_VBC (field_cage_id_vbc) */
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['id'] = 'field_cage_id_vbc_target_id';
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['table'] = 'field_data_field_cage_id_vbc';
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['field'] = 'field_cage_id_vbc_target_id';
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['group'] = 1;
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['exposed'] = TRUE;
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['expose']['operator_id'] = 'field_cage_id_vbc_target_id_op';
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['expose']['label'] = 'Cage ID';
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['expose']['operator'] = 'field_cage_id_vbc_target_id_op';
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['expose']['identifier'] = 'field_cage_id_vbc_target_id';
$handler->display->display_options['filters']['field_cage_id_vbc_target_id']['expose']['remember_roles'] = array(

you can change an exposed filter to Select List or Text Box using the following code..

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $view = $form_state['view'];
    if ($view->name == 'my_view_machine_name' && $view->current_display == 'display_name') {
        $options = array('your options');
        $form['your field name']['#type'] ='select'; //Use TEXTBOX for text field.
        $form['your field name']['#size'] = null;
        $form['your field name']['#default_value'] = '';
        $form['your field name']['#options'] = $options; //not needed for textbox
    }
  }
}

Another option is use Autocomplete Deluxe for References Module.

Hope this will help you..


Is there a way to link a menu item to the edit page of the last article? I want to create a menu item linked to the edit page of the last article.

I created a view and added filters to get the last article. I added only the field node path to the view.

But how can I get the value of that path field and put it in the URL of my menu item?

Yep!

Create a view that loads the single last published article,  style the view to look like your regular node page and then add a link to the view in your menu.

you could get fancier, but this is the least amount of PHP.


How can I link Fields in a View to the entity it belongs to? How can I link Fields in a view to the entity it belongs to, along the lines of 'Node: Link' or 'Link this field to its node' in Views D7? Do I have to define anything special to give me a field in Views Field to pick from to enable this?

Also, instead of just link to the defaultUri, how could I use a pathauto aliased path if it exists instead of the entity uri?

The link to node or link to user option you see on some properties in views are special. The reason the possibility is there, is because Views has added the option and functionality in a special handler.

Things are not that easy with fields since they can be attached to anything, which makes it much more complex (compared to nid, uid, title and username). You could probably do this with some code, but usually it's much easier to use the rewrite result option, and select output as link and type in the link with tokens: node/[nid]. I'm not sure, but I believe the Views will run the link through l or url enabling path auto.


Display different icons depending on field value I am trying to produce a result that requires PHP code to evaluate whether a Drupal 8 node field is a "x", an "f", a "m", a "h", or an "l".

Thanks to some help on an earlier question, I've accomplished my task (to replace the value with a useful icon) when the value is binary: if it exists, show this. If it's empty, show nothing. I've done this via CSS.

Now I'd like to extract the actual value of the node field, and display different icons based on its value.

I am not planning to do this via a function, but rather by code on the node itself.  Is there some syntax I can use within the php that will extract this?  So that I can have the equivalent of:

$price = $node[field][value];

then I'd do:

if ($price == "m") { // use icon X }
else if ($price == "h") { // use icon Y };

Thank you for any and all help/suggestions!

This only requires one field. It sounds like it is a list (text) field to me.

This should be done as a new variable to the node template by way of using hook_preprocess_node in your MYTHEME.theme (replace any instance of MYTHEME with your actual themes name, i.e. bartik) file. Here is an example:

function mytheme_preprocess_node(&$variables) {
  $type = $variables['node']->getType();

  if ($type == 'NODE_TYPE') {
    $price = $variables['node']->get('field_name')->value;

    switch ($price) {
      case "m":
        $variables['custom_icon'] = 'icon1';
        break;

      case "h":
        $variables['custom_icon'] = 'icon2';
        break;

      case "x":
        $variables['custom_icon'] = 'icon3';
        break;

      case "f":
        $variables['custom_icon'] = 'icon4';
        break;

      case "l":
        $variables['custom_icon'] = 'icon5';
        break;

      default:
        $variables['custom_icon'] = FALSE;
        break;
    }
  }
}

Then, create a node--NODE-TYPE.html.twig file, where NODE-TYPE is the machine name (bundle) of the node in question (ex. article, page, product).

In this file, you now have a new variable available to use, which would be output with:

{% if custom_icon %}
  {{ custom_icon }}
{% endif %}

If no value, or value does not match whats expected, the switch statement will set the variable to FALSE so you can check in Twig if you should output it or not.


How to show titles as plain text on rendered entity reference By default the titles are showed as links to there node if you choose to display format rendred entity (full).

I want the titles as plain text and not links

If you have display suite. You will need to do this no in the rendered part, you have to do this in the view mode of the content type that you are rendering for instance. I have installed display suite and that helps me to have more control over the layout

profile product --> rendering entity from news product displayed as teaser
news product --> In news product in the teaser view mode or full mode in your case, in manage display choose the title and select no link.

You need to have applyed a column layout in display suite to see it.


Why my custom submit handler isn't working in menu item edit form? Code:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymod_form_menu_link_content_menu_link_content_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  array_unshift($form['#submit'], 'mymod_menu_link_content_form_submit');
}

function mymod_menu_link_content_form_submit($form, \Drupal\Core\Form\FormStateInterface $formState) {
  //some code
}

Debug shows me that my custom submit handler is added to $form['#submit'] array as a first item. However this submit handler is never called.

Forms can have submit callbacks in two places. Either on the form level or on the button that is pressed. The form level callbacks are only invoked if no button-specific callbacks are specified.

Entity forms generally have the submit callbacks on the submit button, which is usually $form['actions']['submit']['#submit'].

This was the same in Drupal 7, although the node form and possibly others had a backwards compatibility layer that also invoked form-level submit callbacks, but this was removed.


Theming custom block in twig file and render variables I created a custom block and I'm trying to render it in twig file. The file gets used, as I can see its output, but my variable 'my_variable' defined in the block is not rendered:

in CustomBlock.php

public function build() {
    $build = [];

    $build['custom_block'] = [
      '#my_variable' => 'abcdef',
      '#theme' => 'custom_block',
    ];

    return $build;
}

in my_module.module:

function my_module_theme() {
  return [
    'custom_block' => [
      'template' => 'custom-block',
    ],

  ];
}

in custom-block.twig.html:

<div>{{ my_variable }}</div>

-> The twig file gets used and the div is shown, but the variable is empty/is not rendered.

You probably just need to define the available variables:

function my_module_theme() {
  return [
    'custom_block' => [
      'template' => 'custom-block',
      'variables' => ['my_variable' => ''],
    ],

  ];
}

You'll need to rebuild caches for the change to be picked up.


Rate content and attribute points to author I am looking for a module that allows users to be rated points +1 -1 . Any suggestions?  I would like individual users to be rated like stack exchange. I would also eventually like to have a rating for a node, e.g. project which also contributes to the user's points.

You're looking for the User Points module. For node ratings you can use the User points Nodes and Comments or/and the Fivestar modules. There are also plenty of other modules that integrate with the User Points module, there's a nice list in the User Points Contributed modules page.


How to add some custom text after a taxonomy field in panels? I have a taxonomy field called cvtype.

This cvtype is containing several names like
- Standard
- Complete

I can add this to a Panel by adding content > node.
I would like to add the letters CV behind each term in this panel.

How to do this in D7?

You can achieve this by using display suite to add a prefix:

Download & enable the module Display Suite (if not already installed) https://www.drupal.org/project/ds
Go to <my_url>/admin/structure/ds/settings
Enable export field templates

Edit your cvtype taxonomy and click on the Manage Display tab

Choose the one column layout (and save) -> display the name field, click the gears icon & add the prefix


Webform Address Element and Canada provinces In the webform (drupal 8) module I am using the address element and notice that the state/province field does not contain any Canadian provinces - only US States and Territories.

Where can I add the Canadian Provinces?

You can alter the default state options via /admin/structure/webform/config/options/manage.

I recommend installing the Address module for substantially better international address support.


How to migrate to translatable fields I am using the latest Entity Translation module in order to provide a couple of translatable fields for some of my content types. I have a content type which has a translatable field which is called "title_field".

I am using the Migrate module (version 2.0) in order to fill in the Drupal scheme with data from an old database. Normally, in a single language, the line would be:

$this->addFieldMapping('title_field','name')

Now the problem is that I have two translations of this field in my old database, which I want to create through the migration API.

$this->addFieldMapping('title_field','name_el')->arguments(array('language','el'));
$this->addFieldMapping('title_field','name_en')->arguments(array('language','en'));

Unfortunately this last one does not work. Any idea how I can go further with this?

I solved the problem by first doing the field translation manually for one node, and then using Node Export to see the actual code describing the node.
Finally, I used the prepare function of the Migrate api to do the work manually.

function prepare($entity, stdClass $row){

    $entity->language = 'el';
    $entity->title_field['el'][0]['value'] = $row->name;
    $entity->title_field['en'][0]['value'] = $row->name_en;
    $entity->translations = (object) array(
                    'original' => 'el',
                    'data' => array(
                            'el' => array(
                                    'entity_type' => 'node',
                                    'entity_id' => $entity->nid,
                                    'language' => 'el',
                                    'source' => '',
                                    'uid' => '0',
                                    'status' => '1',
                                    'translate' => '0',

                            ),
                            'en' => array(
                                    'entity_type' => 'node',
                                    'entity_id' => $entity->nid,
                                    'language' => 'en',
                                    'source' => 'el',
                                    'uid' => '1',
                                    'status' => '1',
                                    'translate' => '0',

                            ),
                    )
            );
 }


Can I remove unused core modules from Drupal? I am about to start a new website that is supposed to handle thousands of users at once. It is having some mobile application, and I need to use web service.
As a matter of performance, and the link I found here, I am planning to remove core modules such as the Blog module, the Forum module, and maybe the Search module too.

Is it a best practice? What can I do to increase the performance, as I am not planning to purchase a VPS or something like that for hosting?

Modules that have never been enabled are not a performance issue.

The issue report you linked is referring to what Drupal does when it doesn't find an enabled module; in such case, Drupal rescan the directories where the modules are placed, causing performance issues. To avoid it, modules should be uninstalled from the module page, and then deleted from the server directories; if you do this, you will never have any performance issue.

If you are thinking of removing the database rows found in the "system" table referring to those core modules that you don't use, then it is useless, as Drupal adds those rows back every time you visit the module page.
If Drupal were not doing that, you would not be able to install new modules. When you visit the modules page (admin/modules in Drupal 7), Drupal rescans the directories where modules are placed, to list the new modules you could have copied on the server. If it finds a module that   doesn't have a row in the "system" table, it adds it; it cannot know if you removed that row from the table, or it is a module that you copied on the server, and you want to install.

If you are thinking of removing the module files for those core modules you don't use, you should keep doing it every time you update Drupal; as there isn't any gain, it's useless doing it.


Why Manage_fields and Manage_display tab are not shown in content type? Suddenly My dev site is not showing

  Manage_fields and Manage_displays

in all content types. I am using contributed module admin_menu. I clear all cache but it happens same. This is multilingual site. I can't understand why it occurs? Can anyone solve this problem? I have enabled field_ui modules.

There is unchecked permission of field. After checked it shows the tabs. Make sure two things to solve this problem.
1. Enable Field UI (field_ui) module
2. Make sure the field in permission is checked

  admin > people > permissions


How to render content with  in twig to create paragraph Sorry I'm newbie in drupal 8
I want to render my content from database which have
 tags inside and my expectation every
content
 will create new paragraph
My database content was like this:

Content 1

Content 2

Content 3

I was try using {{ content.value |raw }} but it was render all content without create new paragraph

I also try using {{ content.value | raw | nl2br }} and {{ content.value | replace({"\n": "
"}) | raw }} but this one create double
 every paragraph so my paragraph become annoying

Is there any solution in twig to render
 tags to create beautifull paragraph?

Thank you

1) It's bad security practice to use |raw. See How do I get the raw field value in a twig template? for proper/safe way to do it.

2) I am confident that  {{ content.field_name }} or {{ entity.field_name.value }} is printing  your <p> tags. If you right click and inspect element, you should see them in the HTML. Your issue must be CSS related perhaps the p { ... } CSS code have an inline or a float in them.


Why are there entries in sessions table for uid 0? I was alarmed to find sessions being written to the table [sessions] for uid 0. Do I need to worry or is this normal? I could not find answers by searching. I don't know how the sessions table works.
This is Drupal 8.

Do not be alarmed, this is normal. Typically seen in Drupal Commerce sites to keep track of anonymous users also known as user 0.


Patch for module applies with patch command but not composer I have encountered a weird issue in which a patch I rolled for Commerce does not apply with Composer; it gives no errors, but the patch is not actually applied.

  "extra": {
    "patches": {
      "drupal/commerce" : {
        "Allow order types to have no cart": "https://www.drupal.org/files/issues/commerce-direct-checkout-2.2-2810723-37.patch"
      },

However, the same patch applies correctly after downloading and using the patch command:

/web/modules/contrib/commerce$ patch -p1 < ../../../../patches/commerce-direct-checkout-2.2-2810723-37.patch
patching file modules/cart/src/Form/AddToCartForm.php
patching file modules/cart/tests/src/Functional/AddToCartFormTest.php
patching file modules/cart/tests/src/Functional/CartBrowserTestBase.php
patching file modules/product/config/schema/commerce_product.schema.yml
patching file modules/product/src/Plugin/Field/FieldFormatter/AddToCartFormatter.php
patching file modules/product/src/ProductLazyBuilders.php

What is wrong with my patch that makes it fail in Composer?

It turns out this is an issue with Drupal patches for composer when using an older version of Git.  The problem is with composer-patches 1.6.3.

Three possible solutions for now until the bug gets fixed.

Force 1.6.2

In composer.json, specify 1.6.2:

"require": {
"composer/installers": "^1.0.20",
"cweagans/composer-patches": "1.6.2",

Force git clone with 1.6.3

In composer.json, instead of "dist", use "source":

"config": {
    "preferred-install": "source"
  },

Update git to the latest version


Rules - After updating / saving user not working I'm using Rules module to execute a python script after a user has been created / updated. This python script retrieves information of users from the database and feeds a datapushing / realtime data engine.

Everything works perfect, BUT, the script is executing before saving.

Update regarding 'script is executing before saving'

When I get the information from the DB with the python script is the one I have before saving, the only workaround is saving twice. One to make changes, to second one to 'really' update. I've noticed this because I need to save twice to get real information.

I found this issue: http://drupal.org/node/430274

I thought on running the script in Drupal's User Core but good practices kind of don't let me do it ( for now :) )

Update

I created a Module with this Info

<?php
// $Id: infographic.module

/**
* @file
* Custom functions for this site.
*/
function infographic_user_insert(&$edit, $account, $category) {
    exec('python GenerateInfographic.py');
}

function infographic_user_update(&$edit, $account, $category) {
    exec('python GenerateInfographic.py');
}

Any Suggestion!?

Thanks!

You can use hook_user_insert and hook_user_update to execute your script, which is called after the user has been saved to the database.

Hooks should be implemented in a module. If you are new to module development, the Drupal documentation describes this very well: http://drupal.org/documentation


How to implement a select list that allows for multiple selections? I am creating a content type that contains a field of type "Entity/user reference", and for the widget I want the user to be able to select multiple entities.

I installed and tried the Improved Multi Select module, however I did not find it in the widgets list.

Then I installed and tried the Multiple Selects module, I found it in the widgets list, however it does not work the way it should: it works like a normal select list that allows selecting one entity, it is not giving me the option to "add another item".

How can I fix this? Or does anyone know another way for allowing multiple selection?

From the various attempts you tried, it seems that the reason for your issue is simply that you have not indicated that "multiple values are allow" for this field.

To ensure multiple values are allowed, navigate to /admin/structure/types/manage/mytype/fields/field_abc (assuming 'mytype' is the machine name of your content type, and 'abc' is the machine name of your field). As an alternative, use the "edit" link for your field, within the "manage fields" tab for your content type, after you selected the content type via Admin > Structure > Content Types.

Then within the option that says "Number of values", indicate the "Maximum number of values users can enter for this field.". Note: the default is 1, so if you did not change that yet (eg to 'unlimited'?), then that would explain your issue (and resolve it).


Understanding the source of a 'Failed to get available update data' errors When manually checking module updates for a customer site all modules update OK (and are updating fine) but there is an error saying "Failed to get available update data for 2 projects."

I suspect this is due to a custom theme and/or module that cannot update but with quite a few modules on this site. How can I identify what these "2 projects" are? I can't see anything on the admin site. I tried drush with pm-update with verbose and debug but can't see anything.

I'm assuming once identified that the next step would be to lock those modules.

If I get your question right, I would suggest the following on a terminal:

drush pm-updatestatus 2>&1 | grep "No release history" -B1

This should give you all the projects (modules and themes) that you are looking for.

Cheers!


Settings.php in read only mode? When does drupal settings.php become read-only? I experienced the drupal encountered an error when I was just creating a view. Cannot see the error logs from the admin side. Thought will enable the php error reporting in settings.php and it is shown as read-only? Why does it happen? How can I find the error causing this issue?

When does drupal settings.php become read-only?

Towards the end of the installation process, when the install scripts have finished writing all they need to write to the file.

  Why does it happen?

Because leaving that file writeable represents a security risk.

  How can I find the error causing this issue?

It's not an error, so there's no cause to find.


how to ignore the validation of hidden form fields in the user registration form? I am having a problem regarding the validation of the hidden fields.

I have some some fields that are hidden and only visible if a specific field is selected.

And I marked those those hidden fields as required. So I want to validate those fields only if they are visible and not validate if they are hidden.

I tried the client side validation module but the problem is if I enter the visible required field values then upon submission it also validate those hidden fields.

Any idea?

You need to use #ajax attribute on your specific field to alter the form ( to remove #required for your hidden element ). It lets Drupal re-build the form before submission and core validation. You will need to implement hook_form_alter and an ajax callback function.

Here is a workaround.

function yourmodule_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'user_register_form'){

        $form['toggle_me'] = array(
            '#type' => 'checkbox',
            '#title' => t('Tick this box to type'),
            '#ajax' => array(
              // #ajax has two required keys: callback and wrapper.
              // 'callback' is a function that will be called when this element changes.
              'callback' => 'ajax_form_alter',
              // 'wrapper' is the HTML id of the page element that will be replaced.
              'wrapper' => 'replace_field_div',
              // Don't show any throbber...
              'progress' => array('type' => 'none'),
             ),
        );

        # This field will be shown or hidden when "toggle_me" is checked or unchecked
        $form['dependency'] = array(
          '#type'       => 'hidden', # initially hidden
          '#title'      => 'Dependency',
          '#required'   => TRUE,
          '#prefix'     => '
',
          '#suffix'     => '
',
        );
        // An AJAX request calls the form builder function for every change.
        // We can change how we build the form based on $form_state.
        if(isset($form_state['values']['toggle_me']) && $form_state['values']['toggle_me'] == 1){
            # when "toggle_me" is checked, show this field and set required.
            $form['dependency']['#type'] = 'textfield';
            $form['dependency']['#required'] = TRUE;
        }else{
            # when "toggle_me" is unchecked, hide this field and remove required.
            $form['dependency']['#type'] = 'hidden';
            $form['dependency']['#required'] = FALSE;
        }
    }
}
/**
 * Callback for toggle_me
 *
 * On an ajax submit, the form builder function is called again, then the $form
 * and $form_state are passed to this callback function so it can select which
 * portion of the form to send on to the client.
 *
 * @return renderable array (the textfield element)
 */
function ajax_form_alter($form, $form_state){
    return $form['dependency'];
}

The example shows only two new elements ( toggle_me and dependency ) which are added to user registration form using hook_form_alter. When "toggle_me" is checked, show "dependency" and set required. When "toggle_me" is unchecked, hide "dependency" and remove required.
If you don't know about ajax form alter, download examples module and check ajax example.


How do I get the form field value? The question is clear from the title itself :

I have tried :

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
          $form_state->getValue('field_p_fqdn');
          $form['field_p_fqdn']['und']['#default_value'];
}

where field_p_fqdn is my field name .But both didnt worked . Any idea ??

Depending the field type, it could be:

For exemple for plain text:

$form['field_p_cert_fqdn']['widget'][0]['value']['#default_value']

or

$form['field_p_cert_fqdn']['widget'][0]['#default_value'];

or

$form['field_p_cert_fqdn']['widget']['#default_value'][0];

or for entity reference:

$form['field_p_cert_fqdn']['widget'][0]['target_id']['#default_value'];

or some other thing

I would recommend you to use the devel module: https://www.drupal.org/project/devel (with the kint submodule enable). With this, you can add

dpm($form);

in you alter function to get the structure of the $form.