Passing data from outer preprocess to inner template I have two templates:
- a child that is printing each item in a list;
- and a parent that calls it
there is also an intermediate Field template that is not involved.

The parent has preprocess access to node field data that each child (node teaser) call needs to use. The child is printing items in a multivalue entity reference field.

How can the child get the data from the parent felds so it can print the right html?

Edit: Just in case it's not clear, the situation is:

paragraph_entity        <== preprocess hook can see field_settingsN which change how "B" and "A" render (e.g. add/change attrs, class).
  -> field_settings_1
  -> field_settings_2
  -> field_references   <== have a defined template "B"
    -> 1.. entity refs to nodes
      -> node           <== have a defined (teaser) template "A"

Done this a couple times, but really got the caching better last time so that it works perfectly... I've put in some fairly verbose comments, but if anything is unclear just shout.

/**
 * Implements HOOK_preprocess_paragraph().
 */
function HOOK_preprocess_paragraph(array &$vars) {
  /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
  $paragraph = $vars['paragraph'];
  // Change 'content_reference' to be your paragraph bundle's machine name.
  if ($paragraph->bundle() === 'content_reference') {
    // Instead of 10 set that to be the max number of references in the field.
    foreach (range(0, 10) as $i) {
      // Change all references to 'field_content_reference' to use your field's
      // machine name.
      if (!isset($vars["content"]["field_content_reference"][$i])) {
        break;
      }
      /** @var \Drupal\node\Entity\Node $node */
      $node = $vars["content"]["field_content_reference"][$i]["#node"];

      // Example change to the Node.
      $node->field_parent_paragraph = $paragraph;
      $changed = TRUE;

      if (isset($changed)) {
        // If we've changed the node, give a new cache id.
        // THIS IS IMPORTANT!
        $vars["content"]["field_content_reference"][$i]['#cache']['tags'][] = "paragraph:{$paragraph->id()}";
        $vars["content"]["field_content_reference"][$i]['#cache']['keys'][] = "paragraph";
        $vars["content"]["field_content_reference"][$i]['#cache']['keys'][] = $paragraph->id();
      }
    }
  }
}

Follow that up with something like:

/**
 * Implements HOOK_preprocess_node().
 */
function HOOK_preprocess_node(array &$vars) {
  /** @var \Drupal\node\Entity\Node $node */
  $node = $vars['node'];
  if (isset($node->field_parent_paragraph)) {
    $paragraph = $node->field_parent_paragraph;
    $vars['content']['#attributes']['class'][] = $paragraph->field_settings_1->value;
  }
}


External Server Theming Workflow Running into a slight workflow problem, and finding out that a lot of us being new to Drupal doesn't help. =) Thank you in advance.

The issue being is that a lot of the front-end developers at my company are used to working locally with every project. But our new Drupal CMS I would like to only have running in one location, not on their local machine or our internal server, but only running on a remote server and installed once. We will have many running for our clients and I need to keep the code maintained properly, and would hate a front-end developer to work on it locally to only find out their version is behind now during the length of their project. Or worse yet, they are working on five projects at once and they have to maintain all of those on their machine.

We figured out a small hack to get CodeKit to work on their machine while still seeing the files on the server refresh, so SASS isn't an issue. But they are so used to working locally, they are having a hard time grasping theming on a remote server. I am very much used to working in larger applications that need several environments or complicated compiles, so using Drupal in one place seems SO easy to me.

How does everyone else work on themes? What does your workflows look like? What advice can you give? Anything will help!

I mount the remote drive locally using 'Transmit' so I can use my local dev stack (sublime, livereload, sass, compass etc...). This does not always play nicely with file permissions and kinda urks some of the devs who are used to working locally then to git and staging servers for testing. I just backup alot and like to fly by the seat of my pants on the live server... although I feel i should be working git in there more!


Render a custom region inside node template I am attempting to render a menu assigned to a block right next to the body of a custom content type. I am using Drupal 7.

I have a custom region defined within my template .info file. I would like to render this region and the block assigned to it from within a custom node template ...

node--<my custom content type>.tpl.php

I needed to do this within the custom node template because I needed to break out the individual fields of the content type rather than just using

print render($content);

This is what I was trying to do ...

  <?php
    print render($content['title']);
    print render($content['field_banner_image']);
    print render($content['body']);
  ?>

<?php print render($page['MY-CUSTOM-REGION']); ?>

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

However, my menu block does not render and I get the following error ...

Warning: Cannot use a scalar value as an array in include()[PATH TO MY CUSTOM NODE TEMPLATE]

Is it possible to render a region from within a custom node template?

You should load your menu yourself inside node, use:

hook_node_load
hook_node_view
hook_preprocess_node


Update Drupal Modules - skip a version? I've neglected a site for a while, and now I need to update some modules that are several versions out of date. Can I just jump to the newest version of the module or do I need to copy each version in order and run update.php each time?

Also, if several modules need updating, is it OK to copy all the files across and run update.php once, or do I need to copy each module individually and run the update each time?

As long as you're not skipping major Drupal versions (i.e. going from Drupal 5.x to Drupal 7.x), just jump to the new version(s).


Takes too long to render a product display with 6000+ variations I have a product with several attributes and each one with several options. The total variations is over 6000.
The problem is that rendering takes too long. I've enable Devel module and here are the results:

Executed 72 queries in 323.6 ms.
Page execution time was 13870.81 ms.
Memory used at: devel_boot()=1.44 MB, devel_shutdown()=62.56 MB, PHP peak=69.5 MB.

So I guess there's some bottleneck at the code.

Some notes about the implementation:

I need a unique price for each variation.
I'm using vanilla Drupal Commerce.

There's any way I could improve performance?

Didn't find a proper solution to increase the performance or, at least a clean solution. So I decided to create a module that basically holds an alternative view formatter to the "Add to cart" that comes with Drupal Commerce.

You can find the module here: https://www.drupal.org/sandbox/marcofernandes/2705035

Basically it's a "clone" of "Add to cart" view formatter but it avoids iterations over all variations and field options. It's not perfect but it fits my needs (variations for all possible combinations). I'll keep it as a sandbox until it reaches a more mature state (it lacks some validations and, probably it misses some code styling).


Drupal 6 Migration: Files not showing? I am creating a dev site from production and I read the migration guide and it's basically -- export database, rsync files. So, I cleared the cache (drush cc all) and also turned off Clean URLS because that was suggested in the guide.

I then proceeded to export the database & web directory & files... structure originally;

/home/drupal
/home/drupalfiles
MySQL DB

I decided to change the locations...

/var/www/html/drupal
/var/www/html/drupalfiles

However, all the images are now displaying with an 'x'. When I right click on the image, it says it's looking for files in /system/files ... which, I have a symbolic link in /sites/default/all for files to drupal_files (which wasn't needed on production, btw). Even then, I don't know why it's trying to look in a directory called system.

The file-system settings is listed as 'files' on production and dev. So, I have no idea what's going on :( .. in the database, files are listed as /files/.

