Problem adding a tab to the user menu I created a panel page using the Panels module, Contact list at the path messages/contact-list.

The Privatemsg module causes several tabs (Inbox, Sent messages, All messages) to be displayed across the top of pages with path messages.  I am attempting to add an additional tab that links to my Panels page, Contact list.

Based on the code in privatemsg.module for the "Sent messages" tab:

  $items['messages/sent'] = array(
    'title'            => 'Sent messages',
    'page callback'    => 'privatemsg_list_page',
    'page arguments'   => array('sent'),
    'file'             => 'privatemsg.pages.inc',
    'file path'        => drupal_get_path('module', 'privatemsg'),
    'access callback'  => 'privatemsg_user_access',
    'type'             => MENU_LOCAL_TASK,
    'weight'           => -12,
    'menu_name'        => 'user-menu',
  );

I added this code to hook_menu() in a custom module:

  $items['messages/contact-list'] = array(
    'title'            => 'Contact List',
    'page callback'    => 'drupal_goto',
    'page arguments'    => array('messages/contact-list'),
    'access callback'  => 'privatemsg_user_access',
    'access arguments' => array('read privatemsg'),
    'type'             => MENU_LOCAL_TASK,
    'weight'           => 10,
    'menu_name'        => 'user-menu',
  );

However, although this produces no errors, even after clearing the cache multiple times no tab appears anywhere.  I tried moving the code from my custom module into the privatemsg module to no effect.  I've looked at the documentation for hook_menu() but it still isn't clear to me what I'm doing wrong.

The reason for your problem is that page manager has already defined a menu entry for that path. Just as well, because the menu item you have created would cause an infinite chain of redirection. You would need to change the path for your panels page to be something different in order for the redirection to work.

But you can simply remove your menu entry altogether and use page manager to define the menu item for the page as a tab under Settings -> Menu. You shouldn't need any extra code to do that.


How to use union with a query of view itself? I have a table that have 2 types of data:

first type is '1'
second type is '2'

And I want to get 3 records of both by union so,
I want to know that how to get 3 records of both types from one table at a time
so it is possible by union with itself so i want to add union with my views content.

How to get query of view and alter it and where I put this query in Drupal 7 but I have no one module for this data.

You can look here (https://drupal.org/node/409808) for information on creating custom sql statements in a View.


form_set_error() redirects to raw ajax response page I have a page with a simple view.  Above the view there is a menu link that when clicked loads a node form with a required file field.  The form is fetched and loaded using ajax_commands into a div on the current page.

The problem is when I submit the form without providing a file for the required file field (intentionally triggering error), form_set_error redirects the user to the menu path originally called to produce the form (sitename-ajax/new-profile), which displays an unrendered ajax response.  How do I get the validation response and return it to the target div on the same page - preventing a page redirect?  Code pasted below is simplified for reference.  Thanks!

In my hook_menu():

$items['sitename-ajax/new-profile'] = array(
  'title' => t('New Profile'),
  'type' => MENU_CALLBACK,
  'page callback' => 'sitename_ajax_new_profile',
  'access arguments' => array('access content'),
);

Page callback:

function sitename_ajax_new_profile() {
  $form = sitename_forms_prepare_form('ps_profile');

  $output = drupal_render($form);

  $commands = array();
  $commands[] = ajax_command_html('#new-form-target', $output);

  $page = array('#type' => 'ajax', '#commands' => $commands);

  ajax_deliver($page);
}

Form helper function:

function sitename_forms_prepare_form($type) {
  global $user;
  module_load_include('inc', 'node', 'node.pages');

  $node = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $type,
    'language' => LANGUAGE_NONE
  );

  $output = drupal_get_form($type . '_node_form', $node);
  return $output;
}

The API page for form_set_error() says (emphasis added):

  When a validation error is detected, the validator calls form_set_error() to indicate which element needs to be changed and provide an error message. This causes the Form API to not execute the form submit handlers, and instead to re-display the form to the user with the corresponding elements rendered with an 'error' CSS class (shown as red by default).

I reckon that's probably where your problem lies.  Further down the same page is this:

  Multistep forms not wanting to validate the whole form can set #limit_validation_errors on buttons to limit validation errors to only certain elements.

This looks like it might help.


Views date filter yesterday I want to show yesterday's posts on a block with views. So I added two date filters. They should be:

<today midnight

>yesterday midnight

(-1 day is not ok for me because it spans exactly 24 hours back)

According to the manual: http://php.net/manual/en/datetime.formats.relative.php
I added the two filters as:
Less than "today" (I also tried less than "midnight" or "today 00:00")
Greater than "yesterday" (I also tried greater than "yesterday 00:00")

But they are all showing the items from yesterday and today together.

Is there a way to show items from yesterday 00:00 to yesterday 23:59 ?

I ended up using contextual filter instead of filters. I added:

Content: Created date

Provide default value - php code

return date("d", strtotime("-1 day"));


Does #AJAX work on the body field? Does the #AJAX FAPI property work on the body field? I've got it to work with things like submit buttons and textfields such as the title. When I alter the node edit form, and attach an #ajax array to the body field though, nothing happens. I've tried multiple event types (keyup, keypress, focus). Is there anything special that needs to be done to get #ajax to work on the body field?

  // This works (creates backend xhr call).
  $form['title']['#ajax'] = array(
    'wrapper' => 'autopreview',
    'callback' => 'autopreview_ajax_callback',
    'method' => 'replace',
    'event' => 'focus',
  );

  // Doesn't work.
  $form['body']['#ajax'] = array(
    'wrapper' => 'autopreview',
    'callback' => 'autopreview_ajax_callback',
    // 'method' => 'replace',
    'event' => 'focus',
  );

  // Doesn't work.
  $form['body']['und'][0]['#ajax'] = array(
    'wrapper' => 'autopreview',
    'callback' => 'autopreview_ajax_callback',
    'method' => 'replace',
    'event' => 'focus',
  );

According to the FAPI docs textareas do support #ajax, yes.

I'd imagine the problem is because you'll be using a WYSIWYG editor on that field. Such an editor will replace the textarea with an iFrame, and the AJAX events aren't bound to that iFrame (or its inner textarea), so won't get fired when you change the text.

If that is the case, I don't think there's any easy way to overcome the problem except to turn of the WYSIWYG editor for that field.


Display referenced node field in view I have a view made up of nodes that include node reference fields. I would like to pull in a field from each of the nodes being referenced for display in my view.

I know that is a little confusing so let me give you an example.

My food content type contains the name of a food and the number of calories it has.
My diary content type contains a date and a node reference that accepts food nodes.
My view displays your diary nodes.
I would like to display the calories for each food item that is being referenced by diary
I would like to add the calories using views_calc (or something else).

The way I see it there are two ways to do this - either add a calories field to my diary content type that automatically pulls from the node that is being referenced, thus making it available to my view. The other option is for views to be able to pull in fields (sub-fields?) from a node reference field.

I don't know if either option is possible or, if it is, how I would go about doing it. Any help would be greatly appreciated.

Edit: Relationships will allow me to pull in the fields I need, so now I just need a way to add them. Views_calc does not support calculations on relationship fields.

Shouldn't be too hard with a Views Relationship.

As you've mentioned, your View should show content (nodes). Here are the rough settings, as I see it:

Filters: Published or Admin; Content Type: Diary
Display: Fields
Relationships: Content-food nodereference field
Fields: Food (no reference...from the diary content type); calories (from the referenced food field)

That should about do it. I usually have to tweak Views relationships a bit to get them to work perfectly, so it's a bit tough for me to get it exactly right without seeing your content.

Best,
Scott


Limit the search to only one content type I'm trying to setup a search for only one content type; I've tried to google it and I saw so many stuff that I don't know which one to test and as I don't want to install too many modules just to test things. I'm not actually even sure that I have to install something else to achieve that.

Do you have any hint or best implementation example please?

These instructions by selvam on KnackForge worked for me. Basically, you can use the MODULE_search_apachesolr_query_prepare hook to add a filter to the query before it's run.

<?php
function MODULE_search_apachesolr_query_prepare($query) {
  if (/* not correct page */)
    return;
  $compiled_filter = new SolrFilterSubQuery('AND');
  $compiled_filter->addFilter('bundle', 'TARGET_CONTENT_TYPE');
  $query->addFilterSubQuery($compiled_filter);
}

I haven't actually tried the hook, but I did use the filter and apply it to a query in a different context (API) and it worked as expected.


hook_menu_get_item_alter() needs to give a 404 How can I throw a 404 error from within hook_menu_get_item_alter()?

If I call drupal_not_found() then it keeps calling itself, and I don't know an other way to do this.

I was able to do this in hook_menu_get_item() by getting the status of the node from a simple query, and, when status isn't NODE_PUBLISHED, I change the router item's load function from node_load() to is_null(), which will always return FALSE when a node ID is passed to it. A FALSE from a load function will result in a 404 response from Drupal. This is a bit dirty, but it uses the Drupal API properly, and it seems to work!

/**
 * Implements hook_menu_get_item_alter().
 */
function mymodule_menu_get_item_alter(&$router_item, $path, $map) {
  if ($path == $_GET['q']) {
    if (isset($map[0]) && $map[0] == 'node' && isset($map[1]) && is_numeric($map[1])) {
      $status = db_query('SELECT n.status FROM {node} n WHERE n.nid = :nid', array(':nid' => $map[1]))->fetchField();
      if ($status != NODE_PUBLISHED) {
        // Replace node_load() with is_null() as load function, to ensure the
        // output of the load function is FALSE, so we get a 404 response.
        $router_item['load_functions'] = array('is_null');
      }
    }
  }
}


Parent term suggestion on entering the child term in term reference field? I have a term reference field which has the widget Autocomplete term widget (tagging).
I want the functionality like, when a user type a child term in that autocomplete field, the system should return a suggestion of the parent term that did you mean [parent term].

Suppose A is a parent term and its child term is B. So when a user type B in the field, it should show a suggestion of did you mean A?

I think you'll need to override the taxonomy autocomplete path. Here's what you will need:

hook_menu_alter() implementation, so your custom module takes over the taxonomy autocomplete suggestions. See hook_menu() implementation, specifically $item['taxonomy/autocomplete'] item in /modules/taxonomy/taxonomy.module for more information.
You'll need to re-create the core taxonomy_autocomplete() function, which is in /modules/taxonomy/taxonomy.pages.inc.
You'll have to perform a check and see for which vocabulary you need to show suggestions:

