How can I remove the title in a specific node? I am working in Drupal 7.

How can I remove or hidden the title in a specific node (not in the content type of the specific node)?

You can use  the Automatic Nodetitles module.

  "auto_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.

If you want to hide the title for the particular node or content type, then you should use hook_form_alter().


If there are so many modules in Drupal, are the hard-coded functions reserved only for contributed modules? I read somewhere (cannot recall source) that a programmer was capable of doing extremely complex and tailor-suited web pages using Drupal without writing a single line of code (using hooks), just using the GUI of suitable contributed modules. Is this at all possible?

Are the Drupal 7 (and 8) functions thought as a way of extending capability via contributed modules, or is it good practice to tailor-suit your own functionality via hard-code modifications of SQL queries via hook_views_pre_view, hook_views_query_alter, hook_views_pre_render, theme_preprocess_page and all of these available functions?

I suspect that most of the time being ready to face a difficult project would need to be spent on trying dozens of different contributed modules, mutual compatibility, flexibility, etc., in order to reduce the custom code you would need.

I am not sure about this commentator being truly honest, but I find difficult not to create my own custom modules and modify queries, template.php, etc., in order to get the desired results, sometimes even by fixing long existing bugs in some contributed modules.

Only using Site Building features (no custom module development yet) should get you pretty far (if not far enough ...).
The Relativity Data Model for Drupal
Have a look at the (illuminating) article "Relativity Model for Drupal", for which this is an introduction to it (quoted from this linked page):

The Relativity Data Model for Drupal is a zero-custom-code, collection of steps, procedures and methods that strive to help site builders, users and site visitors interact with Drupal in a far easier and more efficient way. This is done by:

Data architecture and data modeling merging as a single step through a documentation procedure.
Customized user interfaces that cater to individual workflows throughout permission roles.
Multi-level relational data structures that relate to other multi-level relational structures.
Mimicking the concept of database joins within Drupal's UI's.
Vastly reducing the size of Drupal sites by a small handful of modules that provide greater power, speed and expansion capabilities.

The small handful of modules (cfr. the last bullet) is like so (apart from Drupal core):

Chaos tool suite (ctools)
Date
Entity API
Entity reference
Entity connect
Field Group
Token
Pathauto
Views

Note: this same topic is also presented in the video "Revolutionary DRUPAL Data Modeling Concept!! (This will change your Drupal life!)".
Typical add-on modules
Even though that small handful of modules above can get you already extremely far, I often add a subset of other contributed modules to it also, as further detailed below.
Business logic
Using the Rules and Flag module, it is possible to implement all sorts of business logic (= rules), simply using the typical Drupal admin UI for those modules.
Queries, custom reports and charts

To perform queries (listings, etc), use the Views module, possibly further extended with modules such as Views Slideshow: Galleria (there are dozens of modules to further enhance views).

The Forena module can be used as a supplement / alternative (e.g. if you'd need to also create charts or so, or if you have a need to access data in some external database such as MS SQL, Oracle, etc).
Using the Forena integration with the Feeds module it is possible to import data blocks and reports as Drupal nodes or Drupal users. For a tutorial about the available features check out the video about How to import data and reports based on data as Drupal nodes.

Create charts using the views integration of the Charts module to visualize a lot of data in a way that can be quickly digested.

Page Layout
Modules like Display Suite and/or Panels can help to enhance the look and feel of it all also.
Many more modules

Group (a pretty new alternative to Organic groups, to create arbitrary collections of your content and users and grant access control permissions on them).
Workflow (to create arbitrary workflows, and assign them to entities).
IP Geolocation Views & Maps, a mapping engine to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet)
Or, or  ... on and on goes the list.

Disclosure: I'm a (co-)maintainer of Forena and Charts.


Active trail not producing expected results I'm writing a very simple module to alter the active trail on specific pages.  Observe.

function alter_breadcrumbs_menu_breadcrumb_alter(&$active_trail, $item) {
  if (substr($item['href'], 0, 4) == 'user') {
    $num_crumbs = count($active_trail);
    $people = array(
      'href' => 'people',
      'title' => t('People'),
      'localized_options' => array(),
    );
    $active_trail[] = $people;
  }
}

The profile page by default has the breadcrumb 'Home'.  I have a directory page that has a list of users with links to their profile pages.  This page is located under /people.  So, on the user page, I want the breadcrumbs to look like 'Home > People > John Smith'.

I expect the code above to produce 'Home > People', but it doesn't.  Instead, it produces 'Home > jsmith > People'.  It puts in jsmith instead of John Smith because John Smith is derived from custom first and last name fields, but the crumbs currently just take the user's username by default, so ignore that fact for now.  What it comes down to is I don't understand why it's pushing on the username crumb and the People crumb, rather than just the People crumb.  Any insight would be helpful.

Cheers.

It looks like your adding $people to the end of the array, you have to insert it in second place, using http://php.net/manual/en/function.array-pop.php you can do something like this (untested):

$name = array_pop($active_trail);
$active_trail[] = $people;
$active_trail[] = $name;


D7 module for payment associated to a node? I am looking for a D7 module that will allow users to make a payment that is related to a node. So let's say I have a content type called 'Events', and have lots of nodes in the 'Events' content type, I want users to be able to pay in order to attend one of these Events. So maybe the user would view an Events node, and then they can pay for the node (not to view it... but pay for what the node is offering: e.g. an event)

Anyone know of anything??

I don't want to use Drupal Commerce because I don't want a shop per se, I just want to take payment related to a node.

Thanks so much!

There are a number of options. Drupal Commerce is obviously really powerful, but if you want something light take a look at the Drupal Pay module. It is pretty light weight and integrates with webform and a number of other modules.


Access to block edit icon I am trying to create a solution programmatically where I can give access to edit a particular block to a user.

I know using hook_entity_access() I can grant permission to the user to access the block, But the block doesn't show the "edit" icon which I need to help the user to navigate to the edit page.

I found the solution for it.

to reach to the edit button hook_entity_access() is the correct Hook but to provide access to that block content, we first need access to class

Drupal\Core\Access\AccessResult

then to provide access we need to return

AccessResult::allowed()

A complete example where we might want to give access to a block_content would look like this.

Use Drupal\Core\Entity\EntityInterface;
Use Drupal\Core\Session\AccountInterface;
Use Drupal\Core\Access\AccessResult;

function block_user_access_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {

  if($entity->getEntityTypeId() == 'block_content'){
    return AccessResult::allowed();
  }
}


Drupal equivalent of WordPress' page templates I'm developing my first Drupal site, having built my CMS experience on WordPress. I've managed to wrap my head around many of Drupal's paradigms, but I can't figure out how Drupal accomplishes the functionality of page templates in WordPress.

By "page templates" I mean the option in WordPress to set a specific template (written in PHP) to use for a given page:

For reference, I use the templates in multi-site deployments to create standardized pages for subsites (e.g. "contact", "about us"), but a subsite has the ability to disable the template and create their own content.

What would be the best practice to accomplish this?

There are several ways to suggest/override theme of a page in Drupal.

1. Override core theme files:

Firstly there are core themes defined by Drupal, which can be overridden from your theme. For example, the default user profile page uses user-profile.tpl.php. Though this is defined in Drupal Core, you can override it by copying it to your theme folder and modifying. The list of core file can be found here.

2. Default Theme Suggestions in Core

Drupal has implemented some default theme suggestion patterns in the core. It helps us write a specific theme for a page, path or even a particular article without having to write code. For example, if your about page has a node id 1. You write a template for just that page by creating a template file page--node--1.tpl.php in your theme folder. Similarly, you can suggest a theme for a node, user, block etc.  You can see available core suggestions in this page under respective heading.

3. From UI using context module:

Context module allows you to manage contextual conditions and reactions for different portions of your site. You can, for example, choose 1 or more conditions like path, user type etc and then add theme suggestion as a reaction to that condition/s.

Using context module.
Also, see ThemeKey module.

4. From code:
You can also write custom theme suggestion based on your own logic from code, either in template.php file of your template from a custom module.

An example from documentation:

// Add a single suggestion for nodes that have the "Promoted to front page" box checked.

function drop_preprocess_node(&$variables) {
  if ($variables['promote']) {
    // looks for node--promoted.tpl.php in your theme directory
    $variables['theme_hook_suggestions'] = 'node__promoted';
  }
}

A lot of code example can be seen if you scroll a bit down on this page.

Additionally, change the theme debug settings in setting.php to get additional information in HTML markup with respect to the theme. The setting to change is $conf['theme_debug'] = TRUE;. Once done, you'll get a lot of valuable suggestion in the HTML markup of each page.


Commerce form refresh: 500 error on /en/system/ajax Where can I find more information about this error? Nothing is appearing in logs, the error message itself has no useful data.

An AJAX HTTP error occurred.
HTTP Result Code: 500 Debugging information follows.
Path: /en/system/ajax
StatusText: Service unavailable (with message)

Some background info:

Just grasping at straws this point, and may actually completely rework how this feature will work, but just in case anyone has any bright ideas:

Product variations exist in Commerce, certain options refresh the form via Ajax (this is a built-in commerce function), and on refresh any attribute/field that is no longer available is not included with the refreshed form. Again, total standard Commerce function.

I have used a few modules to help me create variations, such as Bulk Product Creation, and as recently has 1 month ago used the exact same process to do this successfully. That product is still working.

When I inspect the ajax call itself there's nothing really unique to this vs. the other working product(s).

I have tried eliminating variations, increasing PHP memory/POST stuff, etc., and have also turned on full error reporting.

Answering my own question so my stupidity is saved for all to learn from.

More details can be found in the "Reports" section of the site.

I have now resolved my issue, and it was a line of code in a custom module we made.


Displaying geo data on openlayers Is there any module I can use to display limited points on OpenLayers using bbox-filtering in Drupal?

try http://drupal.org/project/views_geojson

with the latest version of views_geojson and openlayers you can define a view (of type geojson) that accepts a bounding box as a parameter.

With openlayers you can set the layer to use a bbox strategy so when you drag the map around it will send the bbox coords to the geojson view and just return points within that area.