So frustrating :(!
Any help would be appreciated.

If you're using symlinks, you'll have to allow that in your .htaccess file.


How can I disply the regex match in a view? This is a Drupal 7/Views 3 question.

I am using a regex as a filter in a view to select Body fields with certain characteristics. However, when it comes to displaying the field, I don't want to display the entire body, just the match or matches.

For instance, for the following filter on the Body field for a match on regex:

<h[23456]>[^<]*[.!?:;,][^<]*</h[23456]>

I want to display a views Body match column which only displays any regex matches, not the entire Body field. So in this case I only want to display headings that have punctuation in them which are contained within the body.

This will not display to the public, so I'm not concerned with whether it's pretty, only whether it's readable. So it doesn't matter whether it displays HTML as HTML or as plain text.

However, the Rewrite Results field in the fields edit does not provide an option to match on regex for displaying the text.

How can I accomplish this?

You can create your own module that adds a field formatter for the text_with_summary field type. At the bare minimum you will need to implement the following hooks:

hook_field_formatter_info() for defining the formatter
hook_field_formatter_view() for outputting the results
hook_field_formatter_settings_form() for adding a form field to input the pattern into

Here is an example that will do what you are asking for, but still requires a lot more work before you should use it in production. For example, it doesn't validate the pattern, and does not have an input field to enter the regex pattern in the Manage Display page for content types, even though it can be selected as a formatter.

/**
 * Implements hook_field_formatter_info().
 */
function my_module_field_formatter_info() {
  return array(
    'my_module_regex_formatter' => array(
      'label' => t('Regex matches'),
      'field types' => array('text', 'text_long', 'text_with_summary'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function my_module_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = $display['settings'];
  $element = array();

  if ($display['type'] == 'my_module_regex_formatter') {
    $pattern = FALSE;
    if (isset($settings['my_module_regex_pattern'])) {
      $pattern = $settings['my_module_regex_pattern'];
    }
    if ($pattern) {
      foreach ($items as $delta => $item) {
        $matches = _my_module_get_regex_matches($pattern, $item['value']);
        $element[$delta] = array('#markup' => $matches);
      }
    }
  }

  return $element;
}

/**
 * Returns regex pattern matches.
 */
function _my_module_get_regex_matches($pattern, $subject) {
  $result = '';
  $regex_result = preg_match_all($pattern, $subject, $matches);
  if ($regex_result) {
    $result = '
';
    foreach ($matches[0] as $match) {
      $result .= '
' . check_plain($match) . '
';
    }
    $result .= '
';
  }
  return $result;
}

/**
 * Implements hook_field_formatter_settings_form().
 */
function my_module_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $default = '';
  if (isset($settings['my_module_regex_pattern'])) {
    $default = $settings['my_module_regex_pattern'];
  }
  $element = array();
  if ($display['type'] == 'my_module_regex_formatter') {
    $element['my_module_regex_pattern'] = array(
      '#type' => 'textfield',
      '#title' => t('Regex pattern'),
      '#default_value' => $default,
    );
  }

  return $element;
}

This will add Regex matches as an option in the Formatter select box within the Views configuration form for text fields, including the Body field. When you select the Regex matches formatter, a text input field will appear with the label Regex pattern. The pattern needs to include delimiters, and be properly escaped. The pattern in your question would look like this:

/\<h[23456]\>[^\<]*[\.!?:;,][^\<]*\<\/h[23456]\>/

The pattern is surrounded by a delimiter: /
All brackets are escaped: \<h, \>
The period is escaped: \.
The forward slash is escaped: \/h

preg_match_all() is used to perform a global regular expression match. The matches are outputted as an unordered list of escaped html (i.e. you will see the header tags in the output).


Exporting fields for content type The configuration export feature of Drupal 8 would seem to be a very useful feature. However, I'm not sure I completely understand how it works.

For example, if I do a single export, choose "Content type" then select one of my content types, I would expect that export to contain a full description of that content type. But it doesn't contain any information about the fields in that content type. So if you wanted to export a content type configuration for use on another site, it doesn't seem possible to do that.

I'm not sure I understand the use of being to do Single exports if they don't contain all the required data for an entity. Am I missing something?

UPDATE

You might also try Drupal Console's drupal config:export:content:type command.

It's description says:

  The config:export:content:type command Export a specific content type
  and their fields.

Content types and Fields are 2 separate configuration in Drupal 8, so if you want to export content type with fields you have to export all it's fields configurations too.

Features module might be helpful for grouping configurations, it's not stable yet, I haven't tried it but I think it might worth trying.


Views Data Export: Multiple Columns with Unique Rows (D7) I'm using Drupal 7

I have a view displaying users that are referenced by another entity that has a date field, like this:

John Doe      5/6/12
John Doe      5/8/12
John Doe      5/16/12
Mary Jane     5/5/12
Mary Jane     5/7/12

So, behind the scenes, there's a content type of "Reservation" with a date field and a user reference field.  I'm pulling in all of these reservations and displaying the user name alongside the dates of their reservations.

When I use the views_data_export module, I'm able to export this data as an xls file, which allows this data to open nicely in MS Excel.

The solution I'm looking for is to be able to group this data by user, to create unique rows with multiple columns, like this:

John Doe      5/6/12   5/8/12   5/16/12
Mary Jane     5/5/12   5/7/12

So, if a user has 20 pieces of data, then 20 columns will display next to that user with each column displaying each piece of data.

Have you noticed the following setting on the field which has multiple values:

That should be a collapsed section right under where you specify the label, etc of your field.  Just make sure you check that you want them to appear in the same row and select a separator (comma by default).

That should be all you need!  Does it transfer well for the export?


Cleaning up the node edit URL Say I have node/111/edit, and that node's path is my-node. I want the edit page to be at
my-node/edit, instead of node/nid/edit.

Is there an existing solution for cleaning up the node edit URL, e.g. a custom module or the Pathauto module? All I see for the Pathauto module is a place for page patterns, but that would only handle page views, not edits.

This issue in pathauto Replacing node/XXX/edit to mypage/edit lead to this module: Sub-path URL Aliases give it a shot.

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


Is there a function that can output an image? [field_img] => Array(
  [0] => Array(
    [fid] => 200
    [list] => 1
    [data] => Array(
      [alt] =>
      [title] =>
    )
    [uid] => 1
    [filename] => cpon.jpg
    [filepath] => sites/default/files/cpon_0.jpg
    [filemime] => image/jpeg
    [filesize] => 4434
  )
)

Is there a function that, using the above information, can output an image?
Is there any other method to output an image using the above information?

You can use theme('image').

Supposing that $img contains the PHP object you reported, then the following code can be used to output the image.

$output = theme('image', $img->filepath); // Drupal 6.
$output = theme('image', array('path' => $img->filepath)); // Drupal 7.


How can I redirect the users after confirmation basing on the roles they have? I have two type of users, and I have created two types of registration forms for each role. I want to redirect the users to different pages, once they get the email confirmation according to their roles.

For example:

user1, with the first role, must be redirected to page1
user2, with the second role, must be redirected to page2

I think I can achieve this feature using the Rules module, but I don't know how to do it.

Can you tell me how can I implement it?

yes, with Rules!

create a new rule.
select event: user has logged in (or if you use LoginTobogan module you can use the event "When the user account is validated".)
select condition: User has role(s), and assign the role (I recommend create a new Role and assign this role to a test user)
selet the action: Page redirect, and add the url to the destination
(I have selected 'Immediately issue the page redirect' to see the redirection (if is not select this, I can not see working the redirection, but test if you does not need this. Please review the warning about the setting)
enable your rule and test.


Change Text of Create an Account in Login Block I want to change text of Create an account to

something>
Click here

When I print the form I got these values

[links] => Array
        (
            [#markup] =>

Create new account

Forgot your password?

        )

Also, I gave a try in settings.php like

$conf['locale_custom_strings_en'][''] = array(
  '"Create a new user account' => '
somethifn>
Click here',
);

But this prints as a text.

Anybody can help?

The above mentioned problem can be easily solved by using hook_form_alter hook_form_alterhook_form_alter(&$form, &$form_state, $form_id) . You can use that function in our template.php of your custom theme .

In template.php write..

function custom_theme_form_alter(&$form, &$form_state, $form_id){
  if( $form['form_id']['#value'] === 'user_register_form'){// For registration form on 'user/register' page
    $form['actions']['submit']['#prefix'] = '
';
    $form['actions']['submit']['#value'] = '--your text--';
    $form['actions']['submit']['#suffix'] = '
';
  }
  if( $form['#id'] === 'user-login-form' ){  // For login block that comes with drupal core blocks and can be assigned to any region.
    $form['links']['#markup'] = '

--your text--

Request new password

';
  }
}

This will change your text from 'Create a new account' to your custom text. And don't forget to clear the cache :).

Reply on this thread if you still find some problem.


Search input in Drupal 8 I have a website built in Drupal 8.
In one of the basic page, I have to add a search box which searches only the contents in that specific page.
Please suggest the best practice to implement this.
Thanks.

You need to create a view page, and in the FILTER CRITERIA you can add "for example" : content datasource:title and add the title of this specific page if it will not change
But the best is to use : ID = nid that you will find in your database in the
node_field_data table
Search for the title and you will find your ID and use it to filter in your views and that's it !


How to fix field collection ajax #edit-submit clash with node #edit-submit? I have Drupal 7.41, field_collection 7.x-1.0-beta10+1-dev, and field_collection_ajax 7.x-1.x-dev

I am the admin of a site where we have a disease content type, and a part of each disease node is its lab tests. (Some diseases have upwards of 400+ lab tests) I use Field Collection to format the lab tests, and I use Field Collection Ajax to display them in an way that makes them easier to work with when there are many lab tests.

Field Collection Ajax uses ajax to display, edit, and save the individual field collection items. The "Save Item to List" button for Field Collection Ajax appears to be getting mixed up with the node save button. They both have the same id #edit-submit. I don't know for certain, but it appears that on the disease nodes that have 400+ lab tests after you edit a lab test, the next time you try to save another field collection item to the list it acts like you are trying to save the node, and the next time you try to save the node it acts like you are trying to save a field collection item.

Does anyone have any experience with this happening with field_collection_ajax and know how to solve it?

The problem was that that large node was hitting the max_input_vars cealing. So I just had to increase that and it worked.


How to make passwords case insensitive? it appears as passwords in Drupal 7 are case sensitive. Is there a way to make them case insensitive?

The password is stored as a hash, upper/lowercase differences result in a different hash.

The only possible way I can think of is if you always convert the password to upper/lowercase before it is used, both when registering and when logging in. But that sounds error prone to me.

Also, if the passwords are already stored in the database, then there is no way to do it.


How do I make a custom entity update or create automatically update the solr index? I have implemented a custom entity type which is essentially identical to what the Model module does, with a few additional fields.

I have followed the Apachesolr User module to understand how to index my custom entities in the solr index. But when I add, or update and existing, entity the solr index is not automatically picking up the changes.

/**
 * Implements hook_apacheolr_entity_info_alter().
 */
function my_entity_apachesolr_entity_info_alter(&$entity_info) {
  $entity_info['my_entity']['indexable'] = TRUE;
  $entity_info['my_entity']['status callback'][] = 'my_entity_status_callback';
  $entity_info['my_entity']['document callback'][] = 'my_entity_solr_document';
  $entity_info['my_entity']['reindex callback'] = 'my_entity_solr_reindex';
  $entity_info['my_entity']['index_table'] = 'apachesolr_index_entities_my_entity';

  $entity_info['my_entity']['result callback'] = 'my_entity_result';
}

This is the hook I had to implement to index my content, the various callbacks are irrelevant. It is worth noting the index table needs to be implemented in hook_schema() as well. This can be easily seen in Apachesolr User

Originally I thought I had to implement my own hooks but after seeing that apachesolr took care of deletes I wondered why it hadn't taken care of my updates and inserts.

There is actually a apachesolr_entity_update/insert() which calls apachesolr_entity_should_index(). That checks whether your entity info (returned by entity_get_info($entity_type)) has the following key set:

$info['bundles'][$bundle]['apachesolr']['index']

Where $bundle is the $entity bundle. This made it pretty easy for me to figure out that I just had to add some stuff to my hook_entity_info_alter():

function my_entity_entity_info_alter(&$entity_info) {
  foreach (my_entity_get_types() as $type => $info) {
    $entity_info['my_entity']['bundles'][$type] = array(
      'apachesolr' => array('index' => TRUE),
    );
  }
}

After adding that and clearing cache I no longer needed my entity update/insert hooks.

Note: Don't get this confused with hook_apachesolr_entity_info_alter like I did!

Original Answer

I found the function apachesolr_index_get_entities_to_index() which checks the indexer table for your entity_type for a changed timestamp that's greater than what it's last seen (I have yet to find out where it sets that). Essentially we just need to automate the updating of that table. This can be done with 2 hooks:

hook_entity_insert()
hook_entity_update()

/**
 * Implements hook_entity_insert().
 */
function my_entity_entity_insert($entity, $type) {
  // Update our indexer table
  if ($type != 'my_entity') {
    return;
  }
  $indexer_table = apachesolr_get_indexer_table($type);

 // Insert the new entity into a fictional table of all entities.
  $info = entity_get_info($type);
  list($id) = entity_extract_ids($type, $entity);
  db_insert($indexer_table)->fields(array(
    'entity_type' => $type,
    'bundle' => $entity->type,
    'entity_id' => $id,
    'changed' => REQUEST_TIME,
  ))->execute();
}

/**
 * Implements hook_entity_update().
 */
function my_entity_entity_update($entity, $type) {
  // Update our indexer table
  if ($type != 'my_entity') {
    return;
  }
  $indexer_table = apachesolr_get_indexer_table($type);

  db_update($indexer_table)
    ->fields(array(
      'changed' => REQUEST_TIME,
    ))
  ->condition('entity_id', $entity->entity_id)
  ->execute();
}

You may have to add this line into the insert statement in hook_entity_insert() if you have a status coming from $entity (mine is always 1 so the db table defaults it to that).

'status' => $entity->status,

Edit: You may be wondering "What about delete??", this seems to be taken care of by  apachesolr_entity_delete, I'm going to see why  apachesolr_entity_update and  apachesolr_entity_insert didn't take care of my entities. However this answer is still valid.


admin/config page taking around 30 seconds to load; the rest of the website loads fast I have a new Drupal install and it works allright, everything loads fast, except for the Configuration page at admin/config. What I have done so far to try to tackle the problem:
- Disabled all contrib modules, with no success.
- Disabled the Update Manager module, no success either.
- Enabled Devel and extended query logs, besides page execution time: ordinary pages take some 300 ms to load. The admin/config page is taking around 30000 ms to load. There is no evidence in the logs that it has to do with the database queries. On the Config page, none of them is above the threshold limit.

It then occurred to me trying something else: I am inside a corporate network and there are two different ways to enter this Drupal site: by checking the internal IP false address and by checking the external IP address the IT team has set for this server (open to the world).

I found that by navigating to the Configuration page from the internal IP address, there is no delay at all, the page loads fast! By navigating into it from the external IP address, the page gets these 30 seconds delays to load.

Any ideas on how I should try to fix this issue with the IT team? I have access to the server and I can run commands on the command line and maybe check server logs. I am not a Linux specialist, but I can follow instructions and run commands.

The admin/config page can trigger a check of the site 'status report' which depending on the modules & services your site uses may check for the ability to connect to certain services. 30 seconds sounds like it is trying to use some service but throws a timeout after 30 seconds. Try checking the status report under working / not-working conditions to see if some services are being blocked.


How to build an install profile progmatically I need to create an install profile from an existing site. My question is what to do with the site configurations? The site is pretty complex, so putting them manually in the profile is out of the question.

My current best idea is to create features from the site, and revert them during the install, but it has a big drawback: If I have to modify something on a site that is installed this way, the state of the features will be "overridden", so they need to be ignored or recreated.

I've checked out some possible solutions, but none of them seemed to be perfect.

Ftools can "detach" features, but only for a few types of settings.
Profiler seems to be exactly what I need, but it also lacks of support for most of the settings.
With Features Override I can override the install profile's own features, but is it a good practice? I'm afraid it could cause problems when the complexity increases.
I've heard about Ctools Export Bonus, but only 600 people downloaded it yet. Is it safe to use?

So wich is the best (or the least worst) solution currently, with drupal 7?

The questions you are asking are pretty hard to crack. We have build Kraftwagen which is a Drush extension and a bunch of Drupal modules that will fit your needs.

Please have a look and let us know if it worked for you.


How to test for Entity Type In Drupal you can use the following in template.php to test for a node type:

function THEMENAME_preprocess_node(&$variables) {
  if ($variables['type'] == 'INSERT TYPE HERE') {
    // include code
  }
}

How do you test for an entity that is attached to a node?

The fully loaded node object should be available as a variable.  You then need to know the field name that it is attached as (ie, the machine name from the manage fields tab on the content type).  Once you have that, you should be able to use field_get_items() to check for actual values on that field

function THEMENAME_preprocess_node(&$variables) {
  $node = $variables['node'];

  if (field_get_items('node', $node, 'field_foo') !== FALSE) {
    // do something
  }
}

Just note that this checks for an actual value in the field, not that the field is on the particular content type.  For that, you need to use field_info_instances().

function THEMENAME_preprocess_node(&$variables) {
  $node = $variables['node'];
  $fields_info = field_info_instances('node', $node->type);

  if (isset($fields_info['field_foo']) {
    // do something
  }
}


Automatic Node Expire / Unpublish with Renew Option I have a classifieds site and would like to have a node expire after 45 days (unpublished), no matter how many times the user edits and saves the node. However after the node expires, the user has the ability to renew (publish) for another 45 days. I would like the time to be strictly 45 days with simple a renew button when it is expired.

Here is the workflow:

User creates node
Email is sent to node author indicating successful post.
Node is automatically expired 45 days later.
Email is sent to node author indicating expired post.
User has the ability to easily renew ad (expiry date is 45 days later yet again)
Email is sent to node author indicating renewed post (different from step 2)

I would also like to have a countdown for the days remaining until the expiry date.

I have successfully built steps 1-4 using rules only, however the rules are based on the event 'After saving new content', which means when a node is republished/renewed the rules do not follow because it is not new content.

I have also tried using the Scheduler module to set the unpublish date but cannot figure out how to enable renew only after it has expired.

I have also tried Auto Expire but I think it only gives the ability to renew before it expires, not after.

I would have opted for a custom code solution with the above work-flow.As an alternate contrib module option classified Ads module can be potential option.

Module Features:

  Renewable expired ads during the 'grace period' Simple taxonomy-based
  browsing Ad expiration depending on category selection Per-user
  classified ads lists – custom lists totally sortable Length-limited
  body text with live counter of characters Advanced Help, CCK, Context,
  Panels, Token and Views support


Lead Capture Popup in Drupal I'm looking for a solution to implement a lead capture lightbox popup form in Drupal 7. Is there module that would do this? Basically if a user is on a page after a certain amount of time (~10 or 15 seconds), a lightbox popup would go over the page they are looking at and ask them for their email.

The module allows to display a popup once after a certain delay on a
  page load. This fills a gap in popup modules family (Popups, Popup),
  which are designed to show popups only after a click on an HTML
  element, or to implement a complex behavior like modal dialog forms.

You can specify paths on which you need to display the popup without appropriate delay


Number of calls of hook_node_access I use hook_node_access() to redirect users, if they don't have the right attributes to see a specific node.

While programming I used dpm() to check some variables and was wondering, that dpm() is called 9 times although I just opened a single node.

Well, my question is:
Is it normal, that hook_node_access is called several times for one node, so I should use drupal_static() to avoid duplicate calculations or do I have some disadvantageous loops in my code that I should detect and remove (in hook_node_access are no loops, I mean somewhere else)?

I would welcome every advise!

Thanks, Daniel

Next time I should look into the docs first...

According to node_access(), it doesn't consider the returned value NODE_ACCESS_IGNORE, which I return, if the user doesn't violate my permissions, so that other modules still can deny access, if their permissions might be violated.

So the answer of my question is: I should use drupal_static() to avoid duplicate calculations.


How to add custom css file by code? Well I know that I have to use drupal_add_css like described here.

But that doesn't work and I don't understand why.

I tried to use this hooks: function hook_init, hook_views_pre_render, hook_preprocess_html and hook_preprocess_page.

I tried in that hooks this code:

$css=drupal_add_css(drupal_get_path('module', 'mymodule') . '/style.css');
$variables['styles'] = drupal_get_css($css);

or:

drupal_add_css(drupal_get_path('module', 'mymodule') . '/style.css');
$variables['styles'] = drupal_get_css();

or also just the first line.

also:

drupal_add_css("/".drupal_get_path('module', 'mymodule') . '/style.css');

or that:

drupal_add_css(drupal_get_path('module', 'mymodule') . '/style.css',
               array('group' => CSS_DEFAULT, 'every_page' => TRUE));

Here is my style.css:

#logo {
    display:none;
}

That should hide the logo on success. What is wrong with my tries?

in hook_init, removing the first slash should solve the problem. If not, check for permissions.

drupal_add_css("/".drupal_get_path('module', 'mymodule') . '/style.css');

Should be

drupal_add_css(drupal_get_path('module', 'mymodule') . '/style.css');


Cannot access the site after changing admin password I have drupal 7 site hosted on bluehost.

After I changed the admin password, I got an error. I then tried to access the site, and I was able to do that, but it was very slow.

Now, I can't access the site as an administrator. It becomes even more weird: If I delete all history and cookies from the server, I can access the site; I can also login as an authenticated user.

When I try to log in as administrator, I get a white page or a "500 internal server" error. (It depends on the browser; I tried Chrome, FF and IE.) After I do that, I cannot access the site even as guest or authenticated user; only when I delete all the history and cookies, I can access the site as guest or authenticated user.

How can I fix this?

This is the error log the bluehost Representative gave me:

  [15-Apr-2014 14:48:49 Europe/Helsinki] PHP Fatal error:  Call to undefined function intel_path_filter_type_to_arg() in /public_html/includes/menu.inc on line 814

Is it possiable this module has something to do with the issue? https://drupal.org/project/intel

I think I disable the google analytic api module. Maybe the problem is related to one of the Drupal SEO modules?

I am really not sure, and cannot connect my site..

Yesterday the site worked great!
Restoring the site to yesterdays backup did not help - this is the weirdest thing!

The problem was related to one of the two below (or both):

The error from the intel module
The session cache / cache

Currently the site is live and working great, but the Intel module is active currently  and I don't know if to disable it or not.

The second thing we did (me and the nice guy that helped me) is to clear the cache and sessions cahce  - which was problematic for me since I did not had access as admin. We used update.php after allowing every user to access it on the setting.php file (changed false to true), and clear the cache through the mysql query on the 'my php admin'.

Here are the steps:

enter my php admin
choose database
go to mysql tab
on the query:
UPDATE system SET status='0' WHERE name='intel';
then need to flash the cache - run the query:

TRUNCATE TABLE sessions;
TRUNCATE TABLE cache;
TRUNCATE TABLE cache_bootstrap;
TRUNCATE TABLE cache_block;
TRUNCATE TABLE cache_field;
TRUNCATE TABLE cache_form;
TRUNCATE TABLE cache_image;
TRUNCATE TABLE cache_menu;
TRUNCATE TABLE cache_page;
TRUNCATE TABLE cache_path;
TRUNCATE TABLE cache_update;
TRUNCATE TABLE cache_views;

I will be happy to get feedback on this solution. The site is currently working - so problem solved.
But, I don't know if I still can't disable the intel module and if I can change the admin password. I don't want to cause the problem again.


Paypal express checkout doesn't add taxes I am creating a site where they only want to use paypal express checkout (using drupal 7 /Ubercart 3.1). The problem is that it doesn't display the taxes when processing the order.
I know it doesn't have the address info when it goes to the express checkout but when it comes back, it adds the shipping price but no taxes.
Is there a way to add the taxes in?

I have been through all the options and don't see anything related to this.

I have also tried modifying inside the paypal module itself:

In the function uc_paypal_ec_review_form_submit I see that they add the shipping info if it is not there but when I try to add taxes the same way, the tax functions don't work.

I do see the line "subtotal excluding taxes" which I believe is being generated by the taxes module but no tax is actually applied.

If I use the paypal standard checkout, the tax is applied once the address info is filled in.

Any help would be appreciated.

It seems that Ubercart doesn't set the billing address properly after making the API call. See uc_paypal.pages.inc around line 240.

The original snippet looked like this:

$order->delivery_street1 = check_plain($nvp_response['SHIPTOSTREET']);
$order->delivery_street2 = isset($nvp_response['SHIPTOSTREET2']) ? check_plain($nvp_response['SHIPTOSTREET2']) : '';
$order->delivery_city = check_plain($nvp_response['SHIPTOCITY']);
$order->delivery_zone = !empty($zone_id) ? $zone_id : 0;
$order->delivery_postal_code = check_plain($nvp_response['SHIPTOZIP']);
$order->delivery_country = !empty($country_id) ? $country_id : 840;

$order->billing_first_name = check_plain($nvp_response['FIRSTNAME']);
$order->billing_last_name = check_plain($nvp_response['LASTNAME']);
$order->billing_street1 = check_plain($nvp_response['EMAIL']);

You can see that the billing address is never added. I would assume that most people who experience this issue have the tax calculating by the user's state. Since there's no state, no tax is added. Since the billing address and delivery address will be the same on Paypal, simply add the delivery info into the billing info like so:

$order->billing_street1 = check_plain($nvp_response['SHIPTOSTREET']);
$order->billing_street2 = isset($nvp_response['SHIPTOSTREET2']) ? check_plain($nvp_response['SHIPTOSTREET2']) : '';
$order->billing_city = check_plain($nvp_response['SHIPTOCITY']);
$order->billing_zone = !empty($zone_id) ? $zone_id : 0;
$order->billing_postal_code = check_plain($nvp_response['SHIPTOZIP']);
$order->billing_country = !empty($country_id) ? $country_id : 840;

Hacking core/contrib modules like this sucks and I don't recommend it, but sometimes, you gotta do what you gotta do.

Enjoy your taxes!


Drupal 7 Calendar - How do you disable the number link to the day page? How would you disable the links to the daily page on a calendar page view?

That functionality is automatic and means that you have month- and day-type calendar views defined.

If you don't want to use the daily display on your site, just find the calendar view that defines the daily display and disable that display or view.

That'll automatically disable the functionality of displaying a daily calendar on your monthly view.

Here's a step-by-step:
Look in the calendar view's format settings

If the calendar type is 'Day', then that's the one that's automatically being linked to your month's date number, just disable that view or display:

Hope this helps!


Error in drupal "Notice: Undefined index: extension in require()..." I am seeing this error on my page

  Notice: Undefined index: extension in require() (line 207 of
  /home/....../public_html/includes/filetransfer/sftp.inc).

I have no idea from where. I tried doing search but I did not see any help.
Could you please guide why this message is poping up on all the pages.

There is not an sftp.inc in the filetransfer folder in Drupal core by default. Perhaps more information on your contributed modules in use, a custom module, Drupal version, etc. might help...


Get vocabulary name from vid function I am trying to extract the vocabulary's name from it's vid. Is there a function that does that or do I have to create it?

You can load the vocabulary object using taxonomy_vocabulary_load() and get the name that way:

$vid = 1; // Vocabulary ID
$vocab = taxonomy_vocabulary_load($vid);
$vocab_name = $vocab->name;


Rendering a form element without drupal_get_form? I'm trying to render a simple form element without the accompanying  tags and other drupal goodness (validation, etc). Is it possible to render a form element using form api methodology but without running it through drupal_get_form?

You can embed a for in a template file for instance with drupal_render_form() in D6 or drupal_render_children() in D7. See this community issue.

You will still have to get the FAPI array somehow, you usually still use drupal_get_form() for getting the $form array.


Save Node Title By database query I am trying to update a node title by database query as

 $num_updated = db_update('node') // Table name no longer needs {}
  ->fields(array(
    'title' => "custom_title",
    'status' => 1,
  ))
  ->condition('nid', $nid, '=')
  ->execute();

The above code is updating the node title in node table, but on node display I am not seeing the updated title.

The reason I am not using node_save() to update node title is to by pass auto entity label functionality for updating node title.

You also need to update the node_revision table. You either need to create a new revision for that node or update the latest one.


Views Summarize Won't Sum when field is output as link (D7) I'm using Views Summarize module for one of my views. I need to output the field as link and sum them up, but the total is displayed as $0.
When I uncheck the output the field as link option, the total is displayed correctly.

http://i.stack.imgur.com/SNK0h.png

Anyone has a solution for this?

Have you seen this issue on drupal.org: http://drupal.org/node/1880450?

It looks like this is actually a bug in the module - not anything you're doing wrong.  However, there seems to be a user-submitted patch that fixes issues with decimals, currency, etc that you can try out...


How to set or get the triggering element upon submit a form using JQuery? I have a Drupal 8 form with checkboxes.
The form submits upon clicking on a checkbox using JQuery.

Here is my code.

 $('#edit-event-types input[type=checkbox]').on('change', function(event, ui){
    $('#events-to-doc').submit();
  })

Unfortunately, if there isn't any submit button in the form, then function submitForm in the form class doesn't execute. But I don't need in a submit button on the form, I want to submit the form clicking on the checkboxes.

Can I somehow set the checkboxes element as the triggering element with Jquery? I need the function submitForm to execute and $form_state->getTriggeringElement() return the checkboxes as the triggering element.

Submit buttons (and their names) are special for Drupal. I'm not sure how this changed in D8, but in D7, the submit button name was used (IIRC) to determine which one was clicked.

I would suggest adding the submit button, hiding it with CSS and triggering a .click() to the button instead of doing .submit() directly. You can then either get the checkbox value if that's enough, or use a hidden field and some JS to determine which checkbox triggered the submit event (last clicked checkbox).


How to get a two layer sort with a taxonomy term relationship and avoid duplicates in a user view I have a user view, that needs to list users, sorted by the weight of an taxonomy term associated with the user via an entity reference field and added as a relationship in the view.  Once I've sorted by term weight, I next need to sort by the family name field of the user.  As soon as I add the second sort I start getting duplicates.  How can I accomplish the sort I need without the duplicates?

Turning on aggregation and grouping by the sort AND adding distinct to the query settings works in my simplified version of the view, but once I add in the other things the view won't load with aggregation on.

Update: I thought I had it simplified as far as it could go, but it turns out the relationship has nothing to do with it.  I get duplicates just be adding a sort of family name.  Curiouser and curiouser.

You need to add a filter that restricts family name to one language.

Credit: @ratface, answering this Q as per What should I do when an answer has been added as comment?


How can I serve individual static text files with the same name from the webroot for each multisite instance? I use Drupal 8 and I want serve statics files in each multiple sites with Nginx.

I've a site at web/sites/site_1/ and a site at web/sites/site_2/.

I want serve ads.txt or robots.txt for each sites with different content.

I can add directory in site_1/statics/ with files and serve this files at root with Nginx but I don't know how I can to do this.

Is it possible to do this with Nginx? Or is there some other way?

It maybe is possible with Nginx but Nginx config is off-topic. Please have a look at the RobotsTxt module instead. The RobotsTxt module simply provides you a /robots.txt route that behaves just like a normal robots.txt file with the difference that you can configure the content of it from the back-end per site. You only need to pay attention that you deleted the physical robots.txt file to let the RobotsTxt module do its work.

  Use this module when you are running multiple Drupal sites from a
  single code base (multisite) and you need a different robots.txt file
  for each one. This module generates the robots.txt file dynamically
  and gives you the chance to edit it, on a per-site basis, from the web
  UI.

  Note: You must delete or rename the robots.txt file in the root of your Drupal installation for this module to display its own robots.txt
  file(s).

This solves your robots.txt problem. The ads.txt needs to be solved the same way. You need to create a custom module that does just the same as the RobotsTxt module for the /ads.txt route. With an admin settings form to store its content.


Commerce Price Field formatting I'm using a view which is rendering the Product displays as DisplaySuite modes.

Right Now, the generated code for the price looks as follows.

HK$100.00/Month

In order to achieve a similar rendering as

I need to split the decimal part and the currency into their own markup.

Any idea about how to do that in a clean fashion ?

I have found a working solution for that, even if there might be a more clean solution, at least it works.

In the template.php file of my theme in use I put the function :

  function MYTHEME_preprocess_field(&$vars) {
  if($vars['element']['#field_name'] == 'commerce_price') {
    // dpm($vars);
    $price = $vars['element'][0]['#markup'];
    $parts = explode(".",$price);
    $parts[0] = str_replace('HK$', '',$parts[0]);
    $markup = 'HK$'.$parts[0].'.'.$parts[1].'';
    $vars['items'][0]['#markup'] = $markup;
  }
}

Once this saved, a markup on which it is possible to act is generated.
The "per month" par is supplied by a field suffix using Display Suite.
The rest is some easy CSS to style the output.

Another method is possible. At uncommenting the dpm($vars) line in the code above, some candidate template files names for the field are provided.


Using Realnames in other places In Drupal Commons, we're using the Realnames module. Is there a way to extend this module's information to other search box fields?

For example in the Organic Groups invite (/og/users/??/invite), could my users search for other users by the user's first or last name? That is, in the form og_invite_link_invite_page_form's first field (edit-invitees), how could I search on an individual's Given Name (first name) or Family Name (last name)?

This addition provided what I needed. Basically, I needed to override the $form['invitees'] by using and slighly modifying og_username_helper.module ( http://drupal.org/project/og_username_helper ).

 74     if ($form['#id'] == 'og-invite-link-invite-page-form') {
 75       // print 'in';
 76       // print_r($form['invitees']);
 77
 78       $form['invitees'] = array(
 79           '#type' => 'textfield',
 80           '#description' => t('Lookup a username and add it to the list below.'),
 81           '#autocomplete_path' => 'og/username_helper/autocomplete',
 82           '#size' => 40,
 83           '#maxlength' => 60,
 84           '#weight' => -2,
 85           '#access' => $helper_access,
 86           );
 87
 88       return $form;
 89     }
 90

I've packaged this up into a module to extend the og_username_helper.

 58 /**
 59  * Extends og_username_helper to Groups Invite Members tab
 60  */
 61 function soc_searchtweak_form_alter(&$form, $form_state, $form_id) {
 62
 63   $form_changes = array();
 64   $form_changes['og-invite-link-invite-page-form']='invitees';
 65   $form_changes['commons-profile-friend-search-form']='search_text';
 66
 67
 68   foreach ($form_changes as $form_id=>$field_id) {
 69
 70
 71     if ($form['#id'] == $form_id) {
 72       $form[$field_id] = array(
 73           '#type' => 'textfield',
 74           '#description' => t('Lookup a username and add it to the list below.'),
 75           '#autocomplete_path' => 'og/username_helper/autocomplete',
 76           '#size' => 40,
 77           '#maxlength' => 60,
 78           '#weight' => -2,
 79           '#access' => $helper_access,
 80           );
 81
 82       return $form;
 83     }
 84
 85   }
 86
 87
 88 }

The module.info file puts og_username_helper as a dependency.

1 name = Search Tweak
2 description = Extends og_uesrname_helper in various places
3 core = 6.x
4
5
6 dependencies[] = og_username_helper


add js by #attached - hook_page_alter in theme's template.php I am trying to add js by #attached, as I understand it's better from a caching perspective then drupal_add_js(). I try to use hook_page_alter() in template.php.
I have the following code:

function mytheme_page_alter(&$page) {
 $theme_path = drupal_get_path('theme', 'mytheme' );

  if (!isset($page['content']['#attached']))
    {
      $page['content']['#attached'] = array
      (
        'js' => array(),
      );
    }

  $page['content']['#attached']['js'][] = array($theme_path . '/test.js');
}

(this is adapted from http://www.jaypan.com/tutorial/including-javascript-or-css-files-every-page-load-module-drupal-7, I first tried to attach [#attached] directly to $page by means of  $page['#attached'] = array... , but as I faced the problem described below I tried to test some code suggested by other people).

The problem is that the elements of the js are not properly set. After the 'js' => array(), The Aptana Debugger shows what I'd expect :

After $page['content']['#attached']['js'][] = array($theme_path . '/test.js'); , however, the array values are not set:

Still the value of array($theme_path . '/test.js')is what it 'should' be:

It's as if the ascription did not go through.
What did I do wrong?

I think your problem is you're trying to use a hook from a theme template.php? (Assuming because you have mytheme_page_alter as your function name for hook_page_alter). If you're not getting the JS included, it's specifically because you can't use hooks in template.php files. You need to create a new module.


How to programmatically add menu for content type? E.g. article has main menu as default, I want to add (and remove) second menu as available to article content type in my unit tests, how can I do it?

In hook_menu and set 'access callback' to custom function and then:

$node->type == 'my_node_type'

and/or user type that can access this node...


How can I label content in views as "new"? I use a panel with views on the home page of my drupal site (workaround.org). But I would like to put a "new" label in front of any article that was created or edited in the past 2 weeks. The view field "Node: has new content" did not help me because it will flag any content as "new" for anonymous users. Instead I just want to show anonymous users what content has been added recently.

I have some suggestions, ranked below sort of from simple to complex.

You can simply add a static text field to the view, write "New" in the text field, and then filter the view to contain only content from the period you want to have the "New" label on them.
If you want the same list to also display more content, create an attachment display in the same view, override the text field and the date filter, and set the display to attach after the first one.
Use the Theme information in the view to directly override the views output. Find the content id in the template, load the node, and check the creation date.
Render the content through a view mode instead of on a field by field basis. In the the node-template, you can now check the creation date of the node and output the label. This solution would possibly benefit from an added 'per-view-mode' theme suggestion.


Modify field in node drupal 7 I have field "myfield" in a node. The field is created in the content, not by hook. I want to change the value of that field. I do not want to display the value from database, but my value let's say random number. I tried to do this with hook_node_view and with hook_entity_view but I cannot change it on the display. Here is my code:

function mymodule_node_view($node, $view_mode) {
  if ($node->type == 'my_node_type') {
    if ($node->nid == 46) {
      $node->myfield['und'][0]['value'] = 55;
//or I tried with $node->content and no success
    }
  }
}

What am I missing? Can you help me, please!
Thanks you in advance!

You can use this line instead:

$node->content['myfield'][0]['#markup'] = '55';


How do I add a class to the HTML "body" tag programmatically? I would like to add a custom CSS class to  the <body> tag. I am using Drupal 7/Corolla.

How can I do it programmatically from my custom module?

The preprocess functions can be implemented from modules, and themes.

The preprocess function that you need is hook_preprocess_html() and the variable to set is $variables['classes_array'], which is an array containing all the classes set for the  element.   The content of the html.tpl.php file that is used by default by Drupal (if the theme doesn't use a different template file) is the following one:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
  "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language; ?>" version="XHTML+RDFa 1.0" dir="<?php print $language->dir; ?>"<?php print $rdf_namespaces; ?>>

<head profile="<?php print $grddl_profile; ?>">
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>

<body class="<?php print $classes; ?>" <?php print $attributes;?>>

    <?php print t('Skip to main content'); ?>

  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>

In your module you just implement the preprocess function as follows:

function mymodule_preprocess_html(&$variables) {
  $variables['classes_array'][] = "new-class";
}

template_process() then uses $variables['classes_array'] to populate $variables['classes'] with the following code:

$variables['classes'] = implode(' ', $variables['classes_array']);

Using a preprocess function in a module is preferable if your site uses more than one theme, or if the theme set for your site is not the one you created. In this case, you are able to set your custom CSS classes, and not lose them when updating the theme, or simply changing the default theme used by your site.  If your site uses just a theme, and that theme is a custom theme you created, then you can implement the preprocess function in your custom theme. As you maintain the theme, the CSS classes are not lost when updating your theme.


Where does drupal determine which theme file to use for an entity field? So I've got this problem where file_entity is ignoring the configured video formatter despite triple-checking the GUI configuration. Instead it's being rendered by theme_file_entity_file_video(), which shouldn't be happening.

But it is. So I'm digging back into core to see where the theme function responsible was established. I'm in drupal_render but I'm already seeing the theme function set improperly...

So my question: Where does drupal determine which theme file/function to use for an entity field?

Clarification: my question is, "How/where does the theme registry get built for an entity?" I want to watch it get built with a debugger.

Everything can be overridden by one hook in any module so bear that in mind.

The theme registry is where everything is stored in terms of theming for pages/entities. It all depends on the order here in determining the theme it will use.

You can use the devel module and dpm out the theme registry:

https://api.drupal.org/api/drupal/includes%21theme.inc/function/theme_get_registry/7

It usually is built in this order:

module where entity is created
module where function was called to get the entity
your theme directory

but at any point that could have been overridden


Views & custom exposed filters : where do I start? I've got this module which makes an additional field available when you base the view on Users. The field is made available through hook_views_data().

I've created a filter for this field, and it should be exposed to users. However, what I would really like to do is to create a custom filter. That is, a very custom form with some specialised options which the user can choose between.

How do I go about doing this?  How do I tell Views that I've got this custom exposed filter. I know hook_views_plugins has something to do with this, but I can't find any place which describes the general picture of how things interact. Does anyone have any experience with this; and how things work together and which pieces I need to solve the "puzzle"?

Any input appreciated!

I guess the best place to start is to look at the way some other module is doing it. Or how views itself does it for some core module :) (i.e. taxonomy or user.
There is at least 3 things you have to do :

tell views you have something for it
provide it :)
tell drupal to load it

the telling can be done by implementing :

hook_views_data in case you define an entire field, or
hook_field_views_data_views_data_alter (no doc if i get it right) if you want to change someone elses field filtering

create a directory views, place a file called your_module.views.inc in it and put the hooks there.

then create a file with a class that will extend the filter

and include that file in the modules info file

dont forget to refresh cache and that should be it :)


Setting up Content Synchronization module Blanca.Esqueda,
I'm interested in using your Content Synchronization but am having a little bit of problem getting it to run. I'm using Drupal 8 on Acquia Devdesktop, running Content Synchronization 8.x-2.0 using PHP version 7.1.12. The installation instructions is a bit cryptic to me (see image below).

Where do you put this in settings.php? I just appended it to the last lines. But then where is ../content/sync pointing to (see image below)?

After all that I'm getting:
An AJAX HTTP error occurred.
HTTP Result Code: 500
Debugging information follows.
Path: /batch?id=17&op=do_nojs&op=do
StatusText: 500 Service unavailable (with message)
ResponseText: The website encountered an unexpected error. Please try again later.
I would love to use the Content Synchronization module. Can you give me a hand on this?
Thank you very much for your help,
Kai

$app_root is the top directory of your website. The one where your index.php is located.

Therfore the ../content/sync is a location like this:

- content
    - sync
- public_html
    - index.php
    - (all the Drupal 8 files)

To add to that — this is probably done out of security reasons. Not to store your data from DB with the code. Same reasoning was followed for the Config Management core module.

And lastly - you have to make sure there is such a location on your server. Locate index.php, go one directory up and locate or create the content/sync path and try again.


Is there a way to find out how many registered users logged in a given time period? I am working on KPIs for my site and there are a few numbers I want to track. One of them is how many registered users actually logged in every month. Is there a way to get this number?

You could count all User table rows in the database where the fields for "Last Access" and or "Last Login" are newer than one month old .  You'd need to compare those timestamps to a timestamp for the start of the current month. You can find that with something like this or maybe it's as simple as:

$this_month_start = strtotime("-1 month");


DatePicker is not working Datepicker is not working. This code working with Drupal 6, but not with Drupal 7.

drupal_add_js(drupal_get_path('module', 'PROPERTY') .'/jquery/jquery-1.4.1.js', 'module');
drupal_add_js(drupal_get_path('module', 'PROPERTY') .'/jquery/jquery.min.js', 'module');
drupal_add_js(drupal_get_path('module', 'PROPERTY') .'/jquery/jquery-ui.min.js', 'module');
drupal_add_js(drupal_get_path('module', 'PROPERTY') .'/jquery/datepicker.js', 'module');
drupal_add_js(drupal_get_path('module', 'PROPERTY') .'/jquery/ztfb_datepicker.js', 'module');
drupal_add_css(drupal_get_path('module', 'PROPERTY') .'/jquery/ui.all.css', 'module');

drupal_add_js(drupal_get_path('module', 'PROPERTY') .'/jquery/scrollJump.js', 'module');

$(document).ready(function() {
  $("#startdate").datepicker({
    dateFormat:'dd-mm-yy',
    autosize:false,
    changeYear:true,
    changeMonth:true
  });
});

I include the file in PROPERTY_Form.admin.inc file.

require_once("D://wamp/www/propertysite/cron/includes/jquerydatepicker.php");

function PROPERTY_Form() {
  global $user;
  $form = array();

  $form['PROPERTY_Form']['startSyncFrom'] = array(
    '#type' => 'textfield',
    '#prefix'=>'
',
    '#suffix'=>'
',
    '#id'=>'startdate',
    '#default_value'=>date('d-m-Y'),
    '#description' => '(You can select any past date to ensure even your old Data gets synced)',
    '#attributes'=>array('tabindex'=>9,'style'=>'width:70px;'),
  );

  return $form;
}

You do not have to include all of that jquery libraries: Drupal core has that libraries. You can just include any jquery.ui library with drupal_add_library('system', 'ui.datepicker') or another library which you want to include. Then, in your JavaScript file, you can write something like this.

(function ($) {
  Drupal.behaviors.custom_js = {
    attach: function(context) {
      $('#YOURID input[type="text"]').datepicker({
        showOn: "button",
        buttonImage: Drupal.settings.basePath + "sites/all/themes/YOURTHEME/images/calendar.png",
        dateFormat: "dd-mm-yy",
        showAnim: "slideDown",
        buttonImageOnly: true
      });
    }
  };
})(jQuery);

If you want to use the datepicker with the form API, you have to change the type element to 'date_popup'.


Views: Show either field a or field b I'm trying to find a way to get a view to display either field_a or field_b.
For example I have to different image fields that are being rendered differently on the full  node display, both of which are optional. Now I'd like to be able to show one of those pictures in my list view, either picture 1, or, if that's not present, picture 2, but never both.

Is there any smarter way to achieve this than to put the logic into a views fields template?

put the logic into a views fields template

If it's a "one-off", most of the time, that's the way I would have gone about it. Display the "primary" field, exclude the seconday. Template the primary to display the second as necessary.

At a recent project, I "was just going to do this once", but then the client started changing their mind, and now I have a really big mess of views templates. If I knew that I would have a lot of logic like this, I would use a Views Context display instead, pull that into Panels, and have the Page manager handle the display logic instead. More complicated, but also neater IMO, and easier to maintain, as the logic becomes independent of the presentation.


create category and subcategory menu on the left sidebar I need a category, subcategory and subbactegory based solution for
  example

Project
    Web project
        Project 1
        Project 2
    Desktop project
        Project 1
        Project 2

Project 1 (when i click this then content appear on right side)
Project 2 (when i click this then content appear on right side)

  Basically, when i click on the li page wouldn't be refresh. 1) i click
  on web project then menu expanded Project 1, project 2 appear and if i
  click on project 1 then content related to project 1 appear on the
  right side. Similarly for Project 2 and the subcategory for desktop
  project will be same means i can create subcategory related to desktop
  project.. Like in any category and product relation we need to select
  the category and add the product detail similarly in this

Views Tree would be worth trying.
Toggling of leaf terms can be handled by javascript.
To show content, you can declare ajaxified menu callbacks, which simply takes tid as argument and replace a certain section of DOM with the server reponse.


How do you theme a Quiz Question? I have a True/False Quiz module question that I want to theme the output on...basically wrap the question with some extra stuff. I grabbed the truefalse-answering-form.tpl.php file from the module folder, copied it to my theme folder and made the needed changes, but my overriden theme file isn't being loaded.

I cleared the caches and still no luck.

Devel Themer isn't really providing me with useful info either...

Has anyone successfully themed a Quiz Module Question? Is there something extra that needs to be done?


Tabs within a content type I have a question about tabs. I'm using a content type hotel with all the information about a hotel for example, hotel residence, location, food, spa, sports ... At this moment this is just one big list of text. I was trying to make tabs for it because this is I think the solution. I was trying it with the module quick tabs but there I have to use nodes or views to make the tabs so i don't know what to do know because it's impossible to put every element (location, food,...) from every hotel (40) in a view.
Do you guys have any ideas?
Thanks for your help.

Sounds like you want to use the Field Group module.

This module allows you to group a number of fields on a content type together. You can then choose from a number of different display options for that group, including tabs.


How to provide pagename.tpl.php to specific page? I have basic knowledge of Drupal ,I know that if I am giving page name with .tpl.php file taht directly apply to that specific page .but to apply that I don't know so can you please help me ?

copy this code to template.php (donot forget to change the yourtheme name)

function yourtheme_preprocess_page(&$vars) {
  // Do we have a node?
  if (isset($vars['node'])) {

    // Ref suggestions cuz it's stupid long.
    $suggests = &$vars['theme_hook_suggestions'];

    // Get path arguments.
    $args = arg();
    // Remove first argument of "node".
    unset($args[0]);

    // Set type.
    $type = "page__type_{$vars['node']->type}";

    // Bring it all together.
    $suggests = array_merge(
      $suggests,
      array($type),
      theme_get_suggestions($args, $type)
    );

    // if the url is: 'http://domain.com/node/123/edit'
    // and node type is 'blog'..
    //
    // This will be the suggestions:
    //
    // - page__node
    // - page__node__%
    // - page__node__123
    // - page__node__edit
    // - page__type_blog
    // - page__type_blog__%
    // - page__type_blog__123
    // - page__type_blog__edit
    //
    // Which connects to these templates:
    //
    // - page--node.tpl.php
    // - page--node--%.tpl.php
    // - page--node--123.tpl.php
    // - page--node--edit.tpl.php
    // - page--type-blog.tpl.php          << this is what you want.
    // - page--type-blog--%.tpl.php
    // - page--type-blog--123.tpl.php
    // - page--type-blog--edit.tpl.php
    //
    // Latter items take precedence.
  }
}

all examples are inside the comment which format you should follow in side the template folder for creating tpl.php '%' is use for all, best of luck,
note : don't forget to clear the cache
you can use devel_themer module for specific suggestions of tpl's.


how to print 'add term' taxonomy form into block I have a taxonomy vocabulary named "jenis dokumen". I want to let anonymous users add terms within this vocabulary. I'm trying to add a block and render that form to add new term using PHP filter, but it's failing.

This is my code:

include_once(drupal_get_path('module','taxonomy') . '/taxonomy.admin.inc' );
return drupal_render(drupal_get_form('taxonomy_form_term', jenis_dokumen));

Can anyone help?

now i have success with this.

$vocabulary = taxonomy_vocabulary_load(2, FALSE);
module_load_include('inc', 'taxonomy', 'taxonomy.admin');
return drupal_render(drupal_get_form('taxonomy_form_term', $vocabulary));

but, there is a default value in field name 'Jenis Dokumen'
how can i get blank (no value) in field?

A couple things:

The function taxonomy_form_term() expects the $vocabulary parameter to be an object with a "machine_name" property
You should wrap the vocab name in quotes
More elegant to use module_load_include() instead of include_once()

So:

if ($vocabulary = taxonomy_vocabulary_machine_name_load('jenis_dokumen')) {
  module_load_include('inc', 'taxonomy', 'taxonomy.admin');
  $edit = array();
  $taxonomy_form = drupal_get_form('taxonomy_form_term', $edit ,$vocabulary);
  return drupal_render($taxonomy_form);
}


Send mail to product owner with Rules I have a Drupal 7 site running including Commerce. I'm asked to make the webshop work in a way that the mail send after completing payment is send to the product owner(s).

So when creating a product via /admin/commerce/products/add the admin fills in the email address of the product owner/seller in a custom field called field_seller_mail.

When the visitor of the website pays its order, the site should send one or more mails to the owner(s) of the products zo that they can handle the delivery of the products.

In rules I choose the when payed in full trigger.
Then I choose to loop in the action part and loop trough the line items, but the field field_seller_mail is nowhere to be found.

What is the best way to solve this problem?

If the data about a product are not available when processing a "line item", you can make them available. To do so, use a technique similar to what is explained in my answer to "How to access commerce_product field of line-items using Rules to flag the Commerce Product?", which includes a Rules Component that looks like so:

{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about this product: Product ID = [product-fetched:product-id], Product SKU = [product-fetched:sku], Product Title = [product-fetched:title], Product Creator = [product-fetched:creator]" } }
    ]
  }
}

Here is a blueprint of what you need to do:

Create a Rules Component, similar to the above Rules Component. Just an import of that Rules Component should be enough (to get started and further improve it as detailed below).
Rework the Drupal Message shown via the last Rules Action in the Rules Component (Starting with "Some details about this product"), e.g. by also using any of the available tokens that fit your needs.
Execute that Rules Component inside your Rules Loop of the rule in which you want to loop over all line items.
Improve the Rules Component from Step 1 by creating whatever additional Rules Action(s) you need. Make sure to place these Rules Action(s) AFTER that Rules Action (in the Rules Component) that performs "Fetch entity by ID".


How to use node title or path alias instead of node id in node reference contextual filter in views? I have node A with a node reference to node B.

In a view I show all nodes A that have particular node B referenced (nid: 123, title: node-B-title).

Instead of using the nid in the contextual filter I would like to use the node title. For example, instead of:

view-name/123

I would like to use

view-name/node-B-title

How could I do that?

I had a very similar problem and I not just found the solution to it, but also learned new things about how view works. Let me share what I learned and the solution to your problem too.

When you are creating a view with one or more contextual filters, the view must receive values of those filters from somewhere. This can be done by -

Picking the context filter value(s) from the URL

Typically you would have a page view for such purposes one that has URL of the form foo/%/bar or foo/bar/% for single contextual filter OR of the form foo/%/bar/% or foo/bar/%/% for multiple filters
In case you have multiple filters, the url value that appears first is mapped to the first filter, next to the second filter and so on.

Views allows you to tell what to do if the filter values are not available in the URL. This is typically used for block views.

You can choose from different actions and then configure the choice too.

asdfj kajsdf

Another thing views allows you is to tell what to do with the filter values if they are found in the URL as described in #1 above. Typical use cases are - Making dynamic titles based on filter values, Validating filter values etc.

When validating filter values, you can change the values too! (That is where our solution lies btw). This is very akin to the way we can change $form values in the drupal form validation callbacks.

Solution to your specific problem lies in using a very similar code in the sections pointed to by the arrows in the above image.

This link  proved out to be great help to me. Here is an excerpt from it:

$np = explode('/', drupal_get_normal_path($argument));
if (!empty($np[1])) {
  $handler->argument = $np[1];
  return TRUE;
} else {
  return FALSE;
}


How can I translate the label of a vocabulary? I load the vocabulary with taxonomy_vocabulary_load($vocabulary_id).

How can I can translate its label in the language currently used?

It will be default by the current language.

There are only two ways to get something else, unfortunately:

a) Use ConfigEntityStorage::loadOverrideFree to load a config entity without overrides, then it is in the default language of that entity, which is what language() returns.

b) You can set the current config language and then load the entity. See for example user_mail function :

  <?php
  // Get the current language and override it.
  $language_manager = \Drupal::languageManager();
  $language = $language_manager->getLanguage($desired_langcode);
  $original_language = $language_manager->getConfigOverrideLanguage();
  $language_manager->setConfigOverrideLanguage($language);

  // Do your thing here.

  // Restore the config language.
  $language_manager->setConfigOverrideLanguage($original_language);


Apache solr views, Drupal 7 I am using D7, views 3, apache solr views modules. I have created a view with 2 contextual filters for apache solr. I want to view the solr query built using my contextual filters. But the view preview is displaying the text "No query was run".

Is there any way to view the solr query at preview page?

You can use the Devel module, and enable page show devel page query.
Devel:

A suite of modules containing fun for module developers and themers.

Helper functions for Drupal developers and inquisitive admins. This module can print a summary of all database queries for each page request at the bottom of each page. The summary includes how many times each query was executed on a page (shouldn't run same query multiple times), and how long each query took (short is good - use cache for complex queries).

Also a dprint_r($array) function is provided, which pretty prints arrays. Useful during development. Similarly, a ddebug_backtrace() is offerred. See full demo.

Accelerate development of your site or module by quickly generating nodes, comments, terms, users, and more.


Any way to flag users who previously submitted a webform on revisit? My business team needs users who submitted a specific form to be flagged in order to allow them to gain access to a certain piece of content, which we've hidden behind a conditional check on whether they have the flag or not. I understand how to set up a form action to raise a flag on a given user. Unfortunately, I didn't know there was a requirement to flag users until most had already submitted the form.

I'm wondering if there's anything I can do, now that the horse is out of the barn and a number of users have already submitted the form without getting flagged, to ask users to revisit the form and, if they've already submitted it once, just:

a. get the flag raised
b. get redirected to the page with the restricted content

The table webform_submission has everything you need. The webform nid and the uid.

You could implement hook_user_login and set a flag in the current $user object if the form has been submitted. Then check for this flag where ever you need it.


Code showing on every content page I'm pretty new to Drupal but have take my company's half-baked site from the server and gotten a working instance of it in my local wamp stack working.  The only problem is that it seems on every page there is a section of code being inserted:

<?php
if ( isset($entity->field_job_id['und'][0]['safe_value'] )) {
   $job_id = $entity->field_job_id['und'][0]['safe_value'] ;
   $application_link_form = '
<form action="/careers/application" method="POST">
    <input type="hidden" name="job_id" value="' . $job_id . '" />
    <input type="submit" value="Apply online" class="job-application-link" />
</form>';
   print $application_link_form;
}
 ?>

This is showing a section of this code plus an "Apply Online" button at the top of each section of content.  It doesn't seem to matter what the content type of the content and the site which I imported all the files and db from has no such code - not even when I view source is there anything even commented out.  Hopefully this code gives you some context as to where this is ocurring - it comes immediately following this series of divs:

In any case, I cannot figure out where to find this code in order to get rid of it.  I'm not seeing any modules relating to this, etc.  And I just am baffled as to why it would start showing up after importing from a site that doesn't display this.  If anyone can think of any possibilities, please let me know!

If it's not in the source, it's in the DB. At a guess, this is code that someone entered using the PHP filter, but the PHP filter is not active so it's showing up as text.

As to where it is in the DB, there's many possibilities. I'd use brute force to search the DB in its entirety. (That's easy for me to say as I have a copy of SQLyog to hand. I'm sure there are other tools that provide this functionality, though: I think PhpMyAdmin has it.)

Addendum: looks like it's in a custom pane, so the table panels_pane is the most likely culprit. Ideally you want to find how it's getting inserted onto the page. Do you have the module Panels Everywhere enabled?


Changing group visibility needs group content to be resaved when group content visibility field is set to "Use group defaults" Drupal Commons 7.x-3.2
Organic Groups 7.x-2.1

Content type: Mygroup
Field: Group visibility - value: Public

Content type: Mypost
Field: Group - default value: Mygroup
Field: Group content visibility - default value: Use group defaults

Now when I create a group and a post based off on these content types everything is fine. As in everything is visible for all users.

Now when I change the Group visibility to Private I would except the post to not be visible anymore (because of the Use group defaults setting.

Unfortuanetely that's not working until I resave the post content. Then it will respect it's parent's settings.

This bug is mentioned in this video (around 6 min)

Does anyone know how to solve this problem?

Reason. I assume you see this behavior because all the node permissions are cached in Drupal, and only updated when (re-)saving a node or rebuilding the permissions.

Workaround. So instead of re-saving all nodes of your group individually, a faster workaround would be to go to admin/reports/status/rebuild and rebuild all permissions at once. This would probably also be the place to hook into for a real bugfix: rebuilding of the group nodes permissions, triggered when saving the group node with a different value in the "Group visibility" field.

(This answer is an educated guess, I didn't test myself so far.)

Redesign discussion. A still better solution would however be a larger rework of the OG permissions system, as discussed in Drupal issue #1122388. See esp. comment #10 there, discussing that the "Group content visibility: use group defaults" value is not that meaningful as it prohibits a use case where one wants the group itself publicly visible, but have its content default to private, and setting that via a fallback to the group setting so that later changes are simple. This scenario (publicly visible group node with private group content nodes) is supported by newer versions of Drupal Commons 7.x-3.x (using OG 7.x-2.7 here), but changing the setting only affects group content nodes added afterwards. So it's not the "fallback to group provided default" we want here, even though the "Group content visibility" field has "use group defaults" as its default value (which is not used though). That could be reported as a bug / improvement request to Drupal Commons.


hook_form_alter() to put multiple radios in a table I have a content type that has a series of multi-value select fields. That I need users to select in relation to a value pulled from another node.

The best way to present this is to have a table that looks like this:

I've got the 'bones' of a hook_form_alter, and I can almost present what I need. However, I cannot seem to get my checkboxes/radios to appear in the grid. I am this far...

My form_alter function looks like:

function hnbuilder_form_node_scheme_of_work_form_alter(&$form, FormStateInterface &$form_state, &$form_id){
/** check whether we passed a node reference into the form via ID in the url **/
if ($_GET['id']){
    $nid = $_GET['id'];
    /** if we didn't pass it in, we are editing the node **/
}else{
    $current_url = Url::fromRoute('<current>');
    $path = $current_url->getInternalPath();
    $path_args = explode('/', $path);
    $thisnid = $path_args[1];
    $thisnode = \Drupal\node\Entity\Node::load($thisnid);
    $nid = $thisnode->get('field_related_unit')->target_id;
}
/** Load the referenced node */
$node = \Drupal\node\Entity\Node::load($nid);

/** get the learning outcomes from the referenced node
    and put them into an array **/
$lo = array(
    0=>"",
    1=>"LO1 ".$node->field_lo1->value,
    2=>"LO2 ".$node->field_lo2->value,
    3=>"LO3 ".$node->field_lo3->value,
    4=>"LO4 ".$node->field_lo4->value
);

/** create table headers **//
$header = array(
    0 => 'Learning Outcome',
    1 => 'Assignment 1',
    2 => 'Assignment 2',
    3 => 'Assignment 3',
    4 => 'Assignment 4'
);

/** an array of the checkbox/radio options from our content type
    each field has 4 options
*/

$ffld = array(
    1=>$form['field_lo1_sow']['widget']['#options'],
    2=>$form['field_lo2_sow']['widget']['#options'],
    3=>$form['field_lo3_sow']['widget']['#options'],
    4=>$form['field_lo4_sow']['widget']['#options']
);

/** create a new array of options for the table
    */

$options = array(
    1=>array($lo[1],$ffld[1][1],$ffld[1][2],$ffld[1][3],$ffld[1][4]),
    2=>array($lo[2],$ffld[2][1],$ffld[2][2],$ffld[2][3],$ffld[2][4]),
    3=>array($lo[3],$ffld[3][1],$ffld[3][2],$ffld[3][3],$ffld[3][4]),
    4=>array($lo[4],$ffld[4][1],$ffld[4][2],$ffld[4][3],$ffld[4][4])
);

/** build the tableselect **/
$form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#js_select' => FALSE
    );

return $form;

}

I think I have several issues, and I'm hoping someone can help:

I'm not sure that 'tableselect' is the right thing to be using, as it seems this only supports single selection (based on the table row).
I'm unsure how to display the existing checkbox/radios as actual field items. I'm stuck getting their values.

Is there a way to achieve this? If so, I'd really appreciate some pointers.

I think you can define a wrapper element as type table. The core user permissions form does this, and I think is similar to what you're trying to build:

 $form['permissions'] = [
  '#type' => 'table',
  '#header' => [
    $this->t('Permission'),
  ],
  '#id' => 'permissions',
  '#attributes' => [
    'class' => [
      'permissions',
      'js-permissions',
    ],
  ],
  '#sticky' => TRUE,
];
foreach ($role_names as $name) {
  $form['permissions']['#header'][] = [
    'data' => $name,
    'class' => [
      'checkbox',
    ],
  ];

In your case, I think you'd define something like $form['sow'] as a '#type' => 'table' which will be a wrapper element that all the checkbox (or radios) appear under.

Then loop through your fields (these will be similar to how the user permission form loops through each permission, creating a row).

foreach ($fields as $low) {
  $form['sow'][$low]['description'] = [
    '#type' => 'item',
    '#title' => $low['title'],
    '#description' => ...,
  ];

  // Now loop through each assignment. This will be similar
  // to how the user permission form loops through each role
  // for each permission.
  foreach ($assignments as $assignment) {
    $form['sow'][$low][$assignment] = [
      '#type' => 'checkbox', // Or 'radio', depending on the need.
      // Other form element details here too.
    ];
  }

Then, for each assignment (these will behave similar to each role in the user permission form)


Language specific menu items when adding content I am building a bilingual site that's English and French.  When I add a content item in English, then go to Menu Settings, click on Provide a menu link, and click on Parent Item drop down menu, I get all the menu items English and French.   How do I get the drop down menu item to display only English menu items if my content is in English language?

My experience is that user 1 (admin) sees all menu items no matter their language setting, but i'm not sure if it's meant to be or if it's a bug.

Better have a look at the Issues of i18n and in particular at Drupal 7 & i18n: Only current language items visible in Menu Settings / Parent menu item


Complicated views layout I need to display part of the exposed form in my page's sidebar, and the rest of the form and content in the $content area. There's really no good way that I can find to do this. I sort of got it to show up in a way by making a "block" view with "exposed form" set and then trying to only show the part that i needed through .tpl files. The problem is that then, when the submit button is clicked (the submit button is in the $content area), then the filters that are in the sidebar are not taken into account.

Ideas?

You are facing the limitations og HTML itself. All of the form fields has to be in the same form to make it work. If you split them up in two forms it will not work as the browser will see it as two different forms.

A workaround would be to render the entire form both places, hide unwanted fields with CSS and use JavaScript to sync values between the forms.


Warning: Cannot modify header information - headers already sent My log is cluttered with this message:

Warning: Cannot modify header information - headers already sent by (output started at /home/path/to/drupal/7/includes/common.inc:2681) in drupal_send_headers() (line 1216 of /home/path/to/drupal/7/includes/bootstrap.inc).

It occurrs only when someone types address to a non-existing comment like this:

http://example.com/comment/874

If the comment exists, or for any other address, there is no error. (I was deleting lots of spam comments recently and the bots keep coming back to read their own comments, that's why there is a lot of not found comments.)

Is there any means to get rid of this error? The only comment module I have is Comment Goodness and there isn't complaint on such error in the issue queue, so maybe it's something else. I checked all my custom module files and each of them starts with <?php and there is no space or anything before this tag, and there is no closing tag. I have no idea what else to check.

In my own case, I've found that this was due to modules that attempt to return a 404 by mistakenly calling drupal_not_found() instead of returning the MENU_NOT_FOUND constant. This causes drupal_deliver_page() to be called twice in a single page request.

Views is the biggest culprit right now; see https://drupal.org/node/1414068 (comment #16) for a patch that resolves it. You should grep through your modules directory for "drupal_not_found" to find other modules with this problem.


How to find operation type in validating form? I have created a custom validate function for specific node form.

But validate rules are different between edit a current node or add a new node modes.

Now, I want to know, is there any way that we understand whether we are in edit mode or create mode in form_validate function ?

A new node will not have a node ID.

So you can check the form values or the original form for that to determine whether it is a new node or not.

For example:

if (empty($form_state['values']['nid'])) {
  // This is a new node.
}
else {
  // This is an existing node.
}


How to achieve if else statement while querying with database? I want to export some data from test_records table depend upon supplied from date and to date. I from and to date not supplied I want to export whole data. So how I can achieve that. Below is my code.

$from_date = strtotime($form_state['values']['fromdate']." 00:00:00");
$to_date   = strtotime($form_state['values']['todate']." 23:59:59");

$result = db_select('test_records', 'n')
      ->fields('n')
      ->condition('submitted_time',  array($from_date, $to_date), 'BETWEEN')
      ->execute()
      ->fetchAll();

I am using one condition that will compare submitted_time in database with supplied from and to dates.  But When I pass nothing, it should get all the data from that table. Any suggestion will be appreciated.

I'm not sure if you can add if statement to a query but as you already have the values of $form_state['values']['fromdate'] and $form_state['values']['todate'] you can just add an if statement. If those two don't have values then execute a different query without the condition('submitted_time',  array($from_date, $to_date), 'BETWEEN') condition.


Contextual links for programmatically embedded views When embedding a View programmatically, using views_embed_view, what can I do to have the contextual menu (gear icon) appear over its area?

Views does this by wrapping the render array output with the views_add_block_contextual_links() function. It checks if the display plugin has contextual links associated with it. If the $display_id is a block then it will have the contextual links.

  if ($view = views_get_view($name)) {
    if ($view->access($display_id)) {
      $output = $view->execute_display($display_id);
      // Before returning the block output, convert it to a renderable array
      // with contextual links.
      views_add_block_contextual_links($output, $view, $display_id);
      $view->destroy();
      return $output;
    }
    $view->destroy();
  }

You already understand the $name and $display_id. The output from this needs the render() function. You can put this in a function that is called in TEMPLATE_preprocess_node(), for example, and then use print render($embedded_view) in the node.tpl.php template.


My Custom drupal 8 module does not shown in modules list I'm developing my first drupal 8 module, a custom migration module, the info.yml file is written as follow :

name : Drupal Center Custom Migrate
description : This module provides custom migration configuration and plugins to migrate my custom site from drupal 6.
type : module
core : 8.x

package : Custom migrate
dependencies :
  - migrate
  - migrate_plus
  - migrate_tools
  - migrate_upgrade
  - migrate_drupal

The above code is saved as dc_custom_migrate.info.yml . This module also provides some config migration file and some custom source plugins.

The problem is my custom module is not shown up in modules list.

I can't figure it up where am I doing wrong!!!

PS. I'm developing in windows 10 environment and using Aquia Dev Desktop 2 as web service simulator.

Remove the spaces between the identifiers and colons:

name: Drupal Center Custom Migrate
description: This module provides custom migration configuration and plugins to migrate my custom site from drupal 6.
type: module
core: 8.x

package: Custom migrate
dependencies:
  - migrate
  - migrate_plus
  - migrate_tools
  - migrate_upgrade
  - migrate_drupal

Then it'll work.

See the YAML rules for more info.


How can I get multiple values in a RESTful endpoint from a field who points to other resource? I have a Drupal 7.x site with RESTful installed (version 2.5) and I want have one endpoint which shows a node view, and add a field which show a index of nodes ,extracted from another endpoint, which have a entity reference field pointing to the first node.

I tried adding 'resource' key in publicFields method but I can only get the first result.

I saw restful obtain a resource view using ResourceFieldEntity class, calling allways view method inside of singleValue method, which only can return first value. It guess it's made in this way because singleValue don't need return more than one value, but in my case its needed, because i need the resource retrieve the complete result.

Here is where method is called, in line 336 of ResourceFieldEntity class.

   try {
     // Get the contents to embed in place of the reference ID.
     /* @var ResourceFieldCollection $embedded_entity */
     $embedded_entity = $embedded_resource
       ->getDataProvider()
       ->view($embedded_identifier);
   }

I solved this creating a custom resource getter class (extending ResourceFieldEntity), and overwrite singleValue method, and called index method instead of view method.

   try {
     // Get the contents to embed in place of the reference ID.
     /* @var ResourceFieldCollection $embedded_entity */
     $embedded_entity = $embedded_resource
       ->getDataProvider()
       ->index($embedded_identifier);
   }

Are there any other proper way to do this?

I haven't used this module in a while, so I'm not sure if there's a major difference in the approach between 1.x and 2.x.

I would just implement a custom function for getting the single resource, so that you have full control over what is ret

/*
* Overrides \RestfulEntityBase::controllersInfo().
* Allows us to specify custom functions for different HTTP actions.
*/
public static function controllersInfo() {
  return array(
   '^.*$' => array(
     \RestfulInterface::GET => 'customGetSingleExample',
   ),
  );
}

/**
* Return custom data for getting single resource result
*/
public function customGetSingleExample() {

  //grab request values
  $request = $this->getRequest();
  static::cleanRequest($request);

  //do stuff with request (EntityFieldQuery etc)

  .....

  return $result;
}

This is within a custom resource class, which extends RestfulEntityBaseNode

class RestfulCustomResource extends RestfulEntityBaseNode {