If it's the vocabulary where you want to have child -> parent functionality, add the code for fetching the parent term and provide additional suggestions.
If it's some other vocabulary, make sure you return the same output as the core function would.

You'll need to add this in a custom module.

function YOUR_MODULE_menu_alter(&$items) {
  // This will re-route this path to your custom module, so you can have any
  // additional logic.
  $items['taxonomy/autocomplete']['page callback'] = 'YOUR_MODULE_taxonomy_autocomplete';
}

function YOUR_MODULE_taxonomy_autocomplete($field_name = '', $tags_typed = '') {
  // Copy the content of taxonomy_autocomplete() function here, and add necessary
  // modifications at the end of it.
}

Hope this helps.


Commerce Kickstart Review Overrides Error I want to upgrade Commerce Kickstart (commerce_kickstart-7.x-2.53) to the latest 2.54. Following the upgrade instructions I went to the Structure Features menu to check for overrides and found these are overriden.

Commerce Kickstart Blog
Commerce Kickstart Lite Product
Commerce Kickstart Merchandising
Commerce Kickstart Slideshow
Commerce Kickstart User

But when I go to Review Overrides, I get these errors.

Notice: Array to string conversion in features_override_features_export_render_addition() (line 428 of /home/-----/public_html/sw/profiles/commerce_kickstart/modules/contrib/features_override/features_override.export.inc).
Notice: Array to string conversion in features_override_features_export_render_addition() (line 428 of /home/-----/public_html/sw/profiles/commerce_kickstart/modules/contrib/features_override/features_override.export.inc).
Error: Call to a member function stateVariables() on string in RulesPlugin->availableVariables() (line 740 of /home/-----/public_html/sw/profiles/commerce_kickstart/modules/contrib/rules/includes/rules.core.inc).

First, is there a fix for these errors?
If not, is there any way to know what overrides are actually in place?
In any case, can I proceed with the Commerce Kickstart (commerce_kickstart-7.x-2.54) upgrade?

FYI: Running Drupal 7.58 and PHP Version 7.1.16

Thanks

Are you sure those modules are compatible with PHP 7? We haven't tested nor do we recommend running Commerce Kickstart 2.x in PHP 7 as far as I know.


Uploading images to CKeditor in a file field way? Background

I'm looking for one of the two possible solutions concerning image-uploading to Drupal, and especially to CKeditor image uploading and handling:

Possible solution 1

A module that creates an independent image-folder to every node, uploads images to this specific directory, and then let me choose only between these images directly from CKeditor. If the node is deleted, than this folder is deleted along with it.

Possible solution 2:

a module that uploads images into CKeditor text areas in an efficient, fast, Drupal-file-field-like way; It is important for me that this uploader will use the same rules like the Drupal file-field, the same mechanisms and SQL tables, so that when I delete the image I uploaded - it will be totally deleted from the site's home-folder.

So basically the uploader I'm looking for should do 2 things:

Upload files easy and fast, just like the Drupal file-field does.
Send some kind of signal when a file is deleted from that very CKeditor text area.

Please help me to find of these two possible solutions:

I'm not 100% sure but maybe insert module is a suitable solution for you.
INSERT:

Insert is a utility that makes inserting images and links to files into text areas or WYSIWYGs much easier. It adds a simple JavaScript-based button to FileField and ImageField widgets. When used with ImageField and ImageCache, images may be inserted into text areas with a specific ImageCache preset.
This module was previously known as FileField Insert.


Only allow certain roles to publish content, other roles can save as unpublished? I have a Content Admin and a Translator Roles.

Content Admin's can create, edit, delete, and publish content (this is working fine)

Translator's shouldn't be allowed to publish content, they should only be able to create and edit translations. (it should save as unpublished).

Anyone know how to achieve what I'm trying to do in Drupal 8? Or know if a module that does this has been ported to Drupal 8?

You will need to alter insert / update node entity form:

Define a permission "Save unpublished content"
Make a hook_form_alter or hook_form_ENTITY_TYPE_form_alter
Check if you are alter the exact entity types you need.
Hide all buttons you don't need (based on permission)
Add button ('save unpublished content') (based on persmission)
When submitting: call the default submission and add yours to set the status 0.

Save button is an UL with two LI elements: save published, save unpublished:


Calendar - current week I am looking for a way to add a class to the  week row indicating whether the week is the current week.

The week is rendered by calendar-month-row.tpl.php and the arguments are passed within calendar_build_month().

What is the "Drupal way" of intercepting this procedure?

I of course do not want to hack the module to generate the desired output.

Copy template file
sites/all/modules/calendar/theme/calendar-month-row.tpl.php
to
sites/all/themes/YOUR_THEME_NAME/templates directory and edit it in this manner:

<?php
/**
 * @file
 * Template to display a row
 *
 * - $inner: The rendered string of the row's contents.
 */
$attrs = ($week > 0) ? 'week="' . $week . '"' : '';
$attrs .= ($iehint > 0) ? ' iehint="' . $iehint . '"' : '';
if ($week == date('W')) $class .= ' calendar-current-week';
$attrs .= ($class) ? ' class="' . $class . '"': '';
?>
<?php if ($attrs != ''):?>
<tr <?php print $attrs?>>
<?php else:?>
<tr>
<?php endif;?>
  <?php print $inner ?>
</tr>

Don't forget to clear page cache after this.


How to see an overview of the download statistics of all modules on drupal.org? At the moment the usage overview page on drupal.org gives an idea of the number of sites using a certain module. However as noted this includes information from only sites that include the update status module which means it is biased toward newer sites, is there a way to see an overview of the download statistics of a module as well in a similar view?

You can get information about a particular module in both XML and JSON format by accessing URL:

Eg: (For Views Module) :

XML format:

https://www.drupal.org/api-d7/node.xml?field_project_machine_name=views

JSON format:

https://www.drupal.org/api-d7/node.json?field_project_machine_name=views

Reference: https://www.drupal.org/api


How to detect the current URL? I would like to add a body class in D6 if you are on a specific page(s) currently in my template.php I have:

if url('the/path') {
 add the body class...
}

but that function doesn't seem to be working for me.

Drupal's Alias is what your looking for

<?php
$path = drupal_get_path_alias($_GET['q']);
if ($path == 'the/path') {
  // do stuff
}
?>

Others Below:

Full URL

<?php
global $base_root;
$base_root . request_uri()
?>

Drupal's "Internal" URL

<?php
$arg = arg();
// Path of 'node/234' -> $arg[0] == 'node' && $arg[1] == 234
?>


How to delete paragraph when uninstalling the module? I have been creating the custom module which have the paragraph configuration, when installing the custom module, the paragraph config will be stored in the database and then It will be available in the paragraph types.(/custom_module/config/install)

When uninstalling the custom module, the paragraph types are not getting uninstalled. By Manually, I am deleting it after the uninstalled.

Is there any possible way to delete the paragraph types when uninstalling the custom module?

Because of this, we are unable to fix some issues

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_example_ch_hero_video_target_id' in 'where clause': SELECT 1 AS expression FROM {paragraph_revision__field_example_ch_hero_video} t WHERE field_example_ch_hero_video_target_id IS NOT NULL

I have replaced the hero video field with some other machine name. then I could not delete the paragraph or install the module.

Can anyone give some valuable advice?

Add this to the relevant config file(s) in config/install:

dependencies:
  enforced:
    module:
      - custom_module

That will force the config item(s) to be removed when the module is uninstalled.


Need to add custom element in sitemap.xml file I have installed sitmap module to create sitemap.xml file.
Now I want to add some custom element like

<expires>2010-10-10</expires>

for some URLS.

If you don't mind a programmatic approach, then follow these steps:

Ensure that XML Sitemap module is installed & enabled
Create/use a custom module (say, MYMODULE) & use the following hook:

  function MYMODULE_xmlsitemap_element_alter(&$element, $link, $sitemap) {
    // Some logic to generate datetime
    // or hardcoded value
    $element['expires'] = '2010-10-10';
  }

Go to admin/config/search/xmlsitemap/batch-generate & click on 'Run'
Go to admin/config/search/xmlsitemap/rebuild & click on 'Rebuild sitemap'
Go to sitemap.xml, inspect element or view page source & verify that 'expires' tag is included

Hope this helps.


Allow downloading files from private filesystem when paths to files are built without Drupal I have set up files under private filesystem (large tree of dirs and files).
Drupal does not know anything about those files, because they are not added by file upload field, but links are manually defined as strings (in special field in content type), and put in place with ftp.

Also, path to those files are not completely contained within string, but constructed in field--field_myfiled.tpl.php (some taxonomy magic adds parts of the path, so in actual string i have only filename).

Now, adding just system/files/ before link constructed in field--field_myfiled.tpl.php returns privilege errors, so I guess i need to tell Drupal somehow to allow downloading these files. I am not sure - could I use hook_file_download in this case, and how I could implement this or simmilar function or approach to give access to those files ?

EDIT: My latest findings are that it seems that hook_file_download is triggered whenever you try to access a valid link to a file in private filesystem. No need for anything except hook_file_download here!

Here are a few modules that should help you configure the way files are served.

Storage API module. It provides advanced file storage and serving options; such as to upload or serve from a separate server, via ftp, etc. It's my favorite option. I currently use it to host all files on a separate server.
CDN module. Designed for CDN related tasks, but can be used in your case to specify an alternative file location for specific file types.
Remote Steam Wrapper module. Not sure if this will work for private files. It makes it easier to serve external files.
Media Mover module. Provides advanced file serving possibilities, i.e. get files from a FTP server, provide file tokens for authentication, get files from CCK fields, etc. It's only available in development version.

Update

If you want to do it via custom code, use field_view_value() function to pull the URL from the field. Use file_create_url to create URL for streaming. You'll also need to use hook_file_download to allow the file to be downloaded; otherwise you will get a page not found.

Update

If I understood correctly, you have a field, where you enter the file name (i.e. myFile.pdf), and you rewrote its field theme (field--field_myfield.tpl.php) to generate the full location of the file. The problem here, is that you cannot include hooks/functions within a theme. Your solution would be to construct the file location in a custom module or template.php.