I am new to Drupal and Im not going to lie this was a bit of a bastard to setup because there is not much documentation. I couldn't get the bbox contextual filter to work so I setup a custom filter that used top,bottom,left,right then wrote a rewrite rule in an .htaccess file that split the default parameter passed from the openlayers front end (a GET variable like BBOX=42,124,43,125) into the four filter parameters. This will NOT work if you expect your map to cross the equator or 0 meridian. But it works for me and I still hope to get contextual filters working at somepoint.


How to add embedded YouTube video at the end of ViewSlideshow - Drupal 6 I have a Slideshow view which loads two fields, main images ('group multiple values' unchecked to create rows) and video ('hide if empty' checked). It takes these from one node which it gets from the nid argument.

The slideshow currently displays 13 images but each image also has a seperate instance of the video attached to it.

I've tried playing about with the views-slideshow.tpl.php file and I've also tried excluding the video from display then manipulating the view ovject from withing hook_views_prerender() and hook_preprocess_views_view(), all with no luck.

I just want the 13 unique images with the single instance of the video link added to the end, therefore creating 14 unique slides. Ideally I would want to add 2 or 3 videos so the solution needs to account for this.

One of our Drupal Developers has written an article on the subject of creating Slideshows in Drupal using embedded Youtube Videos. Take a look, maybe it may help you to sole your problem. http://wearepropeople.com/blog/how-to-create-slideshows-with-embedded-youtube-videos-in-drupal-7


Select the right pathauto alias for a node I'm working on a drupal 8 project, I need to access the content type X nodes via two aliases depending on some conditions, for this I've created two Pathauto patterns using Pathauto contrib module:

path_1 --> /local/[node:title]

path_2 --> /global/[node:title]

path_1 & path_2 are supposed the machine name of those two patterns.

What are those two patterns? actually what I want to do is check if a node of type X has the checkbox field 'global' checked so use /global/[node:title] as alias for this node else use /local/[node:title].

Which hook should I implements for selecting/altering a pathauto pattern for a node? And can I use those aliases as a route for a controller?

Another option, and I find this to be preferable to altering the token because it's exposed to site builders and makes what's happening perfectly clear in the UI, is to create your own custom token that will return /global or /local for that piece of the url. You just need to implement hook_token_info and hook_tokens. This blog post walks you through the process.

Ex:

/**
 * Implements hook_token_info().
 */
function MY_MODULE_token_info() {
  $info['tokens']['node']['MY_TOKEN_ID'] = [
    'name' => t('MY TOKEN LABEL'),
    'description' => t('Return "/global" for nodes with the global checkbox checked, otherwise returns "/local".'),
    'type' => 'url-fragment',
  ];
  return $info;
}

/**
 * Implements hook_tokens().
 */
function MY_MODULE_tokens($type, $tokens, array $data, array $options, Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $replacements = [];
  if ($type == 'node' && !empty($data['node']) && isset($tokens['MY_TOKEN_ID'])) {
    $node = $data['node'];
    $global_or_local = '/local';
    if ($node->hasField('MY_GLOBAL_FIELD') && !empty($node->MY_GLOBAL_FIELD->value)) {
      $global_or_local = '/global';
    }
    $replacements['[node:MY_TOKEN_ID]'] = $global_or_local;
  }
  return $replacements;
}

Note: I'm not sure if that logic to determine global or local is perfect, but it should be close.


How to get $nid inside hook_menu_alter function I'm trying to show or hide a menu tab based on whether my node meets a certain condition. In my hook_menu_alter I can't seem to get the $nid even though I was under the impression that the menu_alter fired after node load...

I've been googling for a day now and trying different solutions, but just can't seem to access the $nid.

When I print arg(0) or $_GET['q'] I get the result "admin_menu/flush-cache" instead of "node/62" even though I'm on a node page... what am I missing?

Menus are cached; unless you have something funky going on, loading a node won't rebuild that cache (it would be frightfully expensive to do so).

You need to make 'live' decisions in a callback, e.g.

function MYMODULE_menu_alter(&$items) {
  $items['foo']['access callback'] = 'MYMODULE_access_callback';
}

function MYMODULE_access_callback() {
  $node = menu_get_object();
  if ($node && $node->bar) {
    return TRUE; // Allow access.
  }

  return FALSE; // Default for anything that doesn't match your criteria.
}

The above is a contrived example, real-world will be different depending on exactly what you need to do.


Notice: Trying to get property of non-object I have created a module, and I am trying to use the following code:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_state['view']->name == 'album1') {
    // ...
  }
  // ...
}

The line that causes the error is the following one:

if ($form_state['view']->name == 'album1') {

The error I get is the following one:

  Notice: Trying to get property of non-object in mymodule_form_alter() (line 15 of C:\xampp\htdocs\drupal\sites\all\modules\mymodule\mymodule.module).

$form_state['view'] is not defined for all the forms, and it is not a value set by Drupal core modules. Before to access $form_state['view']->name you should verify $form_state['view'] is defined, and it is an object (and not an array, for example).


How do I alter the complete url, not just the path, of nodes? When a node's field "External URL" is filled, I want the URL of this node to be that field's value wherever it is rendered/ teasered.

Writing my own service and class using (implementing) InboundPathProcessorInterface and OutboundPathProcessorInterface I can only alter the path, but the base url still gets prepended.

So, whats the correct way?

I thought maybe extending the entity and extending the toURL() function might be the trick, but that seems like a lot of work for a simple feature, does it not?

Edit: I know I can just setup redirects, but for the sake of completeness I'd like to know.

InboundPathProcessorInterface can't do it, that's an incoming request, it has no way of redirecting to another site, because that's what you have to do.

Implement something similar to redirect.module: a request subscriber that sets a redirect response.

For outbound processing, that definitely works, but you have to set the right options. Have a look at how \Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl::processOutbound() sets the language domain.


How to export content from dev environment for deployment to production environment? We have to deploy content of around 37 content types from development to production environment. Each content type is having around 10 to 12 nodes.
So, we have around 360 nodes for migrating to production environment.

How can i proceed it with at drupal end ?

I haven't done it myself but a colleague of mine had to do this last week. It's just exporting and importing the database. He used HeidiSQL with this link: https://support.appliedi.net/kb/a1034/how-to-import-and-export-a-mysql-database-using-heidisql.aspx


How do I get hex value for field categoryhex on creating category? I want to create a new category to my Drupal site but I need to set an categoryhex but I don't know which value I need to set here.

Thanks for your help.

That hexadecimal value of the color. You can get the hex value of the color from here - http://www.w3schools.com/html/html_colornames.asp
http://www.color-hex.com/color-names.html


Using PHP cURL to send http get request I am able to do the HTTP GET request using cURL in my custom function, my code below works fine for me, but is there Drupal way to do this?

function some_page_callback() {
    $url = 'https://api.example.com/data';
    $accesstoken = 'SoMedGFidHThX2NvdW50eV90bWNhOkEyakJEM2ND';
    $headr = array();
    $headr[] = 'Accept: application/json';
    $headr[] = 'Authorization: Basic '.$accesstoken;

    //cURL starts
    $crl = curl_init();
    curl_setopt($crl, CURLOPT_URL, $url);
    curl_setopt($crl, CURLOPT_HTTPHEADER,$headr);
    curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($crl, CURLOPT_HTTPGET,true);
    $reply = curl_exec($crl);

    //error handling for cURL
    if ($reply === false) {
       // throw new Exception('Curl error: ' . curl_error($crl));
       print_r('Curl error: ' . curl_error($crl));
    }
    curl_close($crl);
    //cURL ends

    //decoding the json data
    $decoded_data = json_decode($reply, true);

    // putting the data into table
      $rows = array();

      $output = '';
      // Example of theme_table().
      $output .= '
Example
';
      $headers = array(t('ID'), t('Name'));

      foreach ($decoded_data['data'] as $line) {
          $tablerow = array(
          array('data' => $line['id']),
          array('data' => $line['name']),
         );
          $rows[] = $tablerow;
      }
      $output .= theme('table', array('header' => $headers, 'rows' => $rows));

return $output;
}

I ended up needing to do something like this not too long ago in a custom module. Drupal has a function called drupal_http_request() to hit the external URL. You can execute it inside a hook function if necessary in your module.

$url = 'http://my-url.com';
      $response = drupal_http_request($url);


In which cases should hook_process() and hook_process_HOOK() be used? Considering that some modules implement hook_process() to alter the content of some variables and replace their content with themed content, in which cases should a module implement hook_process() instead of hook_preprocess() (or hook_preprocess_HOOK())?

function rdf_process(&$variables, $hook) {
  // Handles attributes needed for content not covered by title, content,
  // and field items. It does this by adjusting the variable sent to the
  // template so that the template doesn't have to worry about it. See
  // theme_rdf_template_variable_wrapper().
  if (!empty($variables['rdf_template_variable_attributes_array'])) {
    foreach ($variables['rdf_template_variable_attributes_array'] as $variable_name => $attributes) {
      $context = array(
        'hook' => $hook,
        'variable_name' => $variable_name,
        'variables' => $variables,
      );
      $variables[$variable_name] = theme('rdf_template_variable_wrapper', array('content' => $variables[$variable_name], 'attributes' => $attributes, 'context' => $context));
    }
  }
  // Handles additional attributes about a template entity that for RDF parsing
  // reasons, can't be placed into that template's $attributes variable. This
  // is "meta" information that is related to particular content, so render it
  // close to that content.
  if (!empty($variables['rdf_metadata_attributes_array'])) {
    if (!isset($variables['content']['#prefix'])) {
      $variables['content']['#prefix'] = '';
    }
    $variables['content']['#prefix'] = theme('rdf_metadata', array('metadata' => $variables['rdf_metadata_attributes_array'])) . $variables['content']['#prefix'];
  }
}

I'll try to stay away from explaining the whole theme system. The order and use of the functions is best explained here.

Preprocessor functions run before process functions. You should run hook process for cases where you want to affect every theme call after all the preprocessors have run. (Well, I believe it is only every theme call with a .tpl file.)

RDF is a good example as it wants to insert meta data into every theme template. But in most cases it is not something you would want to do. Another example would be something like the Pirate module.

Preprocessors are more targeted. If you only want to change lists for example you could use a preprocess hook there. I believe that hook_preprocess_HOOK()s are run for templates and functions.

hook_preprocess() can be used in a theme if you wish to preprocess something which is not overridden in your theme, as the theme_preprocess_HOOK() won't trigger unless you do.


Get translated taxonomy terms with Entity Translation I'm using Entity Translation for Taxonomy Terms.

I've a Cities Vocabulary and I need to get translated names of some 1600 cities.

Using taxonomy_get_tree without arguments returns the term names in English. However if I pass the last parameter $load_entities= TRUE then it currectly returns $term->name as translated one.

But it seems fully loading 1600 terms by setting $load_entities can slown down the site performance heavily as mentioned in the api page.

Is there any faster way to do it?

I'm thinking of caching the results in a temp file. Or can use some query as in When using Entity Translation and the Title module, how can I get the translated term from the term ID programmatically? to fetch it myself.

You are using Entity Translation, so keep in mind there can't be any translated term load because you're translating fields not whole term. Term will load by

$term = taxonomy_term_load($tid);

use in devel mode or by dpm see the $term object. There you'll see structure

$term->name_field['en'][0]['value']

You can fetch it this way or by field_get_items() for en language.

$name = field_get_items('taxonomy_term', $term, 'name_field', 'en');

AND

$term->name_field['fr'][0]['value']

You can fetch it this way or by field_get_items() for fr language.

$name = field_get_items('taxonomy_term', $term, 'name_field', 'fr');

This is how you can get the data per language


Make phone calls from a Drupal site When looking at a user's profile page, I'd like to be able to make a phone call to the user whose profile I'm viewing.  Is this possible in Drupal 7?

You could use the tel: or callto: href identifiers depending on the method of your phone call (Skype uses callto:, mobiles that support this feature will use tel:.

For example, if the number is 123-456-789, your link would look like one of the following:

Call this user

or

Call this user

Check this (old) blog post for some examples/ideas on implementation.


Drupal 7 -- Would like to use unique profile template per role I'm working on a Drupal project where we have two main roles (students/teachers) + an admin role. I would like to have entirely different profile pages for the different roles.

At the moment I think the most maintainable method for doing this is going to be to have several profile template files that are called when the specific role is being viewed; I'm just not sure how to preprocess the profile to hint at the correct template.

At the moment, I've built some page pre-processing code to check the role of the profile page we're looking at as follows:

function MYTHEME_preprocess_page(&$vars, $hook) {

  // See if we can influence profile pages
  $content = $vars['page']['content'];
  $theme = $content['system_main']['#theme'];

  if($theme == 'user_profile') {
    $roles = $content['system_main']['#account']->roles;

    if(in_array('teacher', $roles)) {
      $vars['theme_hook_suggestions'][] = 'teacher__user-profile.tpl.php';
    }
    elseif(in_array('student', $roles)) {
      $vars['theme_hook_suggestions'][] = 'student__user-profile.tpl.php';
    }

  }

}

The conditional correctly identifies the profiles being for teachers or students but I can't seem to influence it by suggesting a profile template.

Any thoughts?

Thanks,
Andrew

Have a look at ThemeKey.
From the project page (emphasis added):

ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules. In combination with Drupal's theme inheritance you can easily achieve features like:

individually-styled channels
a front-page / "splash" screen
a date/time-selected Christmas theme
mobile themes for different auto-detected mobile devices
special themes for "limited" or "old" browsers
content, user, or role -specific themes
indicating your environment (production, staging, testing, sandbox, … )
testing your redesign safely on a live server


How can we catch the acces denied exception? I've run into a case where users need to be redirected to the login page when they try to access a page without having the permission to access it.

How can I catch an exception  of the AccessDeniedHttpException class?

To catch the access error you can use a symfony event listener:

  If your listener calls setResponse() on the
  GetResponseForExceptionEvent, event, propagation will be stopped and
  the response will be sent to the client.

http://symfony.com/doc/current/controller/error_pages.html#working-with-the-kernel-exception-event

This is an example how to return a GetResponseForExceptionEvent event:

Drupal\Core\EventSubscriber\CustomPageExceptionHtmlSubscriber

public function on403(GetResponseForExceptionEvent $event) {
    $custom_403_path = $this->configFactory->get('system.site')->get('page.403');
    if (!empty($custom_403_path)) {
      $this->makeSubrequestToCustomPath($event, $custom_403_path, Response::HTTP_FORBIDDEN);
    }
  }

For your own Event Subscriber extend DefaultExceptionHtmlSubscriber.

class MyCustomPageExceptionHtmlSubscriber extends DefaultExceptionHtmlSubscriber

See the complete example:

http://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/EventSubscriber/CustomPageExceptionHtmlSubscriber.php

which extends

http://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/EventSubscriber/DefaultExceptionHtmlSubscriber.php

You would have to use a higher priority, so that your code will run first.

In most cases it might be easier to configure a url pointing to a custom controller here:

/admin/config/system/site-information

BTW the example code above is how core implements this configuration.


How to use drush download file plugin (drush_dlf) project page has no information How to use this plugin?

https://www.drupal.org/project/drush_dlf

  Drush Download File is a drush plugin that allows you to download files and place them in locations. This is behavior similar to what a make file can provide except you won't need to write a make file in order to get a file and put it in the right place.

This is what I am looking for, but there is not documentation, how can I do this?

I tried:

c:\source\sites\all\modules>drush drush_dlf
The drush command 'drush_dlf' could not be found.  Run `drush[error]

Not sure how to do this....

If you would like to install the Drush extension drush_dlf, run:

drush dl drush_dlf

If the module you download is a Drush extension (has a .drush.inc file but no .module file), then Drush will put it in $HOME/.drush, where it will be findable by Drush.

If the module you download has a .module file, then Drush will put it in the appropriate modules directory (DOCROOT/modules for Drupal 8, or DOCROOT/sites/all/modules for Drupal 7). In this instance, the command will only be available for that one site.

To stipulate where the downloaded extension should go, you can add --destination=$HOME/.drush (or some other location). Use caution when doing this with any extension that has a .module file, though, as some of these are designed such that they only work when their module is available and enabled.

Finally, note that Drush caches the location of all of the available Drush extensions.  If you add a new extension, you must run drush cc drush before your new command will be available.  Drush does this automatically if you use drush dl to install the extension, but you must do it manually if you copy the files into $HOME/.drush yourself.

Finally, with regard to Drush Download File, the behavior it purports to provide could also be implemented with a simple shell script that simply called drush dl repeatedly, as Drush dl will already place the files where they belong.  Using drush make or composer is generally preferable, but just using drush dl directly is an option if you don't want to do that.


Show a PHP page in drupal 7 I have a php script that does some querying and book keeping of drupal tables. How can I run this php script directly from the url? The script uses drupal functions so I guess it should be aware of the API.

When I go to mysite.com/script.php I would like this file to run...

Is there any includes that I can add and then run the script so that it is drupal aware and at the same time, does not need to go through all the view/node/block etc? Basically I do not want to add this page as a PHP block data into one of the nodes, I would like to run in directly from the URL.

you should boot drupal on your file so that your file be aware of drupal functions,you can do this by :
YOUR_DRUPAL_ROOT= root of your drupal,here my drupal root was crawler.alexa.com. and
require bootstrap.inc of your drupal.
and then boot drupal compeletly.
here is my example :

define('DRUPAL_ROOT', '../crawler.alexa.com');
require_once '../crawler.alexa.com/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


Not able to post comment anonymously: getting 403 error I am working on phonegap app and using drupal 7 as backend for all json request data. I am using the service module for it. At frontend I am using Angular js in phonegap.

I referred http:// drupal.stackexchange.com/questions/22277/creating-comments-and-nodes-with-services-3-x-and-json for posting comment.

I set permission for anonymous user to post comment to any node from drupal permission section. But its not posting any comment. Giving me error.

  /appapi/comment.json 403: Access denied for user anonymous

Here is my code:

var dataObj = {"subject":$comment.text, "comment_body":{"und":[{"value":$comment.text}]}, "nid":$comment.nid} ;

var res = $http.post($scope.apiBaseUrl+'/appapi/comment.json', dataObj,{ withCredentials: false, headers: { 'Content-Type': 'application/json'} }); res.success(function(data, status, headers, config)
{ //$scope.message = data;
console.log(data);
 });

Here is CROS module setting:

*|*|POST,GET,PUT,DELETE|Origin, X-Requested-With, Content-Type, Accept|false

I am sending comment post request from phonegap app. I am not using the AgularJS module.

Thanks  tyler.frankenstein. Thanks for suggesting angular-drupal.
I integrated it with my agularjs ui and its working superb.

I gone through angular-drupal code and found that it need X-CSRF-Token in header for write operation. Accordingly i modified my CORS setting

*|*|POST,GET,PUT,DELETE|Origin, X-Requested-With, X-CSRF-Token, Content-Type, Accept|false

And used agular-drupal method to save comment. Here is my code.

//register drupal service as provider/injector
.factory('$drupal',['drupal', function(drupal) {
  return drupal;
}])
.
.
.
//inside controller

.controller('HomeCtrl', function($scope, $stateParams,$http,$state,$drupal) {

  $drupal.node_load(27).then(function(node) {
    console.log(node.title);
    alert(node.title);
  });

  var comment = {
  nid: 27,
  subject: 'Hello world',
  comment_body: { und: [ { value: 'How are you?' } ] }
};
$drupal.comment_save(comment).then(function(data) {
    alert('Created comment: ' + data.cid);
});

Other way to achieve this without angular-drupal is to generate x-csrf-token using get request "/?q=services/session/token" and then set it in header for your post request.

Thank you.


How to fetch a single value with an entity metadata wrapper? Say I want to fetch a single value from the node table: I could use the database API:

$value = db_query('
  SELECT title FROM {node} WHERE nid = :nid
', array(':nid' => $nid,))->fetchField();

What is the equivalent using an entity metadata wrapper?

Thanks.

Well you could use:

$node = node_load($nid);
$wrapper = entity_metadata_wrapper('node', $node);
$title = $wrapper->title->value();

But if that's literally all you need to get from the node, an EntityMetadataWrapper is overkill in my opinion. Just use:

$node = node_load($nid);
$title = $node->title;


Does anyone know of a module like "Artsy Editor" for Drupal? I'm looking for a writing interface similar to Artsy Editor which is built for Wordpress.

It's a "distraction-free" wysiwyg that I need for a client's site and thus far I've not been able to find one.

Does anyone have suggestions on an existing editor that I can use, or a way to use existing modules to achieve the same effect?

I'm really looking for a way to have a wysiwyg style interface similar to the new "notes" in the new version of basecamp.

The site in question is a Drupal 7 site.

There's no module for Artsy Editor.
But if you mean inline editor, you can use Edit for Drupal 7 and 8 - In-place editing for fields on any entity. Including WYSIWYG editing powered by CKEditor or Aloha.
"Edit" is part of Spark - Drupal distribution which aims to be "the Pressflow of Drupal authoring experience


Dynamic Persistent Menu problem / module alternatives I'm using Dynamic Persistent Menu (DPM) but I can't make it work. I have a Main Menu, most of the items have children, and since I don't want those parents to be links I'm using Special Menu Items module (I mention this in case there could be a conflict).

I installed DPM; then go to config > User interface > DPM, add new and select Main Menu as the Menu Root and save. I haven't found any steps to follow from there, so I figured that was it, but the children items do not show up. I tried enabling the DPM block but then I get a blank site.

Anyone who has used this module, could you guide me through it? I need the exact functionality this module provides, and from what I've seen neither Superfish nor Nice Menus modules can do this.

Thank you for any help :)

Yes, as you mention, their is a conflict between the Dynamic Persistent Menu and Special Menu Items modules.

Dynamic Persistent Menu adds a CSS class (.dynamic-persistent-menu-menu-item) to all <li> elements of a menu that is overridden by Special Menu Items.

This bug comes from the special_menu_items.module file, line 64. You can remove the following code:

$element['#attributes']['class'][] = 'nolink';
$element['#attributes']['class'][] = 'separator';

EDIT: The main bugs come from Dynamic Persistent Menu. As you know, the class attribute passed to theme_menu_link() should be an array, but in Dynamic Persistent Menu a string is passed.

So your WSOD (blank page) comes from theme_dynamic_persistent_menu_menu_item() in Dynamic Persistent Menu, where a string is passed instead of array.

When Special Menu Items tries to override it, a fatal error is presented.


How to build a block on form submission? I know how to build a block using these functions :

hook_block_info()
hook_block_configure()
hook_block_save()
hook_block_view()

But on a form submission a few information is saved into DB and based on those information one block must be created.  how do I can build a block in that way?

I will encourage you to look at bean contributed module. Using this you can create block types whose instances can be created using bean_create function.

Example snippet:

$values = array(
  'delta' => 'test_bean',
  'label' => t('Test Bean'),
  'title' => t('Test Bean'),
  'type' => some_block_type_that_you_will_create_through_UI,
  'view_mode' => 'default',
  'data' => array(
    'test_boolean' => FALSE,
    'test_string' => t('New String'),
    'test_array' => array(
      'test_array_1' => 'new_value',
    ),
  ),
);

$bean = bean_create($values);

The bean content (block) can then be placed around the site just like any other block.


Remove AJAX in views form (on change) I have a problem with a views form. It should only be submitted when I hit the submit button. Currently it is submitting when I change a value in any textfield. When I select "Using AJAX: no" it doesn't change anything. :/

Can somebody help me out here?

Thanks!

You have to change the settings in view as follows

Go to view and find Exposed Form (under Advanced).
Click on Settings

3.Uncheck 'Autosubmit' option to prevent 'Automatically submit the form once an element is changed'.

4.Click on Apply and save the view.

That's it.


Can't manage display for article I have done something and can no longer edit the manage display pages for the article content type .  When I try to visit them I fall out of the usual rich html interface into a page whose code is attached below.  I think that this is happening because I have accidentally damaged or removed the full content view mode for the article, but I am a newbie so I am really not sure.  I was playing with Display Suite when this problem began.

Any ideas what is going on? and how to fix it?  Thanks.

You are here

Home » Administration » Structure » Content types » Article

Article

Add to Default shortcuts

Primary tabs

Edit

Manage fields

Manage display(active tab)

Comment fields

Comment display

Secondary tabs

Default(active tab)

Teaser

Content items can be displayed using different view modes: Teaser, Full content, Print, RSS, etc. Teaser is a short format that is typically used in lists of multiple content items. Full content is typically used when the content is displayed on its own page.

Here, you can define which fields are shown and hidden when Article content is displayed in each view mode, and define how the fields are displayed in each view mode.

Did you enable text format as Full Html.

In your html code there were two closing div are missed. here is the closing div added.

You are here

Home » Administration » Structure » Content types » Article

Article

Add to Default shortcuts

Primary tabs

Edit

Manage fields

Manage display(active tab)

Comment fields

Comment display

Secondary tabs

Default(active tab)

Teaser

&nbsp;

Content items can be displayed using different view modes: Teaser, Full content, Print, RSS, etc. Teaser is a short format that is typically used in lists of multiple content items. Full content is typically used when the content is displayed on its own page.

Here, you can define which fields are shown and hidden when Article content is displayed in each view mode, and define how the fields are displayed in each view mode.


Creating a sortable table in the backend? I want to create a custom view where informations are shown in table format. In the backend i want to create a view like this:

Do you know a module to achive this? Or how would you create  a module for that?
Any hints are greatly welcome!

Thanks a lot!

If by view you mean that you want to create a custom module page for administrators, check out Examples modules, especially tabledrag_example and tablesort_example.

However, if you want to use Views, check out DraggableViews module.


Where can I get permission string to use with user_access? There is a long permission list at admin/people/permissions.
For example there is permission with title Article: Edit any content.
But where can I get the string which can be used with function user_access()?

Pop Devel on your site and head to yoursite.com/devel/php and enter the following:

$permissions = module_invoke('node', 'permission');
dsm($permissions);

The key for each part of the array will be the string you want to apply the permission.

The following will get a list of permissions on every enabled module on your site (modules sorted by name):

foreach (module_list(FALSE, FALSE, TRUE) as $module) {
  if ($permissions = module_invoke($module, 'permission')) {
    // Print the module title
    dsm($module);
    // Print the permisions
    dsm($permissions);
  }
}


Remove default "Home" link? In Drupal 8, there is a 'Home' link in the "Main Navigation" menu provided by core. However, you can only disable this link, you cannot delete it.

How can I remove it? I don't need it and would rather just delete the menu link but the admin is prohibiting it. I had an issue where a content editor tried to set the menu link of a node to 'Home (Disabled)' by mistake - which caused a WSOD I have not yet diagnosed (somewhere when rendering the menu and/or breadcrumb on the page). Changing the menu link to <Main Navigation> root fixed this behavior, but I don't want it to happen again, so, I would like to delete it.

I opened a drupal.org bug report on 20 december 2016 for this exact same request. The patch passes all tests and is now in the "Needs review" stage. Feel free to test the patch and mark the issue as RTBC.


How to add drupal contributed modules into a custom module I've done a custom module to generate some forms. There is a image field present. I would like to add cropping functionality in image field.

I've seen that is very interesting the Imagefield Crop module. I would like to use it in my code.

So, my question is: Is there any way to add this module functionality into my image field?

Edit 1:

This is my code:

$form['imagen'] = array(
        '#title' => t('Image'),
        '#type' => 'managed_file',
        '#upload_validators' => array('file_validate_extensions' => array('jpeg jpg png gif')),
        '#upload_location' => 'public://',
        '#progress_indicator' => 'throbber',
        '#status' => FILE_STATUS_PERMANENT,
        '#progress_message' => 'One moment while we save your file...',
    );

It is necessary for our company to generate the forms in a custom module, because we need to process data in a special way, that with drupal content type is not possible.

So, I feel totally lost. It is posible to do something like a reference or something similar to use image_crop??

Thank you in advanced.

If any module is providing its API, than you can use its api.Image Field Crop is not providing any API so you can call any method from that module directly. Don't forgot to add contributed module name  as a dependency in your custom module info file.


unserialize() return empty I have a variable that holds a serialized string that I want to convert back into a PHP Array.

$str = 'a:1:{i:0;a:3:{s:2:"id";s:24:"xxxxxxxxxxxxxxxxxxxxxxxx";s:11:"description";s:3:"Two";s:9:"users-idt";s:36:"x6543rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrd";}}';
$arr = unserialize($str) // returns an empty;

But when I take the same string an run unserialize() on it outside Drupal, it works perfectly. Could this be a drupal issue?,

Using Drupal 7

Cant see how it could be drupal, how are you determining that its returning empty? Are you doing a

var_dump($arr); die;

directly after your code?


I am facing issue while posting on twitter using publish_away module? I am getting the following message while submitting the message.

  There was an error 401 from Twitter. Visit Twitter HTTP Status Codes page to understand what is going wrong.

I don't find where I am wrong? Anything specific I am missing in twitter setting?

I have set all the tokens correctly. Attaching screenshot below :

I tried the module and it works fine. Follow these steps to enable auto posting to Twitter.

Go to https://apps.twitter.com, and click "Create New App".
In Application Details, enter the name of the App, enter some description, in website enter http://example.com, leave callback URL empty.
Agree with the user agreement after reviewing it, and click "Create new app".
Go to "Keys and Access Tokens" tab.
Please make sure you give "Read, write, and direct messages" access level to the app.
Click on generate the Access token. Keep this page open.
In a separate tab open http://example.com/admin/config/services/publish-away after logging in as admin.
Enter "Consumer key", "Consumer secret key", "Access token", and "Access token secret" from the app.
Hit Save. The account should now appear under the "Accounts" section.
Create new content of type news for testing, check the "publish to Twitter" checkbox, and save.
The article's link should get Tweeted by your Twitter handle.


Views templates deleted when core updated Yesterday, I posted a proposal for clarifying the procedure for updating core. But now I find that I messed up in doing my update and I'm not sure how to do it right the next time.

I have a set of Views templates under the Bartik theme. They are in the folder:

<Drupal root>\themes\bartik\templates\views

In the update procedure, this folder is deleted along with the rest of the old core.

I was able to easily restore the views folder from the backup, but I'd like to not have to do that in the future.

Generally, it seems like a bad idea to put custom content in a core folder, but it seems that Views needs the template folder to be under the theme it applies to.

Is there a way to put that views folder under the sites folder or somewhere else outside of the core structure so it won't get deleted when I do an update?

Thanks for your help.

Editing files in themes\bartik\templates\views is hacking core. One ought not to. You should create a subtheme of Bartik and make  your changes there. Then an upgrade will not wipe out your changes.

Clear exceptions to the rule for editing core files are robots.txt, .htaccess and web.config.


How can I customize the header and footer from a custom page controller? I have a module named some_module.

This is my some_module.routing.yml:

some_module.index:
 path: '/this/is/the/path'
 defaults:
   _title: 'Some Title'
   _controller: '\Drupal\some_module\Controller\SomeController::index'
 requirements:
   _permission: 'access content'

This is my SomeController.php:

namespace Drupal\some_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class SomeController extends ControllerBase {
    public function index()
    {
        return [
            '#theme' => 'some_template',
          ];
    }

When I go to /this/is/the/path in my browser. It's showing my theme's header and footer. How can I customize header and footer when I access /this/is/the/path?

It depends on how you have built these. Generally you will set any blocks in the header and footer to only show on the paths they are meant to show on, in the block visibility settings. If you need completely different headers and footers altogether, you can build a new theme with those headers and footers, and create a custom theme negotiator (https://www.webomelette.com/choose-your-theme-dynamically-drupal-8-theme-negotiation) to set the theme for those pages.


Global preprocess for all links Is there a some sort of global preprocessing hook for any link on a Drupal site?

Use case:

I've got an enquiry webform embedded on a node that presets some inputs by URL parameters. Editors can set links to that enquiry node on multiple different places on the site (in navigation menus, inside text fields using LinkIt, in URL fields,...).

Whenever the currently active context is a certain node type (e.g. on every full view of a product like "/product/product-id"), I want all links that are rendered on the page (e.g. menu links, blocks, entity reference field on the product pointing to the enquiry node, etc) to have the product_id appended.

I know how to get the current node id in preprocessing and I do know hook_link_alter for menus. But I wonder if there is some sort of global hook that captures all links, saving me from creating 453 different hooks doing all the same thing.

One way to accomplish this would be by using a service tagged with the path_processor_outbound service tag.
Your service should then implement the processOutbound() function in order to modify all links on a page, if the request delivers a node object of the type you want.

This is an example service definition using the described service tag:

services:
  dummy.link_modifier_service:
    class: Drupal\dummy\DefaultService
    tags:
      - { name: path_processor_outbound }
    arguments: ['@request_stack']

This is an example implementation of such a service:

<?php

namespace Drupal\dummy;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Render\BubbleableMetadata;

/**
 * Class DefaultService.
 */
class DefaultService implements DefaultServiceInterface, OutboundPathProcessorInterface {

  /**
   * Symfony\Component\HttpFoundation\RequestStack definition.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;
  /**
   * Constructs a new DefaultService object.
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {

    if (empty($request)) {
      $request = $this->requestStack->getCurrentRequest();
    }
    $node = $request->attributes->get('node');
    if ($node && $node->bundle() === 'product') {
      $options['query'][] = [$node->bundle() . '_id' => $node->id()];
    }
    return $path;
  }

}

This code will now be modifying all Drupal-handled URLs and adding a product_id=XX parameter to them.

Hope this helps, good luck!

@see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21PathProcessor%21OutboundPathProcessorInterface.php/function/OutboundPathProcessorInterface%3A%3AprocessOutbound/


Restrict access to edit page for specific user I have 2 accounts where I need to prohibit them from editing the profile. I managed to hide the edit button but when I type edit into the URL it still allows them to edit the user profile.

if ($user->uid == 267 OR $user->uid == 268){
} // demo profiles, prohibit editing profile
else{
print l(t('Edit My Profile'), "user/{$GLOBALS['user']->uid}/edit");
}

I can't do this based on their role. Thanks

Looks like you're looking for Edit own user account permission.

This module add 'edit own user account' permission.
The goal of this module to prevent changes in user account information in the demo sites.

Or to do it in code:
function mymodule_menu_alter(&$items) {
  if (isset($items['user/%user/edit'])) {
    $items['user/%user/edit']['access callback'] = 'mymodule_user_edit_access';
  }
}

function mymodule_user_edit_access($user) {
  if ($user->uid == 267 || $user->uid == 268) {
    return FALSE;
  }
  else {
     return TRUE;
  }
}


Programmatically update or add a user's avatar I'm trying to update the user avatar in my custom module. Which method shall I use to update the image in db as well as to move the file to public directory?

Thanks.

The file gets stored to file_managed table like this:

// Programmatically create files.
use Drupal\file\Entity\File;
$file = File::create([
  'uid' => 1,
  'filename' => $_FILES['file_id']['name'],
  'uri' => 'public://pictures/' . $_FILES['file_id']['name'],
  'status' => 1,
]);
$file->save();

And I manually updated user__user_picture table which is referring to the fid in the above table.

Finally I ended up with move_uploaded_file to store the image to the filesystem.
I'll proceed with this approach until I find a better way to do the same.

http://www.drupal8.ovh/en/tutoriels/47/create-a-file-drupal-8


is it possible to load data of one block in the tpl of another I'm a novice drupal coder and trying to accomplish the following

My scenario is such that i have the template files
block-mymod-1.tpl and block-mymod-2.tpl
respectively.

What i'm intending to do is get the data of block 2 to be displayed in that of 1.

currently $block->subject and $block->content in block-mymod-1.tpl give the subject and content of block1.

Is there a drupal way of overload the $block so that it could hold the subject and content of second block also?

Apparently my google skills were not good enough or i couldn't find a direct answer.

Any positive response would be greatly appreciated..

Thanks n Cheers!!!

I'm not 100% sure if this will work, but it's worth a try!

You may be able to use module_invoke to place block 2's content into the template of block one using the following code in your block-mymod-1.tpl:

$block = module_invoke('block', 'block', 'view', '2');
print $block['content']

This post might help to explain more, but for your needs you are only interested in the first and last arguments.  The first tells Drupal which module you're invoking, and the last is the block ID of the node you're looking to load the data for.


How to provide free tagging ability when saving nodes using services A content type is going to be saved , this type contains a taxonomy term reference field named field_ucectgry . I'm developing an app so the user can create new node types remotely. Services module is used to provide a REST service for that.

Now for filling field_ucectgry during node creation I must pass the term ID , but the problem is that this field must has free tagging ability which means new tokens for this field is accepted.

So , how can I provide the ability of free tagging for my program?

PS: this is the structure of the field in node :

In D7, a taxonomy term reference field with the autocomplete widget uses JSON like this:
"field_tags":{"und":"Foo,Bar"}"
When it is an autocomplete, the term name needs to be used instead of the term id for free tagging it will simply create the term.


How and where should I override the character length of the description field for an exposed filter I've got an exposed filter with labels and descriptions in my Views. My design requires that the descriptions be displayed as tooltips on hover. In addition, I want this to be the general rule for all my exposed filters in all my views, so the fields that are exposed to visitors is different in each view (probably 10-12 different views with exposed filters). I've got all that working. However, I've run in to a problem with the character limit of the description field for the exposed filter and thus far, I've not been able to find a way around it. So my question is how and where should I override the character length of the description field for an exposed filter in my View?

I've found to possible places where this character limit is set. However, because it's in the core of the Views module I don't want to just change a setting only to have it overwritten the next time Views is updated.

Here are the two places I've found:

/Applications/MAMP/htdocs/d7_chp/sites/all/modules/views/includes/admin.inc:
  313    $form['name'] = array(
  314      '#type' => 'machine_name',
  315:     '#maxlength' => 128,
  316      '#machine_name' => array(
  317        'exists' => 'views_get_view',

and

/Applications/MAMP/htdocs/d7_chp/sites/all/modules/views/plugins/export_ui/views_ui.class.php:
  431      '#type' => 'machine_name',
  432      '#required' => TRUE,
  433:     '#maxlength' => 128,
  434      '#size' => 128,
  435      '#machine_name' => array(

I've looked at a variety of other options as well as adding additional fields to the content type but these are not options. Other than the fact that adding additional fields would be sloppy, the description field in the exposed filter perfectly fits what we need here and we were able to repurpose the tooltip styling and formatting we've created for other content in this piece so we believe that this is the best solution for our scenario and would prefer not to have to rebuild all the tooltip stuff we've already created for this instance.

After discussing it with Kevin in the comments above, I settled on a custom module to solve our problem. It's very simple and small module that includes the following:

function views_description_strlen_form_alter(&$form, &$form_state, $form_id) {

if ($form_id == 'views_ui_config_item_form') {
    $form['options']['expose']['description']['#maxlength'] = 1000;
    }
}


Change arguments in view I have a view with arguments in the page and attachment displays.

When I go to the view page, I see a list of arguments (links) because in "Action to take if argument is not present" I selected  "Summary, sorted ascending."

How do I sort arguments (in this case is term) by weight? I don't see any option to do this. Where can I change the query "ORDER BY term ASC" to "ORDER BY weight ASC" in code?

When I click an argument, I have another page with a list of arguments again, because I have an attachment. How do I only show the argument name I have clicked?

you are using drupal 6, or drupal 7?

If I understand well your questions:

you can change the query used to generate view results (Order BY, Where, etc) using query_alter hook. here one example: Making a field sortable in Views

About weight of arguments, I think that you can control order of precedence in 'rearrange' option:

If your question is related with weight of taxonomy terms, in your View settings > Add sort criteria > Taxonomy: Weight seems will be useful to sort according weight of each term:

regarding shows argument clicked, you can get argument from the current url easily using arg() http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/arg/7:

example URL: http://example.com/node/12345/edit

in this example

arg(0) is node

arg(1) is 12345

arg(2) is edit

here some experiences in Drupal forum to review, with or without using arg():

http://drupal.org/node/180589

http://drupal.org/node/283945

you can add a php code to get respective argument, for example using arg() in a view header or in a drupal php node/page/block:

<?php echo arg(0); ?> or <?php echo arg(1); ?> according your target argument.

I hope information be useful.


How to prevent deleting a term if used? Is there any way to prevent deleting a taxonomy term if it used in any node ?

I have a Taxonomy that is used in Field Collection in my Content Type , I want to warn/prevent deletion of any Term in that Taxonomy if it is used in any node.

I checked taxonomy_term_confirm_delete it is where the confirmation message is formed,
I read from some posts about using

db_query("SELECT COUNT(nid) FROM {taxonomy_index} WHERE tid = :aid", array(':aid' => $tid) )->fetchField()

to get the number of nodes a term is used in but this is not working in my case -maybe because the taxonomy is in field collection ?

I wrote an article tackling this problem.

In short, you have to use hook_form_alter on the form taxonomy_form_term and use the function taxonomy_select_nodes() to check if a node uses the term in question.

You can just copy the code from the article into your custom module (naming the 'mymodule_form_alter' accordingly to your module's name), flush the caches and that should do it.


Empty e-mail body using drupal_mail I'm using drupal_mail for sending eMails from a custom module. This is the code:

function changeme_node_update($node) {
...
$to = "receiver@example.com";
$from = "sender@example.com";
$subject = 'sampletext ' . $nodedate;
$body = "Dear " . $user_name . "! \r\nSome more text\r\n\r\n" . $nodetitle . "\r\nDate:" . $nodedate . "\r\nTime:" . $nodetime . " h";
$body .= "\r\n\r\nSome more text here";

//call mail function
$params = array(
    'subject' => $subject,
    'body' => $body,
);
drupal_mail('changeme', 'information', $to, "de", $params, $from);
...
}

function changeme_mail($key, &$message, $params) {
  switch ($key) {
    case 'information':
      $message['subject'] = $params['subject'];
      $message['body'] = $params['body'];
    break;
    }
}

I'm receiving emails with the subject but the message is missing. Also, where to change the encoding?

Thanks!

Try this :

function changeme_mail($key, &$message, $params) {
  switch ($key) {
    case 'information':
      $message['subject'] = $params['subject'];
      $message['body'][] = $params['body'];
    break;
    }
}

$message['body'] is supposed to be an array as defined here so I changed $message['body'] to $message['body'][]


How do I get the Google Analytics module settings to show up? I am unable to configure I have installed the Google Analytics module and enabled it. But I am unable to configure the settings for it.

More specifically when I click on the configuration gear it just brings me to Home/admin/config/system and lists in this order: Site information - statistics - actions - backup and migrate - special menu items - cron.

In all the videos I have watched on installing this module. This page is where the Google Analytics settings tab should be.

I have also opened up the main configuration page and it brings this error message at the top. "One or more problems were detected with your Drupal installation. Check the status report for more information" It tells me Google analytics isn't configured yet. Then gives me a link to Google analytics settings. But when I click on it, it just brings me back to the page I mentioned above.

What do I do to get the Google Analytics settings tab showing up?

The path is admin/config/system/googleanalytics

There is post about this on https://www.drupal.org/node/1510436

Comment number 17 states a fix

  But after uninstalling--> run cron--> clear caches--> reinstalling-->
  run cron--> clear caches the configuration page appeared, voilà!

Also don't forget to run update.php afte you install a module en clear your caches


Modify the visibility of a form field label with #label_display attribute In D7, I am trying to "hide" a field label through form_alter:

 case 'postal_code_node_form':

   // Set fields as not required
    $form['title']['#required'] = FALSE;
    $form['body']['#required'] =  FALSE;

    // Add css to hide fields.
    $form['body']['#attributes']  = array('style' => 'display:none');
    $form['title']['#attributes'] = array('style' => 'display:none;');

    $form['body']['#label_display']  = 'hidden';
    $form['title']['#label_display'] = 'hidden';

    break;

Unfortunately, the label is still displayed. I could do it through CSS or JavaScript, but I would prefer doing this through hook_form_alter(), so all form modifications are at the same place.

I know this is over a year old, but completely removing the form labels in this way is probably not a good idea in terms of accessibility.

Instead, take a look at #title_display defined by the FormAPI. FieldAPI has something very similar called #label_display.


How to use the managed_file field in a custom form plugin I'm attempting to create a module with a custom form that allows users to upload a file using a managed_file field. The name of my module is foundation_settings and the file structure is:

foundation_settings
  -foundation_settings.info.yml
  -foundation_settings.module
  -src
    -Form
      -FoundationForm.php

Inside FoundationForm.php I'm building the form with the following code:

public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('foundation.settings');
        $form['icons'] = [
            '#type'            => 'details',
            '#title'           => t('Front Page Icons'),
            '#open'            => FALSE,
            'icon1'            => [
                '#type'           => 'fieldset',
                '#title'          => t('First Icon'),
                'icon1_file'        => [
                    '#type'            => 'managed_file',
                    '#name'            => 'icon1',
                    '#title'           => t('First Icon Image'),
                    '#default_value'   => $config->get('icon1_file'),
                    '#upload_location' => 'public://',
                ],
            ],
       ];
}

However I'm not sure how to handle the managed_file when the form is being submitted. In my submitForm function I have

public function submitForm(array&$form, FormStateInterface $form_state) {
    $imageid = $form_state->getValue('icon1_file');
    $file = file_load($imageid[0]);
        if (gettype($file) == 'object') {
            $file->status = FILE_STATUS_PERMANENT;
        }
        $this->config('foundation.settings')
             ->set('icon1_file', $form_state->getValue('icon1_file'))
            ->save();
            $file->save();
}

The upload and saving works okay but I keep receiving this error after submitting

  The file used in the First Icon Image field may not be referenced.

How are you supposed to use managed_file field in custom form plugins?

I think the issue we had was understanding the data that the form was sending back to us when using the 'managed_file' type. This creates an entity of File and stores the image information directly into the table called 'file_managed' in your database, but also saves the file to your directories based upon where you send it. So take this code for example:

$form['mainslider_slide_one']['image_dir'] = [
    '#type'                 => 'managed_file',
    '#upload_location'      => 'public://module-images/home-slider-images/',
    '#multiple'             => FALSE,
    '#description'          => t('Allowed extensions: gif png jpg jpeg'),
    '#upload_validators'    => [
      'file_validate_is_image'      => array(),
      'file_validate_extensions'    => array('gif png jpg jpeg'),
      'file_validate_size'          => array(25600000)
    ],
    '#title'                => t('Upload an image file for this slide')
];

For the '#upload_location' we are telling the file to be stored in our public folder under the specified directory (sites/sitename/files/ directory). So now we have the actual file stored where we want, as well as data stored in the database.

When we receive the information back (under validation for instance) we have the following code:

public function validateForm(array &$form, FormStateInterface $form_state) {
    $managedFileId_imageOne = $form_state->getValue(['mainslider_slide_one' => 'image_dir']);

    if (empty($managedFileId_imageOne)) {
        $form_state->setErrorByName('test', 'No image found for image one');
    }
}

The result of $managedFileId_imageOne will either be an empty array (whereas I am sending an error message back) or an array of fid's.  The fid is the location in the database.  This is the information that we ended up saving into our settings file data. So when we pull the information into our program we are querying for the 'fid' located in the 'file_managed' table using the Entity::load method.

NOTE/UPDATE:

Don't forget that files uploaded in this manner are currently, by default, set to be temporary (status column in the "file_managed" table). You need to set the file to permanent to manually set status to 1 so they are not temporary. I believe this is functionality that is currently a bug and they are looking into possibly updating this in future releases.

Sample from Jasodeep

   $image = $form_state->getValue('image');
   $file = File::load( $image[0] );
   $file->setPermanent();
   $file->save();

Hope this helps at least get you on your way!


private files in drupal 6 I have a sub directory in my files directory which I want to store private images. I display the images with their watermark, via the imagecache modules.

I thought I could make the directory (with the original images) hidden to the public simply by dropping an .htaccess file in the folder, with

deny from all

but the files are still publicly accessible. What am I missing?

If you want to basically prevent hotlinking images, you can try the following in your .htaccess file

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]


How to list all nodes referencing a node in a tree view I have a content type Company with an entity reference field which can be referencing a content of the same type (Company), this field is also set to have multiple values.

What I want to achieve is to list all the companies referencing a company, as a recursive tree (may be only first 2-3 levels).

For Example I have 5 Companies: CompanyA, CompanyB, CompanyC, CompanyD, CompanyE. Each of them referencing one or more companies. Let's say:

CompanyA:

CompanyC
CompanyE

CompanyB:

CompanyA
CompanyD

CompanyC:

CompanyA

CompanyD:

CompanyB
CompanyC
CompanyE

CompanyE:

CompanyB

If am viewing the CompanyA, I would like to have a list like:

Companies Referencing CompanyA:

CompanyB

CompanyD
CompanyE

CompanyC

CompanyA
CompanyD

I hope I was clear enough to explain my goal.

I have achieved this with Views and Views Field View.

I have added a View, showing Content of type Company and created a
Block with display format HTML List of fields.
Added a relationship Entity Reference: Referenced Entity Content entity referenced from field_reference_company
Added a contextual filter Content: Nid with the relationship
I've just added.
Provided a default value Content ID from URL to the contextual
filter.
Added the fields:

Content: Nid, excluded it from display.
Content: Title
Global: View and selected the view itself with Master Display, set as Contextual filters: [!nid]

That's it.


I want to change the order of fields in login/registration form I've user login/registration form in my drupal 7 site. Two links in this form: "Create new account" and "Request new password" are appearing before captcha. And I'm trying to place these links after captcha and before button. How can I achieve this?:

You probably should hide this fields, and show them with javascript before captcha input value is not empty. Check it with "on change" function:

 $('body').on('change', '#CAPTCHA INPUT', function(){}


Authcache: Getting user_link to work in template.php Problem

I'm trying to set-up an Authcache customised menu.

The first way of doing it would be to create 3 menus, one for each of my roles and one for anon then create a custom tpl.php for each using the user_link and user_name variables.

(These variables are provided by the user example module in authcache to all templates.)

Block logic would then give the correct user the correct menu.

It seems a little clumsy.

Is it possible to grab the links inside template.php and use user_link and user_name variables there because I can't find a function which has the links available.

Or how has anyone else solved this problem?

Ok so here is my solution.

Menu's are themed in MYTHEME_preprocess_page, the menu data is also still structured here unlike in MYTHEME_preprocess_menu_tree.

I enabled the memcached example module, this enables the variables user_link and user_name in the preprocess. Then I created a third variable user_account just copying from the other two and altered the cookie so it stores uid not name.

This is because I wanted the "My Account" link to link to "user/x/edit" and I didn't need the name.

I then added the following chunk to my page preprocess.

function MYTHEME_preprocess_page (&$vars) {
  $user_account = $vars['user_account'];
    if (array_key_exists('menu-xxxx', $vars['secondary_menu'])) {
      $vars['secondary_menu']['menu-xxxx']['href'] = $user_account;
    }

The secondary menu in this case is my user menu and My Account is always labelled menu-xxxx in the array. (xxxx will be numbers).


How to redirect the user to a specific page after node is added/edited by user I'm trying to create a drupal 7 website where users can upload pictures with a title.

When the user uploads an image with title, it has to be approved by the admin who then publishes it. My question is after the user uploads the image, how can I redirect the user to a different page which tells the user that the uploaded image has gone for approval by the admin.

You can use the Rules module to do that. If you haven't used it before you can take a look at this video tutorial.


embedding a font in the code I know nothing but the admin functions of Drupal.  The developer of my site used Roboto and other fonts when I asked for Arial.  Now my website design gets completely screwed up in Chrome and Firefox browsers.  The developer has since gone out of business.  I was told that something could be added to the code to "embed' this roboto font so that when someone accesses my site that does not have roboto installed - which is just about everybody apparently - that  roboto will automatically be installed in their computer?  Someone at Go Daddy told me that the problem is that HTTPS should be inserted in the code instead of HTTP.  That the developer does have the roboto code inserted but it should be HTTPS.  I know I probably sound completely stupid but I cannot even find the code to even look at it or CSS style sheets.  I have no idea where the code actually is for my site.  If anyone can assist - I would greatly appreciate it.  My site is nightvisionnv.com.

As for fixing this - see Shawn Conn's answer.

Some more background:

The "Roboto" font is already embedded in your site.  If you look at he markup in your header, it has the following line:

<link href='http://fonts.googleapis.com/css?family=Roboto+Condensed:700italic,400|Roboto:400,400italic,700,700italic' rel='stylesheet' type='text/css'>

This should be:

<link href='//fonts.googleapis.com/css?family=Roboto+Condensed:700italic,400|Roboto:400,400italic,700,700italic' rel='stylesheet' type='text/css'>

to make it work with both HTTP and HTTPS (as already pointed out by Shawn Conn).

Provided this is made to work, it means that if a user don't have Roboto installed, it will be downloaded from the googleapis CDN and cached upon first visit.

The line that inserts that link to the googleapis is probably in html.tpl.php in your site's theme (but I can't be sure - Drupal allows a site developer to insert such links in the header by other means).

Also, your style sheets uses the following every time a font is mentioned:

font-family: "Roboto",sans-serif;

This means: Use "Roboto" when available, otherwise fall back on the browser's default for "sans-serif".  This should work OK in all browsers, including Firefox and Chrome - even if the HTTPS/HTTP mixup mentioned by Shawn Conn stops Roboto from being downloaded.

  Now my website design gets completely screwed up in Chrome and Firefox
  browsers.

I looked at your website in MSIE, Firefox, and Chrome.  I don't see any obvious problems with it.


Directly changing a theme causes a "Functional environment bootstrapping" error I bought a premium theme, installed it, and the site crashed with a WSOD, so I figured changing the theme back to Bartik would probably solve it. Thus, after reading the very fresh Drush 8 documentation I ran the command (also tried other variations that didn't work):

drush config-set system.theme default bartik

Yet, when I did that I got the same error I had before I moved the Dev environment from Windows10 to Ubuntu, that very same error "the demon who haunted me" that says (paraphrase): "Please use a more functional environment for bootstrapping Drush"... I mean, even Ubuntu isn't? Come on...

System details: Ubuntu desktop 15.10, apache 2.4.12, php 5.6.11, mysql 5.6.27... full session:

I wasn't inside the sites' folder! I didn't notice that for some reason - Here is a possible explanation why, that might be nice for you to read:

In the similar time period, I also ran a few general Drush commands inside the root folder just to check if Drush itself is working because of Environment Variable (Path) value setting mistakes I made earlier and tried to fix; I could run drush in each session only after manual var export, but I than went to home/.profile, and added export PATH="~/.composer/vendor/bin:$PATH" in the end of file and it fixed it.


How do I implement a VIDEO gallery like gallery formatter but with videos? I need to implement a gallery of videos in DRUPAL 7 like gallery formatter in Drupal 7 but with videos.

The videos are from YOUTUBE.  I created a content type named "video" and I have used the module:  http://drupal.org/project/video_embed_field for upload the code of video.  Have you any idea for create the video galleries?

Thanks for your help.

If you're able to switch to a module other than video_embed_field I'd highly recommend the Media module along with the Media Gallery module.

You'll also want Media Youtube, I've used those three together quite a bit and they're very good.

I'd also recommend installing Colorbox to take advantage of the built-in lightbox features.


How to copy select list value from a webform submisison into select list field new node? This is the scenario:

A webform with the following fields

Question -> Textfield
Category -> Select options (Listbox) Listing vocabulary HETCAT

A content type Question with these fields

Title
Category -> Term reference listing vocabulary HETCAT

Once the webform is submitted i create a new question node.
Everything works fine, the Question field of the webform is the new Question node title, but i can not see the way to copy the category selected on the webform to the new node

Thanks in advance

This is the export rule code

{ "rules_submissions_to_node" : {
"LABEL" : "Submissions to node",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "webform_rules", "rules" ],
"ON" : { "webform_rules_submit" : [] },
"IF" : [
  { "webform_has_id" : {
      "form_id" : [ "form_id" ],
      "selected_webform" : { "value" : { "webform-client-form-140" : "webform-client-form-140" } }
    }
  }
],
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "het_question",
        "param_title" : [ "node:title" ],
        "param_author" : [ "user" ]
      },
      "PROVIDE" : { "entity_created" : { "new_question" : "New question" } }
    }
  },
  { "data_set" : { "data" : [ "new-question:title" ], "value" : "[data:question-value]" } },
  { "data_set" : {
      "data" : [ "new-question:field-month" ],
      "value" : [ "site:current-date" ]
    }
  },
  { "entity_save" : { "data" : [ "new-question" ], "immediate" : 1 } },
  { "mail_to_users_of_role" : {
      "roles" : { "value" : { "4" : "4" } },
      "subject" : "New question to approve",
      "message" : "[new-question:title]\r\n\r\n\u003Ca href=\u0022[new-question:edit-url]\u0022\u003EEdit to publish it\u003C\/a\u003E\r\n",
      "from" : "[site:name]"
    }
  },
  { "node_unpublish" : { "node" : [ "new-question" ] } }
]}}

Well, finally i figure it out how to solve it.

I'm using Webform Rules module

Just need to add an Execute custom PHP code action and set the value like this

// $new_question is my new node.
// $data['components']['category'] is my webform listbox component.
// $new_question->field_category is my taxonomy reference field select list.

$tid = substr($data['components']['category']['value'][0],4,2);
$new_question->field_category['und'][0]['tid'] = $tid;


HTTP request status error This is the error shown in reports/status.

  Your system or network configuration does not allow Drupal to access web pages, resulting in reduced functionality. This could be due to your webserver configuration or PHP settings, and should be resolved in order to download information about available updates, fetch aggregator feeds, sign in via OpenID, or use other network-dependent services. If you are certain that Drupal can access web pages but you are still seeing this message, you may add $conf['drupal_http_request_fails'] = FALSE; to the bottom of your settings.php file.

What do I need to configure to prevent this error?

My website works well, but this error causes some problems, for example with the Quicktab module.

As you can see Tab Content disappeared and Tab Weight is changed to the select list. What do I need to do to fix this?

Besides that, I have other sites on this server; none of them has reported this error.

Drupal cannot contact itself. The system module reports this error when a system_check_http_request(). Assuming this is the cause of the AJAX errors, you could try, as the error message suggests, to set $conf['drupal_http_request_fails'] = FALSE; in your settings.php file. This might fix the symptoms, but not the cause however.

The fix lies in figuring out why this check fails:

drupal_http_request(url('', array('absolute' => TRUE)), array('max_redirects' => 0));

It could be that url() is not returning your front page URL. If you have drush on your server, you can run the command drush php-script my_test_script.php. With my_test_script.php containing a simple test script:

<?php echo url('', array('absolute' => TRUE)), array('max_redirects' => 0); ?>

If it is returning the correct home page URL, another likely problem, since you're hosting multiple sites, is that your domain is not resolving the correct virtual host. You can test this with the server command:

wget -O- http://www.example.com/

If your site's home page HTML is output to the console that should tell you that the server can contact the resolve & connect to itself. If this is the case it might be something like a PHP config preventing retrieval of HTTP URL's.


Google Analytics Reports with Background Process module (non-blocking http request) Using Google Analytics Reports module latest version 7.x-3.0-beta2. I wanted to make this module to make requests in non-blocking fashion. Standard drupal makes it blocking fashion, which slows things down.

I started looking into Background Process module, which looks promising. Other option is HTTPRL module, which is similar to Background Process.

Right now I am using AJAX for fetching GA API reporting data, but I feel it's slow, because of how drupal_http_request works (synchronous, blocking way).

Is it possible to integrate non-blocking requests to fetch data from GA API without rewriting excellent Google Analytics Reports module?

This is not possible in the manner that you described. Sure you can make a chain of asynchronous calls, the browser AJAX request to Drupal then Drupal making a non-blocking HTTP request to the GA API. However, your AJAX call won't have data to use.

The Background Process & HTTPRL (check out the project page image) work by the request being one way; they are calling out to a URL that will trigger some background action that doesn't need to communicate back (e.g. some batch job or page crawler cron task). In your case, you need the GA API to communicate back with Drupal then Drupal to communicate back with the browser. There's no getting around that.


Custom User Login validation I am developing a Mobile App for my drupal website, where user need to login with existing user account in drupal. How to validate password? I have tried MD5, and also concatinated it with $S$. Any suggestions..

use user_hash_password() to validate the password for existing users.


How to add the input text field in node view page How can i add the field(input filed) for particular content type in submitted node view page.Using this field i can add some text to the particular node. Please suggest me is there any module for this or custom code.....

I think I've made it clear, please answer

You can use editablefields module.

  This module allows CCK fields to be edited on a node's display (e.g.
  at node/123), not just on the node edit pages (e.g. node/123/edit). It
  also works within views etc. Anywhere a 'formatter' can be selected,
  you can select editable (or click to edit).

You can  follow the below step for setting up editablefields for your content type.

Go to  Administration -> Structure -> Content type
Edit your content type and then click on "Manage Display"
Change the Format to editablefields for your field.
Once you set the formatter, you can click on the gear icon to further
change the settings - the settings vary per field type


401 Unauthorized : Missing required argument node I am trying to Create Services to Create Node Type Discussion in a Group using Services Module, but getting the error : 401 Unauthorized : Missing required argument node
In the Header I have given:

Content-type:application/json
x-csrf-token:token value
session-name:session name value

In the Body I have given :
{
"og_group_ref": {"und": [{"target_id": "3897"}]},

"title": "Title of discussion",

"field_description": {"und": [{"value": "test description"}]},

"type": "discussion",

}

Can anyone please tell me why I am getting this error ?

You put comma on last parameter "type": "discussion", that doesn't required at the end. javascript, jquery, json doesn't allow comma at end of array. It returns invalid argument.


$form_state['node'] Values Being Lost in Multistep Node Form After Ajax Click I am really hoping someone might have an insight into this really troubling issue. I have got a custom node form which is presented as 4 multistep pages. In my third step, I have a bunch of ajax buttons which allow the user to save information. The problem is, after the ajax button has been clicked and we click the next 'page' button, all the $form_state['node'] values from the previous pages are being lost. So, consequently, when I get to hook_node_insert, I have empty values from the first 3 pages.

However, the weird thing is, this only happens in a couple of my ajax buttons in that page. I have a few other ajax buttons, which, don't cause any such problem. This is the definition for one of the problematic buttons:

<?php
    //Add the cancel button to cancel the "Add New Product" form
    $form['newproduct']['fieldset']['cancel'] = array(
      '#type' => 'button',
      '#name' => 'Add New Product Cancel',
      '#value' => 'Cancel',
      '#ajax' => array(
        'callback' => 'MyModule_NewProduct_Cancel_ajax_callback',
        'wrapper' => 'MyModule_NewProduct_wrapper',
        'method' => 'replace',
      ),
      '#limit_validation_errors' => array(),
      '#submit' => array(),
    );
?>

This is the callback for that button:

<?php
function MyModule_NewProduct_Cancel_ajax_callback($form, &$form_state) {
  //Return the add new product button
  return $form['newproduct']['addnewproduct'];
}
?>

I know that I might not have included enough code to see the full problem, but was wondering if there was any problem with the my ajax button element definition. Would appreciate any help on this. Thank you.

Update!!  - SOLVED - It was a limit_validation_errors problem.  I didn't have that set for my 'next' buttons in hook_form_formid_alter().

You need to add a submit handler that has

$form_state['rebuild'] = TRUE;

Otherwise the form will actually submit, and the form_state values will be purged.


View doesnt work properly when logged out I have a question about a problem I met. I'm working on Drupal 7 site that has a menu made with a view but for some reason the structure of menu is totaly different when user is logged in than when the user is logged out.
Everything works fine when I'm logged as admin but when I logged out it seems like some of configurations doesnt load. I don't have any errors in console.

I`m not sure what kind of informations from view I can share or will be usefull so I will add every need informations which you asked for.

Adding a code from inspect:
Image with both inspects

A possible cause is that anonymous users don't have access to the content or fields. The inspect images aren't helpful to determine what permissions could be missing. In the UI, go to People > permissions and check that:

Anonymous users can see published content
If there are field-level permissions, anonymous can see all the fields involved in the view
There aren't restrictions to access the view (this is unlikely, the view wouldn't render at all)


drush cannot update commerce kickstart I just installed Commerce Kickstart and got a prompt to upgrade from 7.x-2.20 to 7.x-2.21.
drush cannot update throws error:
The commerce_kickstart directory could not be found within the modules directory at                          [error]
/var/www/planetwigs.com/profiles/commerce_kickstart, perhaps the project is enabled but has been deleted from
disk.
Now, the directory exists and the modules are there.
In the GUI I am offered the option to download module, which I did and replaced all modules with new version, just overwrote since I did not modify anything yet and the old sftp method worked, but drush did not.
BTW it is impossible to use the dropdown to selected version 2.20

Drush update for commerce kickstart is not just update drush pm-update, but rather:

drush dl commerce_kickstart
drush updatedb

Check here


Custom validation for paragraph field I have a content type with one paragraph field which has a checkbox and a text field.

By default, the text field is optional. I want to make it required when the checkbox is checked. Conditional fields module does not work with paragraphs properly. I tried with #states, but this just adds a class. It doesn't make the field required in the back-end.

Maybe I should write a custom validation. How can add it for paragraph field with two fields inside?

As you mentioned, you'll need to add a custom validate function. Since this checkbox can be checked or unchecked on the fly, you will also need to use some javascript to toggle the "required" class on and off the textbox. This will make sure it looks right to the user. Of course you'll need to make sure you have a required class style in css.

This is just freehand, and just one way it could be done. You would need to adapt this to your fields.

create a custom module. In your .module file

<?php
use Drupal\Core\Form\FormStateInterface;

function MYMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  //where CONTENTTYPE is the machine name of your content type
  if ($form_id == 'node_CONTENTTYPE_edit_form') {
    $form['#validate'][] = 'my_test_validate';
  }
}