Example of rewriting the field value via template.php. Replace MYTHEME with your theme name.

function MYTHEME_preprocess_field(&$vars) {
  if($vars['element']['#field_name'] == 'field_myField') {
    $filePath = '/secret/location/' . $vars['items']['0']['#markup'];
    $vars['items']['0']['#markup'] = file_create_url($filePath);
    return;
  }
}

If you want to check for permissions, use hook_file_download.


Views block per node I created a content type call Block. I want to use Views to display this Block content type per node. It means when I create a Block node, Views will create a block for me. So far I don't see any setting in Views allow me to do this. If it is possible I prefer using Views to do it instead of install another module like Nodeblock(nothing against it, just don't want to install another module when existing one can do it).

My original question is a bit confusing. To clear it up:

Is it possible for user to create a block by using a node? For example, user create a new node call 'My day' will automatically create a new block call 'My day'.
Is it possible to accomplish it by using Views module?

In your edit view, click on Advanced (located on the right side) For Contextual Filters click add. Search for "nid" and select Content: Nid

Under When Filter Value is not available, select the 2nd one (provide default value). For Type, select Content ID from URL.

This will filter your view, and show you the fields only from the current "Block content type" node that you're viewing.


Display flash, video, photo in slideshow I want to build a views slideshow. How can I display several format in this slideshow like flash format, video formats and photos together?

I want to upload a flash file, two photos, and one video to show them in a slideshow. I'm using Drupal 7.14.

The Views Slideshow module can loop through more than just Images.  You can even have it look through rendered nodes or custom content.

By using the Views theme and template features and views slideshow you should be able to mix nearly any content you want.

There is a video by Bob Christenson that gives a very good intro to the Views Slideshow module.  Though it is for D6, most of the content is similar enough to be useful in Drupal 7.


add field in admin>content that show if entity is translated I'm looking for a field that i can add in the admin>content view.
I want to know if the entity (News items) is translated or not. (Dutch(default) and English)
Now i always have to click edit article to see if the article is translated.

Search for hours on the internet but no result.  (i did installed the admin view module so i could edit the admin>content view)

Hopefully someone could help me out with this.

You can install the Admin Views module and override the view on /admin/content by adding a field that shows if the node has been translated or not.


Creating a custom FieldType (D8) I'm trying to create a custom FieldType which provides the fields for a complete address (street, house_number, post_code and city).

I created a FieldWidget, FieldFormatter and FieldType class and a "field"-template. (followed the guide at http://www.computerminds.co.uk/drupal-code/drupal-8-creating-custom-field-part-1-field-type and "seeing" Drupal core FieldTypes)

The widget does not get rendered unless I add an element_info()-Hook and a address_preprocess-Hook where I have to define the same stuff like in the FildWidget::formElement() method. But this is the Drupal7 way. Am I missing something?

FieldWidget class

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state)
{
  $element             = $element + array(
    'street'    => array(
      '#title'            => $this->t('Street'),
      '#type'             => 'textfield',
      '#default_value'    => isset($items[$delta]->street) ? $items[$delta]->street : null,
      '#required'         => false,

    ),
    'street_nr' => array(
      ...
    ),
    'zip'       => array(
      ...
    ),
    'city'      => array(
      ...
    ),
  );
  $form['#validate'][] = array($this, 'validateCompleteAddress');

  return $element;
}

FieldFormater class

public function viewElements(FieldItemListInterface $items)
{
  $elements = array();

  $elements['addresses'] = array(
    '#type' => 'fieldset',
    '#tree' => true,
  );

  foreach ($items as $delta => $item)
  {
    $elements['addresses'][$delta] = array(
      '#theme'     => 'fields_address',
      'elements' => $item,

      //'street'    => String::checkPlain($item->street),
      //'street_nr' => String::checkPlain($item->street_nr),
      //'zip'       => String::checkPlain($item->zip),
      //'city'      => String::checkPlain($item->city),
    );
  }

FieldType class

public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition)
{
  $properties = array(
    'street' => DataDefinition::create('string')->setLabel(t('Street'))->addConstraint('Length', array('max' => 255)),
    'street_nr' => DataDefinition::create('string')->setLabel(t('Street number'))->addConstraint('Length', array('max' => 100)),
    'zip' => DataDefinition::create('string')->setLabel(t('Zip'))->addConstraint('Length', array('max' => 5)),
    'city' => DataDefinition::create('string')->setLabel(t('City'))->addConstraint('Length', array('max' => 255)),
  );

  return $properties;
}

public static function schema(FieldStorageDefinitionInterface $field_definition)
{
  return array(
    'columns' => array(
      'street'    => array(
        ...
      ),
      'street_nr' => array(
        ...
      ),
      'zip'       => array(
        ...
      ),
      'city'      => array(
        ...
    ),

  ),
  'indexes' => array(),
  'foreign keys' => array(),
);

}

It seems like I have to provide a custom Element class in the module\Element folder to define the custom input elements for the form rendering.

See \Drupal\Core\Render\Element\Textfield.


How to customize a textarea field? I have created a textarea field using admin ui. It allows users to add Bio to their profile. I want to do 2 things with this field.

Limit the characters to 255.
Use a text format. Note: I do not want to allow users to choose a text format.

With HTML5 on Drupal 7 no JS is necessary if we can add a maxlength attribute to the textarea tag.

I tried to use a hook_form_alter to set this attribute, something like

$form['field_NAME'][LANGUAGE_NONE][0]['#attributes'] = array('maxlength' => 220);

or

$form['field_NAME'][LANGUAGE_NONE][0]['#maxlength'] = 220;

...and a gazillion variations using dsm($form) for ideas and to check my results. I could easily change the $form['field_name'] values but my textarea failed to acquire the maxlength atttribute.

This worked:

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 * Add a maxlength attribute to field_NAME.
 */
function MYMODULE_field_widget_text_textarea_form_alter(&$element, &$form_state, $context) {
  if (isset($element['#field_name']) && ($element['#field_name'] == 'field_NAME')) {
    $element['value']['#attributes'] = array('maxlength' => 220);
  }
}


Exclude a block from specific parts of the website with the Context module I have a view/block that is showing on the right sidebar. I don't want to show that block on specific parts of the website.

I do know there is the "Show block on specific pages -> All pages except those listed" option where you can put the URL and shouldn't appear, but it does not work.

This Drupal site is using Context to draw the content, so the problem may be there; I think there is another place where I can configure the URLs the same way I explained before on the context, but I cannot find it.

You can achieve this with the following steps in Context:

Conditions
Type: Path
Configuration:

*

~/user
Reactions
Type: Blocks
Configuration:
What you want.

The trick is inside the configuration part of Conditions
With the * you say it should be on all pages and you can exclude path(s) with the ~


How to implement Asset Inventory? I would like to create an Asset Management Inventory for our corporate helpdesk. There is a list of assets (laptop, phones etc) which our ICT staff members can borrow from the helpdesk. Members would not have direct access to the system, the main user would be just a helpdesk admin managing the loans.

These are the entities I'm planning to use but I'm not really sure how should I design my content types and how to link them with each other.

Borrower Information

Full Name
Username
E-mail
Telephone
Area
Office No.

Asset Details

Name
Model
Scope.

Loan Information

Borrowed On (date)
To be returned (date)
Updated On (date).

I was thinking about using a Field Collection as a Loan History as part of every Asset, in which the Borrower and the Loan Information would exist. So every time I need to create a new Loan record, I would choose the Borrower as an entity and fill in the Loan Information. If the Asset or the Borrower doesn't exist in the system, I would like the admin to be able to add them.

I'm not familiar with the Entity Reference module and I don't know if it would fit to my scenario. I need some guidance I'm afraid.

Start with creating 3 content types like so:

Borrower, with as fields the various attributed you mentioned within Borrower Information.
Asset, with as fields the various attributed you mentioned within Asset Details.
Loan, with as fields the various attributed you mentioned within Loan Information.

Then use the Entity Reference module to add 2 more fields to Loan:

a 1st entity reference field to indicate the Borrower.
a 2nd entity reference field to indicate the Asset.

Then use the Views module to build all sorts of lists. Such as a Loan history, which could simply be a list all nodes of type Loan, in which you'd also want to add a Views "relationship" to Borrower and/or Asset. You could also add some Views filter(s) to further  limit this list to fit your needs, e.g. to list all available (not borrowed) assets (as in your comment to my answer). For this kinds of lists I often use the dataTables module to make the searching even more flexible/dynamic (in the browser). Refer to my answer to "How to display the data of a View in table format?" for (way) more details on that.

You could easily take this a step further by also adding the Rules module to the mix. E.g. to schedule an eMail reminder to the borrower X days before the "to be returned date". However, for this to work (make sense), you'll also want to add an extra field (of type date) to the Loan type to register the actual return date of the Asset (which you should also add IMO even if you don't want this extra Rules feature). Assuming you added such return date field, you'd want to check it's value in such eMail reminder (to avoid sending reminders for Assets that were returned already).


How do I pull a field value from a form field in to my inline entity form? I'm trying to do something which I would think is fairly simple, but I'm just stumped right now, hoping somebody can help.

I have an entity called 'page', and in that entity I have inline entities called 'subpages'. Both of these entities have a field called 'group_reference' which tells the entity what 'group' the entities belong to.

Basically what I want to do is automatically change the group_reference form field value in my inline entity form to match the group reference in my page form. So far, I'm using inline_entity_form_entity_form_alter to access the inline entity forms values. I'm able to adjust the value to an arbitrary value like this:

function MYMODULE_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#bundle'] == 'subpage') {
    $entity_form['field_group_reference']['und']['0']['#default_value']=X;
  }
}

X being the group id.

So the next step I want is to pull in the group id from the page group_reference field which is already set. That way, they will always match (the user is not able to change this value, it all should be done behind the scenes).

I've tried to include in my module a function that pulls out the value from the field, but I just can't seem to make it work:

function MYMODULE_grab_group_reference(&$form, &$form_state) {
    return $form['field_group_reference']['und']['#value'];
}

function MYMODULE_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  if ($entity_form['#bundle'] == 'subpage') {
    $groupid=MYMODULE_grab_group_reference();
    $entity_form['field_group_reference']['und']['0']['#default_value']=$groupid;
  }
}

I've tried a bunch of different variations. Am I not targeting my values correctly? Is this just an improper way to do it? I'm flummoxed. Any help would be greatly appreciated! Thanks!

Just want to share my solution to this problem. Turns out I didn't need another function, I had all the variables available in my MYMODULE_inline_entity_form_entity_form_alter function in the $form_state array.

I targeted: $form_state['input']['field_group_reference'][und]

And that got me the value of the field in my parent entity.


why i can't write anything to a custom cache table? First in mymodule.install I declared mymodule_schema(hook_schema) mymodule_install() and mymodule_unistall()

Where mymodule_schema() is like this:

function mymodule_schema() {
    $schema = array();
    $schema['cache_mymodule'] = drupal_get_schema_unprocessed('system', 'cache');
    return $schema;
}

this worked perfectly and table cache_mymodule with the same structue as table cache was created.But in my code, using this:

$cid=some_calcuated_cid();
$cache=cache_get($cid,'cache_mymodule');
if (!$cache){
    $data = some_calcuated_data();
    cache_set($cid,$data,'cache_mymodule');
    dpm('CACHE SET');
else {
    dpm('used cache');
}

I always get 'CACHE SET', Now if i change 'cache_mymodule' to just cache, Or remove it, It works perfectly (saying used cache), Am I missing some hook in mymodule?

You don't need to create your own table to use the internal cache. Just use cache_set() and cache_get() as documented. This will store the $my_data in the default 'cache' table:

// Store $my_data in cache.
cache_set($data_id, $my_data);

// Get $my_data from cache.
$data = cache_get($data_id);

Your code snippet should look something like this:

$cid = some_calcuated_cid();
$cache = cache_get($cid);

if (!$cache){
  $data = some_calcuated_data();
  cache_set($cid, $data);
}

Documentation:

cache_set()

cache_get()


Block defined in code not appearing in admin interface I have implemented hook_block_info() to define a block inside a custom module 'x'. I have followed the documentation and believe the values in my array are correct. I have cleared all caches multiple times. I have disabled and re-enabled my module. I have tried setting status to both 0 and 1.

What is strange is that if I place a DPM() inside the x_block_info_alter(), I can see the block as an array when I visit the admin page. However, in the actual block list, it's not there!

Is there something wrong with my code that I can't see?

function x_block_info() {
  $blocks['mname'] = array(
    'info' => t('Admin title'),
    'cache' => DRUPAL_NO_CACHE,
    'status' => 1,
  );
  return $blocks;
}

I had exactly the same thing:  dpm() showing me my block on admin/structure/block, but no block actually appearing in the admin.  Disabling, uninstalling and re-enabling the module where I defined my block then clearing cache worked for me.


Accessing the uri within the template_preprocess_image_formatter I am using template_preprocess_image_formatter and I am trying to access the uri protected property inside the URL array (see screenshot)

does anybody know how to access it?

i've sorted it

you can do it like this

$variables['url']->getUri()


Sending a single email from a view I have a view where each page is a contract.  My client wants a button on the page that says "Send me more information." The button will send two emails, one to the customer saying "We'll get back to you" and one to my client.  My client's email needs to contain several fields from the view. (User email and name and node title at least.)

I've looked at various ways to do this, and none are quite right.

Views Send opens a message form.  I want the customer to do nothing more than click the button.
Webform would be good but I don't know how to pass the data from the view into a hidden field on the form.
Rules would work but I can't figure out what the event would be to trigger sending the emails.

I am an experienced site builder but really know zip about PHP, so I can't make a custom module.

Does anyone have any good ideas for what seems like a simple thing to do? Am I missing something obvious?

First thought that comes to mind:

I presume you have your view setup with an argument to create the different pages. Something like /productinformation/%

You could setup a second views display with an extended URL like /productinformation/%/senddetails

You can now make a couple of rules, whenever someone accesses /productinformation/%/senddetails you send the emails and redirect them back to /productinformation/%

When you send emails using rules you have access to tokens. This should give you access to things like the User Email or Page title. This is the part I'm not sure about, I don't know if you can get all the information you require through these tokens. Good luck!


Use hook_cron to send daily mail but I get 4~5 the same mail every day? I'd like to make all of my partners in my company receive daily metrics like new users, pageviews everyday, I wrote a custom module using hook_cron.

This is my code:

function custom_metrics_cron() {
  global $language;

  $default = strtotime('-24 Hours', REQUEST_TIME);
  $last_send  = variable_get('custom_metrics_daily_last_send', $default);
  $only_after = strtotime('+24 Hours', $last_send);

  if (REQUEST_TIME >= $only_after) {
    variable_set('custom_metrics_daily_last_send', REQUEST_TIME);
    drupal_mail('custom_metrics', 'daily', MAIL_RECIEVERS, $language);
  }
}

function custom_metrics_mail($key, &$message, $params) {
  $date = date('m-d-Y', strtotime('-1 Day', time()));
  $metrics = custom_metrics_get_metrics();
  switch($key) {
    case 'daily':
      $message['subject'] = t('Daily Metrics: !date', array('!date' => $date));
      $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
      $message['body'][] = custom_metrics_get_metrics();
      break;
  }
}

It works okay, I get the mails everyday, but the problem is I get not only one mail, I already set the variable and make it send ONE mail every 24 hours but I still get 4~5 mails every 24 hours. Can anyone tell me where does I do wrong?

D7, I struggled a lot, this is what i did, works perfect, following modules are required: Job shcheduler, Rules, and optionally Rules switch user, i use core cron; make a custom module 'MYMODULE' and place this code:

   /**
   * Implements hook_cron_job_scheduler_info().
   *
   * Do not forget to run job_scheduler_rebuild_all() on any changes here,
   * see https://drupal.org/comment/8406919#comment-8406919
   */
  // * Implements hook_cron()
  function MYMODULE_cron_job_scheduler_info() {
    $schedulers = array();
  //add as many scheduled jobs as needed.
  //$schedulers['daily_email_6_am'] = array(...);
    $schedulers['daily_email_7_am'] = array(
      'worker callback' => 'send_emails_action_7_am',
      'jobs' => array(
        array(
          'type' => 'notification',
          'id' => 1,
          'crontab' => '0 7 * * 1-6', // 7am, mon-sat
          //'crontab' => '0 * * * *', // once a day, midnigth
          //'crontab' => '*/1 * * * *', // once every minute, dev settings
          'periodic' => TRUE
        ),
      )
    );
    return $schedulers;
  }
  function send_emails_action_7_am() {
    // Do stuff.
    rules_invoke_component('rules_send_emails_component_7_am');
}

now you have a cron based scheduled job at 7 am from monday to saturday that executes a rule-component machine name: 'send_emails_component_7_am', be carefull, function calls: rules_MACHINENAME of component,  built rule component to send your emails, i  usually i built my emails with views rules module and have a great control to built email-body-value. see this answer, and this one also could be many emails, benefits of using views-rules as you can loop by views all users and filter them as needed and inject to rules whatever you imagine. emails are not 'duplicated', only 1 mail per user.

cron run as anonymous user, so, only if you have some content_access restrictions your emails won't be sent, here comes the benefit of 'Rules switch user', do pay attention with this module settings as this img suggest, i hope this helps someone.


How to remove dropdown items from a form? I am trying to remove two select list items from a form using this code:

function module_r_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == 'forum-node-form') {
        unset($form['edit-taxonomy-forums-und']['#options']['_none']);
        unset($form['edit-taxonomy-forums-und']['#options']['4']);
    }
}

The above code is not working. I would greatly appreciate any help you can give me in working this problem.

If the name of your field is edit-taxonomy-forums-und your code should be:

unset($form['edit-taxonomy-forums-und'][LANGUAGE_NONE]['#options']['4']);

Maybe you don't have the correct name of the field. Go to the Manage fields page of your content type (YOUR_SITE/admin/structure/types/manage/YOUR_CONTENT_TYPE/fields) and check the name of the field.

EDIT:

If you read the comments in the answer you will see that the problem was the change of forum_node_form by forum-node-form.


search in node-with-comments plus in unpublished nodes I need on my site a search. It should index the comments too, fulltext index is fine, they could be seen as part of body.

But as I use workbench with many steps, most nodes are unpublished. And I guess that ist not possible with builtin search.

So I checked search_api and it works for all content and its fields but NOT the comments.

Any suggestions what I could try?

You can use
hook_searchapi_entity_property_info_alter:

function mymodule_searchapi_entity_property_info_alter(&$info) {
    if (isset($info['node']['bundles'])) {
        // For each content type.
        foreach ($info['node']['bundles'] as $bundle_type => $bundle) {
                $info['node']['bundles'][$bundle_type]['properties']['comments'] = array(
                    'label' => 'node comments',
                    'description' => 'the comments of the node',
                    'type' => 'text', // or whatever you want here
                    'getter callback' => 'mymodule_searchapi_get_whatever', // name me whatever you want

                );
            }
        }
    }
}

and your callback

function mymodule_searchapi_get_whatever($entity, $options, $name, $entity_type, &$info) {
    // return the comments here, as you have everything in the function variables - i.e. use return.
}

Look at example implemntations of this hook and it should be enough to get your started.


How to expand/collapse text in WYSIWYG w/CKEditor In full nodes of a certain content type (using panels), I would like to display a text summary with a read more link to display full text, then a show less link to collapse.  I had smart trim enabled which allowed a read more link, but the page simply reloaded to the trimmed summary after clicking the link. I am using WYSIWYG with CKEditor.

So far I have tried jquery expander and expanding formatter.  Jquery expander didn't have any affect on the full text, expanding formatter displayed an ellipsis at the designated trim spot, followed by the full text, and a read more button after the full text.  So, essentially neither worked.

I tried js injector, plus this code and the full text showed -- no effect.

Is there something about WYSIWYG or CKeditor that prevents this function?  Suggestions?

This worked for me
JS Injector
(function ($) {

$(document).ready(function() {
    // Configure/customize these variables.
    var showChar = 100; // How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Show more >";
    var lesstext = "Show less";

    $('.more').each(function() {
        var content = $(this).html();

        if(content.length > showChar) {

            var c = content.substr(0, showChar);
            var h = content.substr(showChar, content.length - showChar);

            var html = c + '' + ellipsestext+ '&nbsp;' + h + '&nbsp;&nbsp;' + moretext + '';

            $(this).html(html);
        }

    });

    $(".morelink").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });
$(".morecontent span").css("display", "none");
$(".morelink").css("display", "block");
})
})(jQuery);