function my_test_validate($form, FormStateInterface &$form_state) {
  $checkbox = $form_state->getValue('field_my_checkbox');
  $textfield = $form_state->getValue('field_my_textbox');

  //if the checkbox is checked
  if ($checkbox['value'] == 1) {
    if (trim($textfield[0]['value']) == "" || empty($textfield)) {
      $form_state->setErrorByName('mytextfield', t('Text field blah blah is required'));
    }
  }
}

In a js file somewhere in your module or theme you could have something like:

(function ($, Drupal) {

  Drupal.behaviors.myForms = {
    attach: function (context, settings) {
      //add a click listener to toggle whatever styles you want
      $('#edit-field-mycheckbox-value').click(function(){
        $('#edit-my-textfield-0-value').toggleClass('required');
        $("label[for='edit-my-textfield-0-value']").toggleClass('form-required');
      //etc
      });

    }
  };

})(jQuery, Drupal);


hook_menu alternative for custom themes I can understand that hook_menu is for modules only, not custom themes.
But if I want to add custom paths/urls to my theme what should I do?

For example if I want some of the content to load by ajax, and I want to use custom urls, then a "hook_menu" would be great for custom themes.

Surely there must be another solution than to write a small custom module?

Any suggestions and help is appreciated.

Raf

As of Drupal 7, themes can implement alter hooks, so you can use hook_menu_alter() in template.php.