CKeditor

      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

      Morbi placerat imperdiet risus quis blandit. Ut lobortis elit luctus, feugiat erat vitae, interdum diam. Nam sit amet arcu vitae justo lacinia ultricies nec eget tellus. Curabitur id sapien massa. In hac habitasse platea dictumst. Integer tristique leo consectetur libero pretium pretium. Nunc sed mauris magna. Praesent varius purus id turpis iaculis iaculis. Nulla convallis magna nunc, id rhoncus massa ornare in. Donec et feugiat sem, ac rhoncus mauris. Quisque eget tempor massa.


how to set administrator menu i want to set

Site building
Site data management
Site configuration
Site users management
Store administration
Reports

as menus as admin login, else it show other menu bar.

Home
Search
Mark List
Contact
Help

so can any one suggest how will I achieve this.
cheers.
Sanjay Dev

Sounds like you are using Drupal 6. The Admin menu module provides a nice menu on top of the page for all admin items the user has access to.

Screen shot of admin menu http://drupal.org/files/images/Administration-menu.preview.png


Using images instead of text in menus I have a client who wants to use images instead of text for his menu items. Is there a native way to do this in Drupal 7?

In Drupal 7 you can using

Menu Icons module

  This module allows you to upload an image in the menu-item's configuration form.

Programmatically

Allow images in menu items in Drupal 7 OR Use images for menu items in Drupal

Reference:

Replacing menu items with images


Stop caching for a specific node (by nid) Drupal 7 Ideally i want to set custom params for caching in some particular nodes using conditions in my template.php

E.g. algorithm: for node with known nid set custom caching params

But that's enough for my purpose simply exclude from caching particular node.
I fond this solution: Stop caching for a specific node type Drupal 7 this is exacly what im looking for but how i can change condition of checking from node type to nid.

I know about CacheExclude module, but for me unwanted to install module for just exclude one node for caching.

I'll be very grateful for helping me.

A module with the below in it should stop caching on node 2. Change the number to do it on a different node id.

function MYMODULE_init(){
  if (arg(0) == 'node' && arg(1) == 2) {
    drupal_page_is_cacheable(FALSE);
  }
}


SOLR Snippet with link to PDF I'm using Apache SOLR as search engine. Everything works fine, indexing as I want, showing the data as I want. I only need to show the PDF which belongs to a certain snippet on a search result. Example:

Result 1: Node Title
Snippet1 -> snippet from node
Snippet2 -> snippet found in pdf x on this node
Snippet3 -> snippet found in node

Result 2: Node Title
Snippet1 -> snippet from node
Snippet2 -> snippet found in pdf x on this node
Snippet3 -> snippet found in node

Result : Node Title
Snippet1 -> snippet from node
Snippet2 -> snippet found in pdf x on this node
Snippet3 -> snippet found in node

The idea is, to have a list of snippets which can be either on the node itself or in a pdf (or any other file) which is attached to this node and link to it (in file case).

Tika extension and Apachesolr_attachments are in place and working.

I get the $vars['snippets'] from hook_apachesolr_search_snippets($vars) and I can modify the output. But I don't see how I could add more information to it.

Any help appreciated.

you can add extra field to solr.
you need to implement
hook_apachesolr_index_document_build_node(ApacheSolrDocument $document, $node, $env_id)

and there $document->addField('pdf_field_name', 'your_url');

also you need to implement hook_apachesolr_query_prepare(DrupalSolrQueryInterface $query)

and add there $query->addParam('fl', 'pdf_field_name');

then in your search-result.tpl.php
$pdf_field_name should be available (after reindexing)


How to give access to the files of node for individual users? In my website I have these modules enabled: File Entity (fieldable files), Media, Rules, Entity reference.

The default download method is: Private local files served by Drupal.

So when userA upload file to node. userB can't see it.

Q: How to give access to view file by entityreference(user) for userB?

UPD:

I create subdomain http://filesaccess.onenglar.com/

So you can login:

user: root

pass: root

UPD2:

Sharing access i think by entity reference field (user)

But how share access to the files of node for individual users?))

To do the access checking yourself you'll need to write a hook_file_download().

In broad strokes you'll need to get the actual file object (see this question for help with that), find the references with file_get_file_references(), and finally load them to check each reference (probably just one but it would be unwise to assume that's true) to see if the current user is given access to the file.


Views: Arrange table elements I'm having problems with arranging elements in a Views Table and I hope you can help me with it.
Instead of rendering each field in a separate column, I'd like to group some of them together in the same column as  shown below:

Credit to @Felix Eve.... Adding more details so that it will be helpful for others..

Edit Size & Price fields and check Exclude Checkbox
Create Global: Custom Text field below above fields so that you can use replacement patterns
Label it as Description
Use Replacement patterns in "Global : Custom Text" something like below .. Use correct tokens from replacement patterns

Size : [field:size]
Price: [field:price]


Add product variations to product display with rules Using RULES, can anyone point me in the right direction to add lots of product variations to existing product displays?

Everything I've researched seems to be centered around creating the display when the variation is created or vice versa.

In a nutshell, my customer has created the product displays and I've setup VBO to create all the product variations. However I can't find a way to add all my particular variations to a particular display unless I either use the "Product Display Manager" module (which doesn't appear to support Bulk Operations), or add the variations one by one via the "Inline Entity Form". We'll be talking about 1000's of variations in the end.

I am a novice at RULES but it's cool to use, so ideally I would like to be able to create a RULE called, "Add variations to display". which would be available on the this page:

admin/commerce/products/variations

where I can:

1/ Select the variation checkboxes
2/ Choose the rule
3/ Click APPLY
4/ Have the rule ask me which product display the selected variations should be applied to (Ideally a list of display TITLES)
5/ Then save that product display once complete (I should be able to do that bit in the rule from what I have read)

Love to hear if someone has been able to do this or at least point me to where I can follow instructions specific to my issue. But I have a sneaky suspicion that it can't be done like this, otherwise I would have found a solution already.

Cheers

Even though I've quite a bit of experience with the Rules module, I don't know (yet) of how to do exactly as you described in your question (also because your question does not exactly include the details about which Event(s), which Condition(s) and which Actions you are looking for (try to be more specific on that (by editing your question accordingly).

I might enhance my answer (soon), but while waiting you may want to look/investige if either of the approaches below can be of any help ...

Commerce Bulk Product Creation

Consider using the Commerce Bulk Product Creation module. Excerpt from its project page:

  ... facilitates the creation of groups of related products in bulk. Product administrators can select a number of options for various fields, and a product will be created for all possible combinations of these values. Out of the box, only list fields are supported for this, but an API exists to enable other types of fields for 'combination creation'.

Attention: this module doesn't have an official release yet (only an RC6), though with over 1.600 reported installs, it seems it is pretty stable / trustworthy.

Commerce Backoffice

Another option to consider is using the Commerce Backoffice module, e.g. because of the auto creation of product display nodes. It provides the backoffice functionality present in Commerce Kickstart (V2), and contains these sub-modules:

Commerce Backoffice Product (commerce_backoffice_product).
Commerce Backoffice Order (commerce_backoffice_order).
Commerce Backoffice Content (commerce_backoffice_content).

This module (and a few dependencies) provides the rich store owner experience that has made Commerce Kickstart 2 so popular (and prevents that you have to install the entire Commerce Kickstart distribution). And there is a great video introduction about it also.

Note: if you use Commerce Backoffice, you most probably also want to use the Shiny administration theme, also used in Commerce Kickstart (V2).


How can 'programatically' configure my site? I often find myself re-creating the same site: a 'clean' instance of what I have developed so far. It takes me several hours to do. So, I have created a .install file to create all of my content types and fields when I install the first of my custom modules. I also need to:

Create two menus
Configure some blocks
Configure the user permissions
Alter some of the default theme settings

What is the best approach to achieving the above 'programatically'? At the moment I do all of these tasks through the various user interfaces, but like I say it's time cosuming to keep doing it every time I want to start afresh.

Thanks

So You Want to Build a Drupal Distro

Take a look at Packaging a distribution on Drupal.org

Here are the steps:

Assemble the pre-requisites
Create a Drush Make file
Convert to a Drupal.org-specific Drush Make file
Build and verify it works
Commit your code to Git
Release your code on Drupal.org
Maintain your distribution

Another great tutorial How to Write a Drupal 7 Installation Profile

Also there is Profiler Builder module.

  Profiler Builder is a module for automating the creation of
  installation profiles and distributions. It has support for the
  Profiler installation profile simplifier library but is able to run
  independent of it (1.0-RC4+). This module creates a downloadable tar
  package that gives you a well made installation profile and associated
  drush make file based on the site its installed on.


Sticky Navigation 8.x-1.1. Funny padding-top In in Drupal 8.5 Theme Bartik and using the Sticky Navigation 8.x-1.1.
When by any chance I reload a page of my site and at that moment I’m positioned in the middle of that page and the menu is “sticky”,  the module add a padding-top equal to the height of the sticky menu bar to the tag Body (as an inline styling). If you go up to the top of the page, after reloading, there is a white strip at the very top of the page (originated by the padding top). Can some tell me how to fix it?

So far my solution was to apply CSS + jQuery to me theme:

CSS

body.js--padding-fix {
   padding-top:0 !important;
}

and JQUERY

jQuery(document).ready(function () {
    if (jQuery('div.primary-menu-container-global').hasClass('stickynav-active'))
    {
        jQuery('body').addClass('js--padding-fix');
    }
});

Note: if you apply the CSS directly to the body tag, it creates a problem with the Admin Menu, that covers the top of the site (minimized this way)

Is there a better solution?


Comment form not working in Drupal 7.x Primary tabs

View(active tab)
Edit

Status message

Forum topic Comment form not working has been created.
Posted by jassics on February 8, 2014 at 9:49pm

I am facing problem in commenting over blog or forum contents.
It is simply showing this error:

Error

The website encountered an unexpected error. Please try again later.

While checking error log I got this:

  EntityMetadataWrapperException: Unable to get the data property format
  as the parent data structure is not set. in
  EntityStructureWrapper->getPropertyValue() (line 438 of
  /home6/cusatalu/public_html/sites/all/modules/entity/includes/entity.wrapper.inc).

and when I checked filedsets I saw these warnings

  Notice: Undefined index: comment_node_panel in
  _field_ui_bundle_admin_path() (line 325 of /home6/cusatalu/public_html/modules/field_ui/field_ui.module). Notice:
  Undefined index: comment_node_panel in field_ui_fields_list() (line 35
  of /home6/cusatalu/public_html/modules/field_ui/field_ui.admin.inc).

Hope, someone is familiar with this error and would help me to fix soon.

I posted this in Drupal official site too.

First problem see: https://drupal.org/node/1909078#comment-8718835

"While I could be mistaken, I'm pretty sure that the error regarding "Unable to get the data property format..." (note the emphasis on format) when inserting a comment is due to code in:

message_notify/plugins/notifier/abstract.inc

Specifically these lines:

// Get the format from the field. We assume the first delta is the
// same as the rest.
if (empty($wrapper->{$field_name}->format)) {
  $wrapper->{$field_name}->set($output[$view_mode]);
}
else {
  $format = $wrapper->type->{MESSAGE_FIELD_MESSAGE_TEXT}->get(0)->format->value();
  $wrapper->{$field_name}->set(array('value' => $output[$view_mode], 'format' => $format));

}

The error occurs in the "comment insert" message type for the field_message_rendered_body field (and not the field_message_rendered_subject field) since it's a textarea that by default allows filtered text types to be selected (i.e. in Managed Fields, select the rendered body field and you'll see "Filtered text (user selects text format)" checked under "Text processing"). I haven't investigated fully yet but the bug can be avoided by selecting "Plain text" under "text processing" in the meantime (which will bypass the empty $wrapper->type->{MESSAGE_FIELD_MESSAGE_TEXT}->get(0)->format->value() in the ELSE statement)."


How to display a block with menu child items programmatically? I need to create block with a list of links menu child items (only first level) of a given menu like this:

Item 1
Item 2
Item 3

With this code I can have the menu items but I don't know how to process each element to obtain the menu item title and the menu item url.

$menu_name = 'main';
$menu_tree = \Drupal::menuTree();
$parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
$parameters->setMinDepth(0);

$tree = $menu_tree->load($menu_name, $parameters);
$manipulators = array(
  array('callable' => 'menu.default_tree_manipulators:checkAccess'),
  array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
);
$tree = $menu_tree->transform($tree, $manipulators);

I found the answer based in this question: How to turn a menu tree into an associative array?

You can use each array element as a item of MenuLinkInterface

To see others parameters check the class MenuTreeParameters

<?php
/**
 * @file
 * Contains \Drupal\YOUR_MODULE\Plugin\Block\SectionsFooter.
 */

namespace Drupal\YOUR_MODULE\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Link;

/**
 * Provides a 'SectionsFooter' block.
 *
 * @Block(
 *   id = "sections_footer",
 *   admin_label = @Translation("Sections"),
 *   category = @Translation("YOUR_MODULE")
 * )
 */
class SectionsFooter extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $menu_name = 'main';
    $menu_tree = \Drupal::menuTree();
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $parameters->setMinDepth(0);
    //Delete comments to have only enabled links
    //$parameters->onlyEnabledLinks();

    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $tree = $menu_tree->transform($tree, $manipulators);
    $list = [];

    foreach ($tree as $item) {
      $title = $item->link->getTitle();
      $url = $item->link->getUrlObject();
      $list[] = Link::fromTextAndUrl($title, $url);
    }

    $output['sections'] = array(
    '#theme' => 'item_list',
    '#items' => $list,
    );
    return $output;
  }
}