How to hide drupal error message - one or more problems were detected with your drupal installation On logging on to Drupal administration page, I get an error message:

  One or more problems were detected with your drupal installation.

I've tried disabling modules.

Is there a way to hide this message?

You could check the status report and try to resolve the error but I guess you are happy to leave it that way.

Or you could hide the message by selecting the class and choosing not to display it using CSS.
Create a file called style.css in your "Theme" folder (alongside the location of page.tpl.php) and place the class within it (you can check the class by using Firebug/Inspector "right click on it, then inspect element").

I think the class will be .warning or .alert, and an example CSS code would be:

div.warning, .alert, div.error, tr.error
{
display:none;
}

This would however hide all alerts and warnings for elements with the same class.  So be careful because you could miss other critical notifications.  You could have a style sheet for non-admin users that would turn this off and another for admin areas that would display these messages.  Its your choice.


Problem with table schema I'm working on an API that pulls data from a Drupal site. Everything has gone pretty well I normally use Drupal Bootstrap to load Drupal use the functions I need then spit out a JSON array. I am having one issue though with a module, for some reason Drupal's schema doesn't seem to think the table exists. The module I am working with is VotingApi.

So in my API call I connect to the drupal db. Then if I run:

print_r(module_list());

I get a big list of modules installed and votingapi is included. If I run:

var_dump(module_exists('voting_api'));

I get a true response. I can also run:

var_dump(db_table_exists('votingapi_vote'));

And get a true response. However if I run:

print_r(drupal_get_complete_schema(true));

The votingapi_vote and votingapi_cache tables don't show up in the list. So then when I try to write a record to those tables with drupal_write_record() it doesn't work because that function checks the schema to see if the table exists. I have tried clearing the schema cache like this before I call drupal_get_complete_schema():

cache_clear_all('schema', 'cache');

It doesn't help, when it is rebuilt from the API the voting tables never show up. If I go into Drupal's admin and Clear All Cache then the table schema is rebuilt correctly and includes the voting tables. Any ideas on how I can get the schema to rebuild correct for the API?

Figured it out. It had to do with using MultiSite apparently when you use multisite and bootstrap it will only bootstrap to the main site. I found an article talking about it here https://drupal.org/node/2080819

Basically you need to override what the system variable is for the url so that it will bootstrap to the correct site.

define('DRUPAL_ROOT', '/path/to/drupal');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
$variables['url'] = 'http://subsite1.example.com/';
drupal_override_server_variables($variables);
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);