References:

Menu tree building is now a service


Delete/ Deactivate account in a separate block I want the authenticated users on my site to be able to delete their own account or temporarily block/de-active. I give the necessary permissions for this. Well and good for now. However, the tricky part is that i want these as separate forms in a page different that user edit. Something like shown in the image below: So that when the user navigates to this page say node/100 then the above is displayed. Any suggestions how to achieve this.

Regards

What you are describing will require a custom module that will provide the non standard functionality.

You will need to provide hooks for blocks (hook_block_info and hook_block_view) producing forms using the FAPI to produce the forms as you are showing in your mock.

Deleting an account would require using form validation to test that the username and password is correct and matches the content that you are viewing as well matches the user that is logged in. Once validated you would call the user_delete function, however be aware that this will delete all content owned by the user.

Disabling or Deactivating account will require a hook_block_info and hook_block_view  as well the form using the FAPI as well a subset of the  validation mentioned above, then calling the user_cancel function passing in the appropriate arguments.

The forms could be rendered using...
1. the blocks ui with conditional visibility settings.
2. at the theme level using a preprocess_page hook in template.php
3. other...

As Drupal is like a swiss army knife and this is one of many ways to solve the issue.


Commerce product variation with different variations I'm still pretty new to Drupal Commerce so I don't know if it's possible to group different variations under a product variation. This may sound weird, so here is an example of a grouped product variation.

As you can see the different product types have common values. The networking one has all values. So this is what I would like to achieve:

Create one product variation called transmission
Have the option to select the product type

The selection you made in the product type column will change the values you need to fill in.

Is this possible? Or would there be an other recommended solution to group like this. I would like to prevent that I have to create variations for each product type.

For something like this, you can create a Type field on the product and then have allowed values for Fiber, UTP or other. If you create these as a Taxonomy field, then they can be used to categorize other products or services with that same term.

You can create all of the fields and then use custom code to alter the form states to require/hide/show/etc. various fields on the form. All of the fields will exist, but only some of them might be shown. When you create your template for the product, you'll just need to ensure that you theme it properly.


Allow users to publish content to their profiles I want my users to be able to upload content to their own profiles. then when people view their profile they see a list of links which lead to what the user has uploaded.

Is this possible?

You can create a block view (Optional  with a filter to show the type of content you want to show) Add the Content title fields and any other field you want to add.

Then You have to set a Contextual Filter of the type Content Author.
Select the "provide default" option and from the type dropdown select user id from url.

Place this block in the user profile page.


Help with contextual filters needed I'm trying to understand how arguments get passed into a view.

I have a view which was working using
content: type (=PersonStory) which is a join table
connecting via Views Relationships to
content: type (=Person)
content: type (=Story)

Here is the old view.

I have installed Panelizer and have a default page for content: type (=Person). When an author's page is loaded, I want to load a view of stories which they have written.

As you can see from the preview, the NID finds the correct author's name, but none of that author's stories are showing. The NID comes from content: type (=Person) and not from the base table in the view content: type (=PersonStory).

Current view:

The contextual filter needed to be linked to Content entity referenced from field_personstory_person_id) Content: Nid and then it worked.

This does not help me understand how to pass the argument from the panel, though ;)


How to create statistical reports about data contained in various content types? I have page in drupal for hockey league. Till now, there was only nodes, some specific content types, simple views, but now, they want to create full statistics for the entire league. I was looking for some modules, but unsuccessfully.

My friends from this league want to type final score of match and system will know who is winner, credit points and calculate any other statistics data for team. I was trying to create something like this with rules, but I failed. I dont know ho to get SUM of fields from one content type, then calculate some value and get it to another content type, filter some values in views and get it to another view for his filtering.

I think that rules, views are insufficient for this. I need help, what way to choose.. trying do this in modelus or best way is to learn module development and create my own module to do this?

You may want to look at Computed field. You can use PHP to do calculations from information from other fields and show display the result. If you want, you can also save it to databse for use elsewhere. You can also try to do it in Views with Views calc. I think Views would be your better bet.


How do I create taxonomy terms from an exploded list? I have followed the procedure outlined on How to add multiple terms to a taxonomy reference field via feeds?

However, I'm unsure of what else to do in order to create taxonomy terms from a set of words imported via Feeds.

How should my content type be set up? I currently have the field set up as 'term reference' and have tried 'select list' and 'autocomplete' as widget type; neither displays any of the field data as a taxonomy term.

An important caveat thats missing from How to add multiple terms to a taxonomy reference field via feeds? is that the taxonomy terms already need to be defined in the vocabulary that you are referencing in order for feeds tamper to assign the term reference value to the node.

In the past I have created two feeds importers, one that is a taxonomy term processor that just contains the terms to load into the vocabulary, and one that is the node importer to import the nodes and have the taxonomy terms assigned to those nodes.

I may be wrong, but I dont believe that you can import nodes and simultaneously populate the taxonomy vocabulary in one step with feeds.


Utilizing private methods/vars inside module I'm creating a custom module which uses a few hooks and then after the form is submitted it will dive into custom PHP interaction that interfaces with an external restful API.

I want some of these variables and functions to be private as they will contain business rules and some variables that I wouldn't want someone to get their hands on (easily).

I'm uncertain of how to do this in Drupal. I understand that I would need to create a PHP class which would then have private/public methods available inside of it. But how do I do this?

Do I build this PHP class in its own file outside of my .module file and then use files[] = includes/MyClass.class.php in my .info file to import this external class file in?

Then once it's successfully imported in I could instantiate it with $something = new MyClass();?

Is it that simple to do, or is there another/better way?

Yes - it's that simple. Remember; Drupal is only PHP.

Although your class should be called MyClass.php rather than MyClass.class.php to adhere to the Drupal Coding Standards for OO code (note - this isn't explicitly declared, but is hinted at when they describe the Interface file naming conventions).

Just to pad this out a bit; you could also use the X Autoload module to allow for PSR-4 style autoloading instead of adding your class in the files[] array. I do this for as much D7 code as possible now (where I'm not using Composer Manager), and would whole heartedly recommend it.

  xautoload is a comprehensive and yet highly efficient PHP class
  loading suite.

  Most importantly, it provides Drupal-8-style PSR-4 (and the old D8
  PSR-0-style in "lib") autoloading for Drupal 7. But it is also a great
  tool for 3rd party autoloading.


Enable SSL for whole Drupal 8 site I'm running a Drupal 8 site behind a nginx webserver. All http request are redirected to https. My problem is that rss links on that site are http links only.

With Drupal 7 by setting the base_url all links are shown as https links. In Drupal 8 this option is missing. How can I set the whole site to https? Is there a config option for setttings.php?

Depending on how the RSS links are rendered, I would suggest calling them over with a protocol-relative URL such as:

//domain.com/rss-feed....

This will force the information to be sent over based on the way the page was rendered.  If the page was rendered using https:// it will use https:// in place of '//'


How to re-order user profile form? I have this code:

function mymod_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['#weight'] = 100;
}

Which is supposed to push the 'account' section of stuff underneath the rest of the form elements. But the weight seems to be fixed/the order is unchanged?

I've inspected the $form array at the point my code runs, and there are all the other fields, with their respective #weight values; and 100 is larger than any of those.

The weight you set here would be overridden by the weight values you set via Mange Fields.

However...

You can get around this by changing the weight in pre_render.

E.g.

function mymod_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  $form['#pre_render'][] = 'mymod_form_alter_weight';
}

function mymod_form_alter_weight($elements) {
  $elements['account']['#weight'] = 100;

  return $elements;
}


Change table class in view block Is it possible to change the table class when using drupal's format table for view. It seems to allow me to only change the row class.

go to core\themes\stable\templates\views folder and copy views-view-table.html.twig or .tpl.php (depending if you are on Drupal 8 or 7)

copy the file and re-name it views-view-table--[view-name]--[machine-name].html.twig or .tpl.php

Then edit the file and add the class

If Drupal 8

{%
  set classes = [
    'cols-' ~ header|length,
    responsive ? 'responsive-enabled',
    sticky ? 'sticky-enabled',
    'my-custom-class',
  ]
%}
<table{{ attributes.addClass(classes) }}>

If Drupal 7

<table <?php if ($classes) { print 'class="'. $classes . ' . ' ' . 'my-custom-class"'; } ?><?php print $attributes; ?>>

Now place your template file in your theme's template folder.

Clear/flush the cache to see changes.


Automatic Nodetitles: How to hide "Pattern for the Title" when empty I installed Automatic Nodetitles 7.x-1.0 on Drupal 7 for Staff Content Type. Everything seems perfect except the feature "Pattern for the title" for "Automatically generate the title and hide the title field".

The pattern I replaced with "[node:field-firstname] [node:field-middlename] [node:field-lastname], but it displayed the ACTUAL TEXT "[node:field-middlename]" on title when middle name is empty. Is there a setting or solution to hide pattern when empty?

Try the -dev version of the module. The release date for 1.0 of autmoatic nodetitles is 2011-Jun-07. You really think something released in 2011 is bug-free in against Drupal 7.31 (current stable release) ...

If you really care you could request a new supported release of the module in the issue queue.


How to resolve my warning in my custom service? I am getting the following error:

  Warning: Missing argument 1 for Drupal\custom_forms\Service\CustomFormsService::__construct(), called in /drupal/docroot/core/lib/Drupal/Component/DependencyInjection/Container.php on line 264 and defined in Drupal\custom_forms\Service\CustomFormsService->__construct() (line 13 of modules/custom_forms/src/Service/CustomFormsService.php).

And my code (service.php) is:

public function __construct($request) {
$this->cityname = \Drupal::request()->get('cityname');

if($this->cityname != ''){
  $result = \Drupal::database()->select('city_municipality','cm')
    ->fields('cm',array('municipality'))
    ->condition('city', $this->cityname)
    ->execute()->fetchAll();
    $result = json_encode($result);
    print $result;
    exit;
 }

custom_forms_services.yml

  services:
       custom_forms.custom_forms_service:
           class: Drupal\custom_forms\Service\CustomFormsService

But the form functionalities are working fine.

Can anyone help me out on this?

You need to add an argument to your services.yml for the class to be injected:

services:
  custom_forms.custom_forms_service:
    class: Drupal\custom_forms\Service\CustomFormsService
    arguments:
      - @request_stack

Note that you should make a few changes to your service as well:

First, add an type hint for the argument:

public function __construct(\Symfony\Component\HttpFoundation\RequestStack $requestStack) {

Next, you will use the $requestStack instead of Drupal::request():

$this->cityname = $requestStack->getCurrentRequest()->query->get('cityname');


What's the easiest way to create CRUD interface for custom entities? What is the fastest way to create admin UI for new entity type? Like at content types. I just need basic list/add/edit/delete actions.

One would think this comes with entity api?

I have found a lot of solutions but all of them included a lot of custom code, which is prone to errors.

is DrupalDefaultUIEntityController the answer? how can one use it?

The Entity Construction Kit (ECK) module allows you to create and manage entities through admin.
Here is a quote about it (from the module's project page):

...  builds upon the entity system to create a flexible and extensible data modeling system both with a UI for site builders, and with useful abstractions (classes, plugins, etc) to help developers use entities with ease.
ECK allows the creation and management of entity types with custom properties; adding bundles to entity types; and fields to bundles, with the help of the Field UI module.


want to load the multiple select box field data as per selected category using ajax form alter? I have list of select box like Team and Player with category option on top of the form. if i select the cricket in that category it should load players and Teams node title based on the category selected using ajax, i have done the ajax code but its working for only one field, please can onyone help to solve this

here is my complete code

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

  switch ($form_id) {
   case "loadtest_node_form":  // If the current edited page is an article form
    /*
    * The wrapper location is the entity reference field that contains the node titles
    * because that's where nodes listed needs to be restricted based on selection
    */
    $form['field_loadtest_player']['#prefix']='
';
    $form['field_loadtest_player']['#suffix']='
';
  $form['field_loadtest_team']['#prefix']='
';
    $form['field_loadtest_team']['#suffix']='
';

 $form['field_loadtest_category'][LANGUAGE_NONE]['#ajax'] = array( // adding an ajax attribute
      'callback' => 'jicustom_test_entity_callback1',
      'wrapper' =>'jicustom_test_entity_wrapper1',
      'method' => 'replace',  // the data would replace the field
      'effect' => 'fade',
      'event' => 'change',  // On change of the selection this action would take place
    );
$form['field_loadtest_category'][LANGUAGE_NONE]['#ajax'] = array( // adding an ajax attribute
      'callback' => 'jicustom_test_entity_callback',
      'wrapper' =>'jicustom_test_entity_wrapper',
      'method' => 'replace',  // the data would replace the field
      'effect' => 'fade',
      'event' => 'change',  // On change of the selection this action would take place
    );

// dpm($form);
    // Only when values are set in field_article_test_entity_type, should the options change
    // Also works for nodes that already have entity type selected
    if(!empty($form_state['values']['field_loadtest_player'])){
      $content_type = $form_state['values']['field_loadtest_category']['und']['0']['tid'];
      $form['field_loadtest_player']['und']['#options'] = jicustom_get_nodes($content_type);
    }
    if(!empty($form_state['values']['field_loadtest_team'])){
      $content_type = $form_state['values']['field_loadtest_category']['und']['0']['tid'];
      $form['field_loadtest_team']['und']['#options'] = jicustom_get_team($content_type);
    }
    break;
  }
}

/*
* Get List of node titles based on the content type
*/
function jicustom_get_nodes($content_type){

$result = db_query("SELECT n.title, n.nid
FROM node n
INNER JOIN field_data_field_category  ft ON n.nid = ft.entity_id
WHERE ft.field_category_tid = $content_type AND n.type='player'
ORDER by n.title ASC");
  foreach ($result as $record) {
    $nodes[$record->nid]=$record->title;
  }
  return $nodes;
}
function jicustom_get_team($content_type){

$result = db_query("SELECT n.title, n.nid
FROM node n
INNER JOIN field_data_field_category  ft ON n.nid = ft.entity_id
WHERE ft.field_category_tid = $content_type AND n.type='team'
ORDER by n.title ASC");
  foreach ($result as $record) {
    $nodes[$record->nid]=$record->title;
  }
  return $nodes;
}
function  jicustom_test_entity_callback($form, $form_state){
  return $form['field_loadtest_player'];

}
function  jicustom_test_entity_callback1($form, $form_state){
 return $form['field_loadtest_team'];

}

Use reference &$form_state instead of $form_state in functions
hook_form_alter(&$form, &$form_state, $form_id)

Edit:
Ohh yes, I got, there is one should be field_loadtest_player you used "field_loadtest_category" on both ajax
$form['field_loadtest_player'][LANGUAGE_NONE]['#ajax'] = array(
   ...
   ...
);
$form['field_loadtest_category'][LANGUAGE_NONE]['#ajax'] = array(
   ...
   ...
);


Ahah helper alwas getting error, but on other page no error I have forms with Ahah helper. When I tried to fill the form, it always getting this error:

warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'A' not found or invalid function name in xxx\includes\form.inc on line 378.

A = name of function, but that function is exist
xxx = location of drupal

Line 378 is:

$form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);

At page_new_init, there is no error at all. But, at page_initedit there's always error. This is the .module code:

$items['new/init/1'] = array(
    'title' => 'Add new',
    'type' => MENU_LOCAL_TASK, //MENU_NORMAL_ITEM,
    'page callback' =>'page_new_init',
'access arguments' => array('new'),
);

$items['new/editinit'] = array(
    'title' => 'Edit',
    'type' => MENU_CALLBACK, //MENU_NORMAL_ITEM,
    'page callback' =>'page_initedit',
'access arguments' => array('new'),
'file' => 'act.edit.inc',
);

And this is the form on function "page_new_init":

function page_new_init(){
  global $user;

 $output .= drupal_get_form('form_new_add2',$id,$codeact);

  return $output;
}

function form_new_add2(){
  global $user;

    $form = array();
    ahah_helper_register($form, $form_state);
    drupal_add_js("sites/all/modules/act/javascript/jss.js");

    $form['input']['account'] = array(
    '#type' => 'textfield',
    '#title' => t('Account Code'),
    '#size' => 60,
    '#default_value' => $account,
    '#required' => TRUE,
    '#autocomplete_path' =>'compose/code',
    '#ahah' => array(
        'event'   => 'change',
        'path'    => ahah_helper_path(array('input')),
        'wrapper' => 'input-wrapper',
        'method' => 'replace',
        'progress' => 'throbber',
    ),

    $form['input']['access_code'] = array(
    '#type' => 'select',
    '#title' => t('Access Code'),
    //'#required' => TRUE,
    '#default_value' => $access_code,
    '#options' => opt_accesscode(),
    );

  return $output;
}

And this is the other function "page_initedit":

function page_initedit(){
  global $user;

 $output .= drupal_get_form('form_initedit',$id,$codeact);

  return $output;
}

function form_initedit(){
  global $user;

    $form = array();
    ahah_helper_register($form, $form_state);
    drupal_add_js("sites/all/modules/act/javascript/jss.js");

    $form['input']['account'] = array(
    '#type' => 'textfield',
    '#title' => t('Account Code'),
    '#size' => 60,
    '#default_value' => $account,
    '#required' => TRUE,
    '#autocomplete_path' =>'compose/code',
    '#ahah' => array(
        'event'   => 'change',
        'path'    => ahah_helper_path(array('input')),
        'wrapper' => 'input-wrapper',
        'method' => 'replace',
        'progress' => 'throbber',
    ),

    $form['input']['access_code'] = array(
    '#type' => 'select',
    '#title' => t('Access Code'),
    //'#required' => TRUE,
    '#default_value' => $access_code,
    '#options' => opt_accesscode(),
    );

  return $output;
}

On "page_new_init", there is no error at all, Ahah helper works fine. But on "page_initedit" the error comes up:

warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'form_initedit' not found or invalid function name in drupal\includes\form.inc on line 378.

What should I do?

In .module file, I have to load .inc file. That's what I forgot! :(

include_once(drupal_get_path('module', 'act') .'/act.edit.inc');


how to set Drupal Auto complete OFF I am new to drupal i want to set auto complete off in my following code

$form['plantuser']['username'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#description' => t(''),
    '#required' => true,
    '#maxlength' => 50,
     '#weight' =>1,
  );

That code doesn't enable Drupal's autocomplete (it would need the #autocomplete_path property to do so), so I guess you mean the browser autocomplete?

The standard way to do that is to set the autocomplete attribute on the element which you can do like this:

  $form['plantuser']['username'] = array(
    '#type' => 'textfield',
    '#title' => t('Username'),
    '#description' => t(''),
    '#required' => true,
    '#maxlength' => 50,
    '#weight' =>1,
    '#attributes' => array('autocomplete' => 'off'),
  );

Bear in mind autocomplete is only valid using the HTML5 doctype; if you're using another doctype you'll need to implement a JS solution to set the attribute instead, e.g.

(function($) {
  $(function() {
    $('#input-id').attr('autocomplete', 'off');
  });
})(jQuery);


Without page refresh views exposed filters have to work (without AJAX) I want to create the Gallery like Example gallery link. Taxonomy filed in views exposed filters. Anyone guide to me?

You might wanted to check

Masonry Views

  This modules defines a masonry grid view style using Masonry API
  module.

Isotope.js

  Isotope.js provides David DeSandro's Isotope jQuery plugin to Drupal
  as a library. Isotope is a display plugin that comes with several
  unique layout modes for content, including the ever-popular "masonry"
  layout. In addition, the plugin also provides several methods for
  responding to user events like window resizing and real-time
  sorting/filtering.

Here is a good tutorial on Building a Dynamic Image Display with Drupal & Isotope


Loading a views block inside another block I'm pretty new to this, but I have been stumbling on a feature I would like to have. I'm using Drupal 7.

I've created a some blocks on my front page. In one of those blocks I have a some div's and text that goes inside of my block. That works just fine and looks great.

Problem is that I want to place some randomly generated testimonials inside this block and I can't figure out how to do so.

Now, I've already created another view block that lists my testimonials randomly, but I just need to know the correct php code. Note: I've also enabled the PHP filter module, but it doesn't seem to be working.

I can easily assign my random testimonial view to a block, but I want to combine some HTML along with the testimonial and I just dont know enough about php.

Example:

   Some random text here...
**PHP to bring in my random block of testimonials from views**
   Some random text here...

I've also heard that placing in PHP like this is not good practice. If anyone has a better way for me to do this I would appreciate it. Like I mentioned, placing this view in a empty block works fine. I just want to be together with some html.

Thanks!

-Dan

You can achieve it by following snippet in your block,

  Some random text here...
  echo views_embed_view('view-name', $display_id = 'display-name');
  Some random text here...

eg:

 <?php echo views_embed_view('test', $display_id = 'block'); ?> //dont forgot to enable text format as PHP.


Can't populate integer value in title field using rules I have a integer value that I'm trying to add to the title of a new node, but I can't figure out how to get it to work.

This the rule I have so far.

{ "rules_rule_create_bid" : {
"LABEL" : "Create a new Bid",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "button_field", "rules", "path" ],
"ON" : { "button_field_clicked" : [] },
"IF" : [
  { "button_field_compare_button" : {
      "clicked_field" : [ "field" ],
      "comparison_field_name" : "field_email_client"
    }
  },
  { "entity_has_field" : { "entity" : [ "entity" ], "field" : "field_client_email" } },
  { "entity_has_field" : { "entity" : [ "entity" ], "field" : "field_project_id2" } },
  { "entity_has_field" : { "entity" : [ "entity" ], "field" : "field_bid_count" } },
  { "entity_has_field" : { "entity" : [ "entity" ], "field" : "body" } }
],
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "new_bid",
        "param_title" : "Default",
        "param_author" : [ "site:current-user" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-bid-contractorname" ],
      "value" : "[site:current-user]"
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-bid-projectid" ],
      "value" : [ "entity:field-project-id2" ]
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-project-description" ],
      "value" : [ "entity:body:value" ]
    }
  },
  { "node_path_alias" : {
      "node" : [ "entity-created" ],
      "alias" : "p_[entity-created:field-bid-projectid]_u_[site:current-user]"
    }
  },
  { "entity_save" : { "data" : [ "entity-created" ], "immediate" : "1" } },
  { "data_set" : {
      "data" : [ "entity-created:title" ],
      "value" : "New Project #[entity-created:field-project-id2]"
    }
  },
  { "redirect" : { "url" : "p_[entity-created:field-bid-projectid]_u_[site:current-user]#overlay=node\/[entity-created:nid]\/edit" } },
  { "drupal_message" : { "message" : [ "entity:field-client-email" ] } }
]
}
}

I want the entity:field_project_id to show in the title, but all I get is the project number.

Title is a string, that's why, in your rule, before setting title value, add a variable, then set variable value to the integer value, then add an action: "convert a data type": your variable, from integer to string, then set a data value, your node title as variable name. else leave the same as it is.


URL function with i18n localization I'm using the Rate module for voting. When an anonymous user clicks on the voting widget, the user is redirected to a url "user/login-to-rate". I'm also using i18n for localization. The issue with both of these together is that when I'm on a page with the URL "en/my-url" and I click on the voting widget, I'm redirected to "de/user/login-to-rate" where "de" is my default language. Ideally the user should be going to "en/user/login-to-rate" i.e. user selected language should be respected.

Going into details, I find that the rate module calls url() using the following code:

print url('user/login-to-rate', array('query' => $query, 'absolute' => TRUE));

There is no language paramater that is passed, which means the default site language gets selected.

Am I missing something here in the configuration? Has anyone faced a similar problem and can help?

url() uses the current language by default, you only need to pass the language to it if you want another language, e.g. when sending mails to a user with a different language.

If you're on en/something and the global language is not en, then something else might be problem, for example incorrectly configured language recognication.


Is there anyway create relationship for filter criteria which has vocabularies( state, city and location)? list of available Vocabularies in my content type.

Country(Term: US)
State (Terms: CA , CO, DE.. etc)
City (Terms:Fremont, Irwin, Los Angeles, Monument etc..)
Location(Terms: All loacations)

I'm trying to create a view for published content result which uses above vocabularies. I need to expose filters to the users where I added above vocabulary fields. How to create a relationship to select particular state->city-> location
(For ex: State(CA)->City(Fremont)->location(xxx-fremont))
Below is the example filter. Please help. Thank you!

The Relationship option in Views tracks entity references, so to use that option, you have to create Entity References among your terms.  In taxonomy terms, the parent and grandparent are entity references.
Generally speaking, Views can only use a data structure that already exists in the database, or can be built from other structures in the database; it can't create a structure "out of thin air."
One approach: Using parents and grandparents
To use parents and grandparents, you would have to delete your current terms and re-structure them like this:

Grandparent: Country
Parent: State
Child: City

You can do this by setting the parent when you create each term:

Countries have no parent
States have a country as parent
Cities have a state as parent

Since there are no rules that enforce this structure unless you code the rules yourself, you have to be careful to make sure you set things correctly.
If you take this approach, you can add relationships to get the parent / grandparent under Relationships in Views, but making the filters by country / state / city will be a pain.
Alternative approach that will make it easier to add the filters but that is harder to maintain
Keep the vocabularies independent.  Add an entity reference field (term reference) to the State term type called Country and let users select a country.
Add two more entity reference fields (term reference) to the City term type called State and Country.
Then you have to set the correct country for each state, and state and country for each city.
Then, in your View, you can simply show a list of cities, and the filters for Country, State, and City will work for cities as you expect.
Note, however, that if a country or state has no cities, no entries will appear.  This is because we set this View to only show the list of cities to make setting up the filters easier.


How to make subprocess & migration_lookup plugins behave consistently with single and multiple items arrays I have a JSON that can hold single or multi values arrays and I can't make subprocess + migration_lookup behave consistently. It correctly imports the nodes in all cases, but it adds the reference to the imported nodes (entity reference field) only when I have more than 1 item in my array.
my JSON can looks like this:
"behaviour": [
          {
            "name": "behaviour name",
            "description": "behaviour description"
          }
        ]

or like this:
"behaviour": [
          {
            "name": "behaviour name",
            "description": "behaviour description"
          },
          {
            "name": "another behaviour name",
            "description": "another behaviour description"
          }
        ]

the process part of my migration config:
  field_behaviour:
    plugin: sub_process
    source: behaviour_array
    process:
      target_id:
        plugin: migration_lookup
        migration: import_behaviours_json
        source: name

This is just guessing, but you could try forcing the multiple flag on the source field using the multiple_value plugin from Migrate Plus:
field_behaviour:
  -
    plugin: multiple_values
    source: behaviour_array
  -
    plugin: sub_process
    process:
      target_id:
        plugin: migration_lookup
        migration: import_behaviours_json
        source: name