How to display a form filled by a VBO-submission? I'd like to use Privatemsg module to send messages to group of users. For this purpose I plan to use a view with Views Bulk Operations (VBO) and plenty of exposed filters.

I was able to create a custom VBO-action that puts the selected users into the recipient field of the message form:

function mymodule_my_custom_action(&$user, $context=array()) {

module_load_include('pages.inc','privatemsg');

$recipients = array();
foreach ($user as $recipient) {
$recipients[] = user_load($recipient->uid);
}

$subject = 'Some subject'

$message_form = drupal_get_form('privatemsg_new', $recipients, $subject);
$message_html = drupal_render($message_form);
}

I'm not very experienced in development so I don't know how to display this form together with the view that helps choosing the recipients. A simple print $message_html; won't be enough of course. For example would it be possible to use a panel page containing two panes: one for the view of users with VBO and one for the privatemsg form?

Any help would be greatly appreciated!

As per the "I'm not very experienced in development", you may want to use an alternative approach which only requires site building skills, as further explained below ...

Use the integration of the Privatemsg module with Rules instead (make sure to checkout this community docu, and its child pages ...), together with the Views Bulk Operations module.

For more details, refer to the video about Using Rules components with VBO. Possibly you also want to look at the 2 prior videos and/or the 2 subsequent videos (all about Views Bulk Operations), i.e.:

Introducing Views Bulk Operations.
More details about VBO settings.
Using Rules componens with more than one parameter.
Using VBO to load list of objects into Rules.

In this specific case;

use Views bulk operations to create the list of your users to be targeted (so this is just a minor variation of the VBO based view you seem to already have in place).
create a Rules Component which uses Rules action "Send a message" (provided by the Privatemsg module). If you'd add 2 "variables" to this Rules Component, named something like "MsgSubject" and "MsgBody", you might want to use those variables as "tokens" for constructing the actual Subject and Body of your message.
Within your VBO settings, just execute this Rules Component. If you then use this VBO-view, you can specify the desired values for the variables used to create your Rules Component (like "MsgSubject" and "MsgBody"). So you avoid hardcoding the "Subject" and "Body" for the "Send a message" action (without those variables it would only allow you to send predefined messages). And this simply by using these variables of your Rules Component (to implement that "Subject" and "Body" of the message). That way, each time you use your VBO to send such messages, you can enter the desired "Subject" and "Body" for each of those messages.

Done, no (custom coding) involved ...

For some other illustrations about using VBO in combination with Rules Components, refer to the answers to these questions:

How to bulk update select list fields?
How to bulk delete selected content/nodes?


Why does Apache show such drastic differences in memory usage when using mod_php? I've taken steps to reduce as much as possible the memory footprint of my Apache mod_php processes by disabling Apache modules as well as Drupal modules.

When the server is under light load, I see memory usage between 40MB and 80MB.  However, when the server is under heavy load and there are about 100 processes active, 90 of those 100 will be 12MB.

I'm assuming this is a good thing of course. I know that the PHP is embedded into each process so then why would there be such a drastic difference in the memory footprints, 12MB and 80MB, and why can those first 10 be in the area of the 12MB range?

The main difference is that different requests to a Drupal site will do different things.

Serving up a static image, CSS, or JS file has very little overhead and the PHP handler doesn't do anything.

Serving up a cached page invokes the PHP handler and Drupal bootstraps, but the overhead is small, compared to other requests.

Serving up a non-cached page will cause a full Drupal bootstrap, and all of the PHP necessary to render the URL will run.

Serving up an image derivative will invoke PHP, and there will be additional memory overhead.

Serving up a page with an empty Drupal cache will result in all of the overhead of rebuilding the memus, registry, etc, and can cause a pretty big memory swell.

So, I suspect you are seeing the result of processes serving up different types of requests.


Initiate file download and redirect to loged-in home page The users can share the file download URL and user with credentials can download the file. All the things working fine. Once the user paste the download url in address bar, it redirects to login page and after successful login the file downloads. But its not redirecting to the loged in home page. Need to happen both things (file download & redirect to loged-in homepage) on successful login. How can we achive this.

Try to use any of these modules. I hope below modules helps you to solve your issues :

LoginToboggan

  Allow users to login using either their username OR their e-mail address.
  Allow users to login immediately.
  Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
  The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in".
  The other brings the user to a separate page, but returns the user to
  their original page upon login.

Login Destination

  The Login Destination module allows you to customize the destination
  that a user is redirected to after logging in, registering to the site
  (7.x), using a one-time login link or logging out (7.x). The
  destination can be an internal page or an external URL. It is possible
  to specify certain conditions like referring pages or user roles and
  make the destination depend upon them. You may use PHP snippets to
  provide custom conditions and destinations. It is also possible to
  keep users on the currently visited page after logging in or out.

Anonymous Login

  This is a very simple, lightweight module that will redirect anonymous
  users to the login page whenever they reach any admin-specified page
  paths, and will direct them back to the originally-requested page
  after successful login.

OR

You can do this by using Rules module.

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules).


The most efficient way to query the user table and custom profile info based on UID I am trying to grab a specific users profile info + custom profile fields WHERE uid = X,
I have used the views module currently and copied that sql however that creates a massive query. I was wondering if there is a better way to query Drupal 6 other than views to grab the UID, name, email, + my custom fields?

SELECT profile_values_firstname.value AS profile_values_firstname_value,
profile_values_firstname.uid AS profile_values_firstname_uid,
profile_values_surname.value AS profile_values_surname_value,
profile_values_surname.uid AS profile_values_surname_uid,
profile_values_telnumber.value AS profile_values_telnumber_value,
profile_values_telnumber.uid AS profile_values_telnumber_uid,
users.mail AS users_mail,
users.uid AS users_uid,
users.access AS users_access,
users.name AS users_name
FROM node node
 INNER JOIN users users ON node.uid = users.uid
LEFT JOIN profile_values profile_values_firstname ON users.uid = profile_values_firstname.uid AND profile_values_firstname.fid = '1'
LEFT JOIN profile_values profile_values_surname ON users.uid = profile_values_surname.uid AND profile_values_surname.fid = '2'
LEFT JOIN profile_values profile_values_telnumber ON users.uid = profile_values_telnumber.uid AND profile_values_telnumber.fid = '3'

There are a few ways your query can be improved. First, there were some multiple queries for the user's id which I removed. Second, your query was selecting from the node table and then inner joining with the users table which can cause some undesired results (e.g. only users who have created content on your site will show up) and it is also less performant.

Here's the improved query. Since all profile values are stored within the same table using a 'fid' field id to differentiate them one has to do an inner join for each value that you want to select. Hence the query has to be a little longer than one would hope.

  SELECT profile_values_firstname.value AS profile_values_firstname_value, profile_values_surname.value AS profile_values_surname_value, profile_values_telnumber.value AS profile_values_telnumber_value, users.mail AS users_mail, users.uid AS users_uid, users.access AS users_access, users.name AS users_name FROM users users LEFT JOIN profile_values profile_values_firstname ON users.uid = profile_values_firstname.uid AND profile_values_firstname.fid = '1' LEFT JOIN profile_values profile_values_surname ON users.uid = profile_values_surname.uid AND profile_values_surname.fid = '2' LEFT JOIN profile_values profile_values_telnumber ON users.uid = profile_values_telnumber.uid AND profile_values_telnumber.fid = '3'


How do I set a custom path for feeds feed items in views? Update

I tried doing what Nikhil and the referenced threads said, but I'm still have trouble. I should have been more clear initially on what the problem is. When I go to <new-feed-node-path>/feed-items I'm given a page not found. That is, localhost/shows/<show>/feed-items. The URL in views for that page used to be node/%/feed-items, and I changed it to shows/%/feed-items. The paths of the feed items themselves works fine, ie. localhost/episodes/<episode-title> is working.

In pathauto settings I put:

Pattern for all Feed paths

shows/[node:title]

Pattern for all Feed item paths

episodes/[node:title]

And then in the feeds_defaults_feed_items view I put shows/%/feed-items in place of the default path, node/%/feed-items. I also tried shows/[node:title]/feed-items. I created a new feed each time to test.

The solution is to

Create a simple rule to delete and create url aliases after the content was saved, for the feed content type.
Used a pattern episodes/[node:title] which will give you the result.

Refer:

https://www.drupal.org/node/1161202
https://www.drupal.org/node/1210128


Why field tables are not getting removed when I remove the field? I have a content type with 20 different fields.

Now the project requirement changed and I dont need 15 fields of them. So I removed all those unwanted 15fields from content type.

But the database is still holding all the 15 tables and also the revision table, Why?
What happens if I remove it?

I feel like having these many unused tables in database might impact the performance. Will it really have impact on the performance?

I feel like having these many unused tables in database might impact the performance

That's very unlikely, unless the extra disk space used will somehow affect your server's performance.

Deleted fields and data are cleared up on cron runs (by field_purge_batch()), so running cron a few times will probably get rid of them. Exactly how many runs it takes will depend on the number of fields, amount of data in each, etc.

I'd advise against removing it manually unless you're quite familiar with the internals of the field API, and understand the implications.


Add field linking to related node I have created a Content Type that allow to download PDF files. Meanwhile I want to have this file available in a html version; as in Modules' notes in Drupal's website.

So the easiest way is to: create this html version as a new node, and use node reference field type to link to this node. But this process takes two steps to do it, and within large nodes it will take while to find the referenced node.

So what is the more sufficient way to add a related node to a content type?

You can do this in two ways.

Option 1:
Add a textarea field to the file content type, with the necessary text options (fe html on etc), and create two various displays via Display Suite. Create a view block with the nid as contextual filter.
And select the node display for showing.

Option 2:
Install the prepopulate module and setup a rule that after saving the html content type node redirects to file content type with the right url + prepopulate information. Have 2 separate content types. In the file content type add a reference field with prepopulate settings.

Now after you create the node with html information it redirects to the file content form with the reference field filled... So no searching and no hassle.


Submitting fieldsets I have fieldsets in my form like this

$form['fieldset_1']['name']

and then

$form['fieldset_2']['name']

but when I submit the form and access the values item in $form_state there is only one name value - not as expected ['fieldset_1']['name'] and ['fieldset_2']['name']

can someone help how the form could be submitted and to have access to bot name values ?

You can use the #tree property on both fieldsets, e.g.

$form['fieldset_1'] = array(
  '#type' => 'fieldset',
  '#title' => t('Title 1'),
  '#tree' => TRUE,
);

$form['fieldset_1']['name'] = array(
  '#type' => 'textfield',
  ...
);

$form['fieldset_2'] = array(
  '#type' => 'fieldset',
  '#title' => t('Title 2'),
  '#tree' => TRUE,
);

$form['fieldset_2']['name'] = array(
  '#type' => 'textfield',
  ...
);


How to hook_form_alter() inside paragraph item I would like to edit a field in the node_form of a paragraph item. For normal fields i would use something like the code below to tweak a field called field_p_custom_id (d7)

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    switch ($form_id) {
        // tweak CONTENTTYPE_node_form
        case 'CONTENTTYPE_node_form':
            // hide custom ID field for all users, even admin (this field should never be changed)
            $form['field_p_custom_id']['#access'] = FALSE;

        break;
    }
}

... but, in the case of a paragraph item, the field_p_custom_id is placed inside a paragraph bundle. I searched inside $form and $form_state, but can't find where to alter this field. (the paragraph item is default not present on the form since it is not required and can be added unlimited times)

For Drupal 8 you can implement hook_field_widget_WIDGET_TYPE_form_alter.

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function paragraphs_test_field_widget_entity_reference_paragraphs_form_alter(&$element, &$form_state, $context) {
  if ($element['#paragraph_type'] == 'altered_paragraph') {
    $element['subform']['field_text']['widget'][0]['#title'] = 'Altered title';
  }
}

see my answer here: How do I alter the behavior of the form fields contained within the paragraph field?


How do I translate a views field to lowercase and with spaces replaced with dashes but not make it a link? I've got a link that surrounds some code (jquery hexagons). I'd like to be able to just print out the link.

The solution

Firstly, 2 copies of the 'studio name field'. The second set to 'rewrite as link' with the translations.

Secondly, 'exclude from display' both fields.

Thirdly. Custom text to print out the hexagon.

[field_studio_name]

        [field_studio_address]

[field_studio_name]

        [field_studio_address]

If I use the 'rewrite as link' replacement then I get

 <a href="/studio/">

If I use the raw version I am stuck with

Here is a fiddle with a views export that demonstrates the problem.

You want link all output with studio/my-studio .First convert My studio to lowercase then rewrite as link  custom text.

Think My studio is [field_studio_name_1] .Convert this to lowercase. Then rewrite as link custom text like this .


How do I use the Print Module with a Custom Form Module? I have searched and searched but have not found a definitive answer or direction. I've installed the Print module (Printer, email and PDF) and have it successfully working when associated with content types.

My problem however, is making it work with custom forms. I have tried placing print_insert_link() in the form and it doesn't show up. I think all I'm missing is an example of print_insert_link() pointing to a custom form module. The path for the custom module I'm working with now is glatfelter_forms/form_scorecard.  How do I properly use print_insert_link()?  I'm using Drupal 7.23. This is my first post so please let me know if I can provide any additional detail. Thanks!

In the configuration page of the Print module at admin/config/user-interface/print, there is a section 'Show link in system (non-content) pages'.

If you select Show on only the listed pages. and enter the path of your form (glatfelter_forms/form_scorecard) in the textarea below, there will be a print link on that page.


How to exclude nodes with a taxonomy term from XML Sitemap? We can exclude content type, or individual node from XML Sitemap. But, is there anyway to exclude nodes with specific taxonomy term? For example excluding nodes with longlivethetroll tag.

You can use hook_xmlsitemap_element_alter() to check if the node has a particular taxonomy term & exclude it.

function MYMODULE_xmlsitemap_element_alter(&$element, $link, $sitemap) {
  // Check if link is a node link
  if ($link['type'] == 'node') {
    $node = node_load($link['id']);

    // Code to check if $node has taxonomy term goes here
    if ($node has taxonomy term) {
      $element['disabled'] = TRUE; // This removes the node link from sitemap
    }
  }
}


Adding Specific CSS to View How would one go about trying to accomplish the following under Views in D7:

Say I have four different content types (apples, oranges, kiwis, and mangoes) which are culminated into one view listing them all on a single page.

I'd like to try and add a CSS class to both apples and kiwis that is unique to each (for example, all apples having a class of "red" and all kiwis having a class of "fuzzy") but I do not want to add classes to mangoes or oranges.

How would I let Drupal know to add these classes based on their content types?

You can use template_preprocess_views_view_fields function in order to do it.


Remotes: Can a local Drush 8 be used to send commands to a remote Drupal 8.4 site which includes Drush 9? Let's say we have a dev-ops administrator who isn't a developer and doesn't want or (normally) need a local copy of the website.

As of Drupal 8.4, Drush 9 is required, and Drush 9 doesn't have a way to install it globally. But Drush 8 still does.

So the question is, can someone use Drush 8 locally with aliases for a remote Drupal >8.4 site with Drush 9 as a dependency?

If not, then, is there another way someone can use a local Drush 9 without building the entire site?

What's the best practice for someone who needs to run Drush locally to control remote sites in the Drush 9 world, where "someone" means someone who isn't working on a local copy of the site?

I would assume install drush 9 locally to a project, but still use alias files for all your remote systems. eg, treat the local installation as a globally installed service conceptually.

if you dont like a random project on your system hosting drush this way stick it on a VM or Container and interact with drush there.


Submit button calling wrong submit handler I have a form with 3 different "Submit" buttons, and I want each of them to map to a particular Submit handler.

I have included these items using the following, generic, pattern:

                    array(
                        '#prefix' => '<td>',
                        '#suffix' => '</td>',
                        '#type' => 'submit',
                        '#value' => 'Update',
                        '#submit' => array('user_profile_details_edit_phone_submit')
                    )

But, every time I click the "Submit" button, the incorrect function is called. The function that IS called is the LAST function I add to a submit handler in this way.

Am I doing something wrong?

Drupal uses the name and value of submit buttons to identify which was pressed, and subsequently which submit handlers to run. If the names and values of all three buttons are the same, the FAPI will only be able to use one of them (in this case the last one).

To fix it you can assign a unique #name property to each of the buttons.


Allow only lowest taxonomy terms to assign to nodes I have a lot of taxonomy terms that need to be categorized into multiple categories and subcategories:

- AAA
  - BBB
    - CCC
    - DDD
    - EEE
...

Is there a way how to restrict assigning higher terms to nodes (AAA, BBB) and allow to use only lowest terms (without any child terms - CCC, DDD, EEE)?

Hierarchical Select.

  Hierarchical Select has the ability to save the entire lineage of a
  selection or only the "deepest" selection. You can configure it to
  force the user to make a selection as deep as possible in the tree, or
  allow the user to select an item anywhere in the tree. Levels can be
  labeled, you can configure limit the number of items that can be
  selected, configure a title for the dropbox, choose a site-wide
  animation delay, and so on. You can even create new items and levels
  through Hierarchical Select!


Drupal and its modules kept in two different subfolders -- possible/how? New to Drupal... I was wondering if it was possible to install it with the core and the modules kept in separate folders, rather than in a hierarchy. A bit like with WordPress, so to speak:

/.htaccess <-- site is here, in /, and in git
/drupal    <-- Drupal core, pulled as a git submodules
/content   <-- plugins and themes, each pulled as git submodules

I'm guessing it's possible, but the installation manual and a bit of googling (skeleton, subfolder, enterprise, etc.) led me nowhere. If so, I could use a pointer to get me in the right direction. If not, will it be possible with Drupal 8, which unless I am mistaking is using Symfony components?

install it with the core and the modules kept in separate folders, rather than in a hierarchy

In short, no.

Drupal must be able to expect to find files in a certain location, and that is not dynamically configurable. The very first line of code Drupal executes is define('DRUPAL_ROOT', getcwd());, and file wise, most things are based on that constant.

Symfony, and PSR-0, doesn't inherently change that. PSR-0 only defines the directory structure around files, not where to find them. With that said, I haven't looked in enough detail at D8 to know if there's a simple way to alter where the autoloader looks for files.

If your filesystem (and webserver) supports symlinks, you can work around the problem by symlinking the appropriate directories in place.


How do I change the default front page? How do I change the URL present under Home » Administration » Configuration » System in my Drupal site?
I want to get rid of the stuff circled in red, but it only seems that I can add different pages only in the blank input box next to it.

It is because you run Drupal in local; if you uploaded your site to a valid domain or set a virtual host, you get rid of it.

You can set your virtual Host following How to Add Virtual Directory Alias on Apache Xampp. You could also use Acquia Desktop dev2 which handles virtual hosts by itself.


Get User ID (not current) in a overridden views.tpl.php I'm using Drupal 7.
I'm creating a view based on profile. It will show a list of all the people.
Now I'm overriding the file views-view-unformatted--MYVIEW-page.tpl.php and I would like to add in the class of the row the ID of that user.
If I write

global $users;
$user->uid;

of course it's giving me the id of the current user and not the uid of that profile.

I would like to create something like this:
FIRST EXAMPLE:

    <?php
    $this_uid = I NEED THIS TOKEN;
    ?>

    <?php foreach ($rows as $id => $row): ?>
      <li class="<?php print $classes_array[$id]; print " ".$this_uid;?>">
        <?php print $row; ?>

    <?php endforeach; ?>

I could create a custom text field in the view a put all the field inside the
 tag
like:
SECOND EXAMPLE:

[name] [gender]

and the file tpl.php will become

<?php foreach ($rows as $id => $row): ?>
            <?php print $row; ?>
        <?php endforeach; ?>

But in this way I will lose the default row classes...

How can i get the first example? Do I need to create a view based on user instead of profile? Or should I use the second example?

Thanks in advance.

You should have a $views variable available with an array similar to $rows called $view->result[] that contains the unrendered/raw view results and just as long as you have a field in your output that has the uid in it, you will be able to access it directly here.  (It can be a hidden field if you don't want it rendered later on) Put a drupal_set_message('<pre>' . print_r($view->result, true) . '</pre>'); or its equivalent in your template to take a look at it, but basically you should be able to use something like $view->result[$id]->FIELDNAME to access it or any other raw data.


Programmatically redirect I'm creating an action to trigger on a rule when a user is logged in. I have a field of the user that is a term reference.

I would like to redirect to the url field of the chosen term. This is how I get the chosen url:

$tid = $user->field_redirect_field['und'][0]['tid'];
$taxonomy = taxonomy_term_load($tid);
$url = $taxonomy->field_url['und'][0]['safe_value'];

I receive a perfect url like stocklijst/gezocht (this works ok). Now I would like to redirect to that url. I've tried this:

drupal_goto($url);

But it doesn't redirect. It always goes to the front-page...

UPDATE:

This is what I do now:

I have a rule (When user logged in) that triggers a custom action "Redirect to user url". It's a custom action like this:

function redirectonlogin_rules_action_info() {
    $actions = array(
        'redirectonlogin_redirect_login' => array(
            'label' => t('Redirect on login'),
            'group' => t('My custom actions'),
            'parameter' => array(
                // curent user
                'user' => array(
                    'type' => 'user',
                    'label' => t('User'),
                    'description' => t('The current logged in user.'),
                    'save' => FALSE,
                ),
            ),
        ),
    );
    return $actions;
}

function redirectonlogin_redirect_login($user) {
    // REDIRECT TO USER REDIRECT FIELD
    $tid = $user->field_redirect_field['und'][0]['tid'];
    $taxonomy = taxonomy_term_load($tid);
    $url = $taxonomy->field_url['und'][0]['safe_value'];

    unset($_GET['destination']);
    drupal_static_reset('drupal_get_destination');
    drupal_goto($url);
}

The user can select a url in a select list. These are taxonomy terms... .

This works perfectly. But it takes some time, could there be a cleaner way and faster way of doing this?

You could use hook_form_alter(),
In this hook we could redirect with $form['redirect'] = $url;


Change the Order of Fields on Teaser node.tpl Hello i am struggling here a bit to change the display of my node teasers. I was hoping to take the title and submitted part and put it on top of my body field to the right of my teaser image. Ive tried Panelizer (looks great but the image field stays there if there is an image or not), Entity View Modes (dont know if this is really what i need) and even tried what could be the best way just simply editting the node.tpl and changing the fields about.

I think i'll just go with the last way as i did almost have it but due to a lack of knowledge and trouble finding out more ive had to ask you guys for some help.

I think i need to add

    <?php if ($teaser): ?>
        something in here
        <?php endif; ?>

but either it just not working (soz ive been up 24hs and im at the end of the line i think. Just hoping for some help either before bed or for when i get up) or else i get 2 body texts and titles appearing. I was just wanting my image on the left then to the right my title nd submitted fields above the body text.

I hate folks that do this but im gonna give it a go as im too tired to think now im sorry. here is my node.tpl Even just a good suggestion of what to do would be great. even better would be reworked code and i wont learn anything at all but i have tried. Tried for the past 4 hours

    <article class="node-<?php print $node->nid; ?> <?php print $classes; ?> clearfix"<?   php print $attributes; ?>>

      <?php if ($title_prefix || $title_suffix || $display_submitted || $unpublished ||   !$page && $title): ?>

          <?php print render($title_prefix); ?>
          <?php if (!$page && $title): ?>
            <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

          <?php endif; ?>
          <?php print render($title_suffix); ?>

          <?php if ($display_submitted): ?>

              <?php print $user_picture; ?>
              <?php print $submitted; ?>

          <?php endif; ?>

          <?php if ($unpublished): ?>

<?php print t('Unpublished'); ?>

          <?php endif; ?>

      <?php endif; ?>

      <?php
        // We hide the comments and links now so that we can render them later.
        hide($content['comments']);
        hide($content['links']);
        print render($content);
      ?>

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

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

Thanks in advanced. Ive got to the stage where even posting code on stackexchange is hard work for me :(

Example

<?php if ($teaser): ?>
    <?php print render($content['YOUR_IMAGE_FIELD']); ?>
    <?php print render($title_prefix); ?>
        <?php if ($title): ?>

<?php print $title; ?>

        <?php endif; ?>
    <?php print render($title_suffix); ?>
    <?php hide($content['YOUR_IMAGE_FIELD']); ?>
    <?php hide($content['links']); ?>
    <?php print render($content); ?>
    <?php print render($content['links']); ?>
<?php else: ?>
   //...show default view mode
<?php endif; ?>

Most of the fields are bundled together into the $content variable.

We can remove them from being output in the $content variable by using the hide() function just before we render it (see above).

We can then print the specific field anywhere we like in the template like. See above where weve put the image field.

To determine what fields you have to play with do a var_dump($content) at the top of the template or even better use the Devel module to do this.


How do I duplicate a menu item properly? Say I need to have the same menu item appear in two different menu trees or at two different level of the same menu. How do I properly "duplicate" a menu item using hook_menu()?

To my understanding, if the original item has its path corporate/contact-us, then putting in the hook_menu() the same path will override the original rather than create a copy. Am I right? How do I clone, or should I say: alias, a menu item programmatically?

(And I need to do that for each language defined for my site.)

I have used this piece of code, using hook_menu_alter() which for some reason did not work; once an item has been created it did not change its label and produced buggy, combined paths (/en/polish/path). Hence the attempt to unset the custom item first.

function MYMODULE_menu_alter(&$items) {
  global $language;

  $custom_items = array(
    'pl' => 'firma/kontakt',
    'en' => 'corporate/contact-us',
  );

  foreach($custom_items as $langcode => $path) {
    unset($items[$path]);
  }

  switch ($language->language) {
    case 'en':
      $items['corporate/contact-us'] = array(
        'title' => 'Contact Us',
        'page callback' => 'node_load',
        'page arguments' => array(285),
        'access callback' => TRUE,
        'menu_name' => 'main-menu',
        'type' => MENU_NORMAL_ITEM,
      );
      break;

    case 'pl':
      $items['firma/kontakt'] = array(
        'title' => 'Kontakt',
        'page callback' => 'node_load',
        'page arguments' => array(286),
        'access callback' => TRUE,
        'menu_name' => 'main-menu',
        'type' => MENU_NORMAL_ITEM,
      );
      break;
  }
}

Similarly, the following hook_menu approach did not work for me, with similar problems. This one was even worse in that the 'fake paths' with '2' in the title where visible to the user in the status bar.

function sint_newsnavi_menu() {
  global $language;

  switch($language->language){
  case 'en':
    $items['corporate/contact-us2'] = array(
      'title' => 'Contact Us',
      'page callback' => 'drupal_goto',
      'page arguments' => array('node/285'),
      'access callback' => TRUE,
      'menu_name' => 'main-menu',
      'type' => MENU_NORMAL_ITEM,
    );
    break;
  case 'pl':
    $items['firma/kontakt2'] = array(
      'title' => 'Kontakt',
      'page callback' => 'drupal_goto',
      'page arguments' => array('node/286'),
      'access callback' => TRUE,
      'menu_name' => 'main-menu',
      'type' => MENU_NORMAL_ITEM,
    );
    break;
  }
  return $items;
}

The code that works in any case, whatever corporate/contact-us is a view, a menu item defined from another module in its hook_menu(), or a path alias for a node, is similar to the following one.

function mymodule_menu() {
  $items['the menu path you prefer'] = array(
    'page callback' => 'mymodule_page_callback',
     // …
  );

  return $items;
}

function mymodule_page_callback() {
  drupal_goto('corporate/about-us');
}

The only problem with this code is that it could redirect users to a page to which they could not have access, and for which they would get an access denied error. If the users don't have access to a menu item, the menu item should be hidden to them, and that can be done by adding the right access callback to the menu item.

function mymodule_menu() {
  $items['the menu path you prefer'] = array(
    'page callback' => 'mymodule_page_callback',
    'access callback' => 'mymodule_access_callback',
     // …
  );

  return $items;
}

function mymodule_page_callback() {
  drupal_goto('corporate/about-us');
}

function mymodule_access_callback() {
  if ($router_item = menu_get_item('corporate/about-us') && !empty($router_item['access'])) {
    return $router_item['access']);
  }

  return FALSE;
}

In this case, the access callback just checks the users have access to the menu item to which they are going to be redirected.


single tpl.php file for two nodes? In my Drupal7, I have same piece of code in tpl.php files for two different nodes. My tpl.php files are following:

page--node--9.tpl.php
page--node--11.tpl.php

Since code is same for both pages, it is possible to create a tpl.php file for both nodes? I mean something like

page--node--9and11.tpl.php

You can use template_proprecess_page hook to achieve this as shown below:

function <THEME_NAME>_preprocess_page(&$vars) {
    if (arg(0) == 'node' && in_array(arg(1), array(9, 11))) {
        $vars['theme_hook_suggestion'][] = 'page__node__9and11'; //For page--node--9and11.tpl.php
    }
}

Add above code to template.php of your theme & clear cache.


What is the difference between "Autocomplete" and "Autocomplete (Tags style)" field widget type? What is the difference between an "autocomplete" and an "autocomplete (Tags style)" widget. These options are present when I add an entity reference field for example.

For one term, there is no difference.

When you increase cardinality (i.e. allow unlimited number of values), with tag style you will put all tags in one textbox, just like you do with tags on this site, and with regular autocomplete you will need to put each one with it's own textbox.


Having trouble adding a custom js file to my Drupal 7 site I added a javascript file to my site in the theme's .info file

scripts[] = js/myjs.js

The js file loads and I can see that it's included in the head when I load the site, however the jQuery javascript doesn't work at all.  I have a simple show/hide when a div on the page is clicked by it's not working.

This works fine when it is not in the Drupal site.

By clicking "Click here to start quiz" it should hide that div and show another.

I have a feeling it is because I do not have the most updated version of jQuery installed (I have 1.4.4 instead of 1.9.1), but I'm not sure how to update it for the theme I'm using.

Any ideas?

I was able to solve the problem by changing the document.ready function on the first line of my js file from: $(document).ready(function () { to: jQuery(document).ready(function ($) { I found the answer here:


How to hide label in customized contact form? I added a field 'Contact_Catégorie (system name: field_contact_categorie)' to the default 'feedback' contact form.

The field type is List (Text) in which I store a set of "email address | label" in order to redirect the email to the proper recipient depending on the item selected in the list.
That works well!

My issue is about the form display: whatever I choose for the label (Above, On the same line, Hidden, not displayed), the label (Contact_Catégorie) appears in the form.

Any idea?

The Display settings are for the message that is sent.  Setting label visibility in this section would impact how it appears in the email body.

The Manage Form Display are the settings for the form - unfortunately there are no options for label display.  You can alter the form by implementing hook_form_alter() https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Form!form.api.php/function/hook_form_alter/8.2.x  OR if you just want to hide that label you could do it with CSS in your theme, a simple display: none; should work.


Loading views blocks that aren't actively set Is there a way to programmatically load a views block that isn't active in the config(not placed under admin->structure->block layout).

My usual method to load a block programmatically is something like the following in hook_preprocess_node:

$block = Block::load('views_block__courses_block_3');
$block_render = \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);

However, that seems to just return null if I haven't placed the block into a region after creating it under views.

Also noticed that the block isn't listed in the config table until placed into a region.

See this answer for details.

Basically, the way to do this is to add a "Hidden Blocks" region to your theme, then place the blocks you want to render there.  The region does not get rendered so it's not a big resource drain.  We do this to use have "block" paragraphs using paragraphs all the time.


Set a default font family and size in ckeditor Its been 4 days I am trying to set a default font family to the ckeditor(not set default label) but I am not able to do the task. Also i tried working with content.css but its not working. Please need a help

Assuming you are using the CKEditor module you will need to override it using CSS. You can either create a ckeditor.css file to override it or edit it in your theme file.

Or you can add

config.extraCss += "body{font-family:Arial, serif;}";

To your extra javascript section in the settings text format.


Force a page to be rendered in admin theme In drupal 7 we could force a page to open in admin page, there are several way to do that in drupal 7

with hook_admin_paths

function hook_admin_paths() {
  $paths = array(
    'mymodule//add' => TRUE,
    'mymodule//edit' => TRUE,
  );
  return $paths;
}
with Admin theme module
with ThemeKeys module

Now I am looking for equivalent solution in Drupal 8, How can I force drupal to render a specified pages as admin theme?

You can add the _admin_route option to a route:

aggregator.feed_add:
  path: '/aggregator/sources/add'
  defaults:
    _controller: '\Drupal\aggregator\Controller\AggregatorController::feedAdd'
    _title: 'Add feed'
  requirements:
    _permission: 'administer news feeds'
  options:
    _admin_route: TRUE

You can also implement your own negotiator (See \Drupal\user\Theme\AdminNegotiator) or add that option to routes dynamically in a request subscriber.


Using AJAX in menu and menu tab links I have a few pages with sub pages as tabs. Each pages are in a custom menu. I'd like to convert the menu links to load each page using AJAX, is this possible?

I know how to load a page using a regular AJAX link, but not a menu, or menu tab link. One way is to replicate the menu links using AJAX and binding the events to the corresponding menu links, which works, but there must be a better way?

Assuming I understand your question correctly, it is possible. This is how I would do it (not sure how much this differs from the way you mentioned). Obviously you would need to change your page callback function, which you set for the tab in hook_menu(), to return a json object rather than a rendered page.

At the end of your page callback function you should add something like this:

// Return the rendered view in a JSON object. The object will contain a property
// named “contacts”, which containes the rendered view.  This will be sent to the
// browser and is accessable to javascript.
return drupal_json_output(array('contacts' => $view));
exit;

You would then need to include some javascript on the client-side to send an ajax request to the server using the URI/path you set for the tab in hook_menu.  This same client-side javascript would then process the returned data.

  currentMenuLink.click(function() {
      var updateContacts = function(data) {
        // The data parameter is a JSON object. Do something with the returned data here.
      };

      // Send ajax request.
      $.ajax({
        type: 'POST',
        url: this.href, // Which url should be handle the ajax request. This is the url defined in the  html tag
        error: function() {
          $('#namecards-get-contacts-by-nid-row-' + currentNid).show();
          $('#namecards-get-contacts-by-nid-cell-' + currentNid).html($('
An error has occurred while retrieving the list of contacts.  Please try again.  If the problem persists, please inform your website administrator.
'));
        },
        success: updateContacts, // The js function that will be called upon success request
        dataType: 'json', //define the type of data that is going to get back from the server
        data: 'js=1' //Pass a key/value pair
      });
      // return false so the navigation stops here and not continue to the page in the link.
      return false;
    }
  });


Which variables do I need to export with Strongarm? I have a theme based on adaptivetheme, which uses the color selector tool to allow one to edit the theme's color scheme through the UI.

When exporting a feature using the theme, the following variables are available:

color_themename_files
color_themename_logo
color_themename_palette (gives the list of colors)
color_themename_stylesheets

If exporting color_themename_files, an array of files like the following is exported:

array(
  0 => 'public://color/omtheme-58e01b40/bullet-round.png',
  1 => 'public://color/omtheme-58e01b40/bullet-sm-arrow-right.png',
  2 => 'public://color/omtheme-58e01b40/bullet-sm-arrow-down.png',
  3 => 'public://color/omtheme-58e01b40/button.gif',
  4 => 'public://color/omtheme-58e01b40/button-o.gif',
);

Similarly, color_themename_logo gives:

array('value' => 'public://color/themename-5cbf1601/logo.png');

I know I want to export color_themename_palette since that's the list of colors.  Is there any reason to export the other three variables?

Yes if the paths match up exactly on the other setup.
No if the paths don't.

Ideally you want to avoid putting platform specific options into features/code as they might not be the same across multiple environments.


Split PDF's into multiple parts Is it possible to allow pdf uploads to be split automatically by drupal?

Example1: If I upload a PDF with 4 pages. Drupal will split it into pdf(page1), pdf(page2),etc...

Example2: I upload a pdf that is 10mbs, It can logically split the files into a limit. So if the limit was 5mbs. It would split the file into 2 even parts...

Drupal can't out of the box. Doesn't mean YOU couldnt in PHP :) (i think)

I've written PDFs on-the-fly using Ruby and mucked with it in PHP soooo ....

Using Fields in Drupal you could supply an File Upload widget for PDFs.

Then write a module to process the file on upload,

Using PHP's built in PDFs functions like:

http://php.net/manual/en/function.pdf-get-pdi-value.php

simply get the numbers of pages, and then retrieve each page's content and make a new simple 1 page PDF out of it. Then save the file and FID to another Field of files with unlimited values for any number of pages .... It sounds doable for most PDFs (not necessarily crappy built non-standard PDFs) -- but definately some work .... :)


Validation with hook_form_alter() In Drupal 8, for the Comment entity, I want to validate an integer field (stored as field_nieuwe_waarde_value).
In each comment posted for a node, it needs to be greater than the value for the previous comment.

The code doesn't give any errors, but the validation doesn't work.

use Drupal\Core\Form\FormStateInterface;

       /**
        * Implements hook_form_alter().
        */

       function waarde_validatie_form_alter(&$form, $form_state, $form_id) {
         if ($form_id == 'comment_waarde_van_dit_voorwerp__form'){
           $form['#validate'][] = 'start_drupal_waarde_voorwerp_form_validate';
         }
       }

       /**
        * Validation form for the waarde_voorwerp form.
        *
        * Check if the value is > then the last submitted value
        */
       function start_drupal_waarde_voorwerp_form_validate($form, FormStateInterface &$form_state) {
         // Look for the just submitted value.
         $nieuwste_waarde = $form_state->getValue('field_nieuwe_waarde');
         // Look for all early submitted values.
         $alle_waarden = $form_state->getUserInput('field_nieuwe_waarde');
         // Search for the last submitted value.
         $laatste_bod = end($alle_waarden);
         if ($nieuwste_waarde <= $laatste_waarde) {
           $form_state->setErrorByName( t('Gelieve hoger dan'), $laatste_waarde, t('in te stellen'));
         }
       }

Adding a validation handler in hook_form_alter() is the Drupal 7 method of adding validation for a field. It will still work in Drupal 8, however the preferred method of adding validation to Field API Field in Drupal 8 is to add a Constraint to the field. Constraints will be applied when the Node is created, no matter the means of creation. Adding a validation handler to the form only validates the field when the node is created using the Form API - IE through a browser. If a node is created by any other means - IE through an API or programatically, the validation is not applied. Constraints are applied no matter the method of creating the node.

Documentation on how to add a constraint can be seen here: https://www.drupal.org/docs/8/api/entity-validation-api/providing-a-custom-validation-constraint

See Method 2 - adding constraints to fields added to an entity you haven't defined, or fields added through the UI


Field Template Loop Counter Override Problem I'm using a template override for field.html.twig

I'm simply trying to generate a data-depth attribute that takes the index of the loop and multiplying it by 0.2.

Here is the Twig markup:

  {% for item in items %}
    {% set i = loop.index %}
    {% set depth = i * 0.2 %}

      {{ item.content }}

  {% endfor %}

Here is the HTML output:

As you can see the first two iterations are the same - they have 0.2 as the data-depth which is incorrect it, the sequence should be 0.2, 0.4, 0.6, 0.8 and 1.0. Is this is a bug with drupal? Or am I totally missing something here.

Thanks in advance.

I just tested this and it works for me:

   {% for item in items %}
        {% set counter = ( counter | default(0) ) + 0.2 %}

{{ item.content }}

      {% endfor %}

This renders as:

...

...

Note, I did not get the repeating depth numbers as you did above.


Grid View of images in a Content I want to display images in grid view. I have designed a view which can display each album in grid view. Here album is a content type. The problem is that inside album I can see list view of images. I have selected unlimited number of value  in image filed under album content type. Below is the screenshot-

You can do it with CSS.

You add CSS to your theme. If you're using a theme like Zen that has SASS, you can add the new rules to your SASS file(s) and compile them to CSS. There is documentation for adding CSS to pages on Drupal.org.


How to create a CSV file to migrate my Commerce Products with the Feeds module? How do you create CSV files?

I have a new Drupal Commerce website and I want to migrate all my products from my previous Drupal 7 Commerce site. I want to use the Feeds module to import my products.

I have not been able to find a way "to create a CSV file". Any suggestions?

  How do I create a CSV file
  from my current drupal commerce to my new one?

You can use the Forena module. Here is a quote from that page:

  ... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Here is another quote from Reasons for considering Forena, related to the "CSV" in the question here:

  Reports created by Forena ... can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are CSV, XLS, DOC, HTML, etc.

So if you'd install Forena in your "old" site, then these are the steps for creating such CSV files are:

a custom SQL query (where you have the full power of SQL at your fingertips, and various extra features related to it provided by Forena, such as using report parameters, conditional SQL, etc).
a custom report (either by an admin, or by just any regular user who is either familiar with creating what is called 'FRX files', or otherwise using the WYSIWYG report editor).
saving the report in (eg) CSV format, using one of the typical hyperlinks to do so in a report.

These steps do not require any PHP coding.

Bonus: instead of CSV format, you also have an option to format it as either XML or JSON. For more details on that, refer to "How to add a link to the CSV download to my module page, for a report created with Forena?".

Alternative: not sure if it would fit your requirements, but you could also use the Feeds integration of Forena. In this case you'd install Forena in your new site, and use Forena to enable Feeds to just go get your data in your old site. Checkout the video tutorial about this topic (specific to this Feeds integration).

For an online demo (prior to installing/testing Forena), checkout these links:

Reporting samples, about data stored in some SQLite database, and including things like drill down reports, creating charts (using the PHP SVG Graph library), etc.
Forena Documentation, which you also get in your own site after installing the module).

Disclosure: I'm a co-maintainer (not owner ...) of this module,
I hope this does not violate the site's policy on self-promotion.


How do I create a download link knowing the uploaded file ID? I've a column in database containing the IDs of the files uploaded using a managed file form field.

How do I create a link to the uploaded file knowing its file ID?

EDIT :
The obvious solution doesn't work for me , i'm using another table where i put my Fids .

this is the warning i got everytime :
Notice: Trying to get property of non-object in Affichage_form() (line 188 of C:\wamp64\www\Gestion_tickets_licences\sites\all\modules\Recherche\Recherche.module). << 188 : $uri= $file->uri; >>

Solution : Thank you for you help .
my solution for my problem is , Once I upload the file , I create the url. Instead of saving Fid , I save the url , It worked .For the download link , I used Alen syntax and it worked great .

First, load the file using file_load(FILE_ID) and get URI like below:

$file = file_load(1);
$uri = $file->uri;

After that generate link using file_create_url();

$url = file_create_url($uri);

Get file name also:

$filename  = $file->filename;

And finally, create a link using l().

l(t($filename), $url);

and output will be like picture-6.png


Database general error: 2006 MySQL server has gone away Recently I started getting an error every time I try and add a content no matter what type.  This is the error that shows up in the browser:

  Additional uncaught exception thrown while handling exception.

  Original
  PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT COUNT(cid) FROM {comment} WHERE status = :status; Array ( [:status] => 0 ) in comment_count_unpublished() (line 313 of /Applications/MAMP/htdocs/modules/comment/comment.module).

  Additional

  PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => php [:db_insert_placeholder_2] => %type: !message in %function (line %line of %file). [:db_insert_placeholder_3] => a:6:{s:5:"%type";s:12:"PDOException";s:8:"!message";s:154:"SQLSTATE[HY000]: General error: 2006 MySQL server has gone away: SELECT COUNT(cid) FROM {comment} WHERE status = :status; Array ( [:status] =&gt; 0 ) ";s:9:"%function";s:27:"comment_count_unpublished()";s:5:"%file";s:56:"/Applications/MAMP/htdocs/modules/comment/comment.module";s:5:"%line";i:313;s:14:"severity_level";i:3;} [:db_insert_placeholder_4] => 3 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => http://localhost:8888/?q=node%2Fadd%2Farcade-project&amp; [:db_insert_placeholder_7] => http://localhost:8888/ [:db_insert_placeholder_8] => 127.0.0.1 [:db_insert_placeholder_9] => 1338336955 ) in dblog_watchdog() (line 154 of /Applications/MAMP/htdocs/modules/dblog/dblog.module).

I also get the following error in my php error file:

  PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in /Applications/MAMP/htdocs/includes/database/database.inc:2136

  Stack trace:
  0 /Applications/MAMP/htdocs/includes/database/database.inc(2136): PDOStatement->execute(Array)
  1 /Applications/MAMP/htdocs/includes/database/database.inc(664): DatabaseStatementBase->execute(Array, Array)
  2 /Applications/MAMP/htdocs/includes/database/database.inc(2315): DatabaseConnection->query('SELECT expire, ...', Array, Array)
  3 /Applications/MAMP/htdocs/includes/lock.inc(167): db_query('SELECT expire, ...', Array)
  4 /Applications/MAMP/htdocs/includes/lock.inc(146): lock_may_be_available('theme_registry:...')
  5 /Applications/MAMP/htdocs/includes/theme.inc(447): lock_acquire('theme_registry:...')
  6 /Applications/MAMP/htdocs/includes/bootstrap.inc(427): ThemeRegistry->set(Array)
  7 [internal function]: DrupalCacheArray->__destruct()
  8 {main}
        thrown in /Applications/MAMP/htdocs/includes/database/database.inc on line 2136

I am having a little trouble deciphering these error messages. Could anyone help me understand what's going on here?

9 times out of 10 this error is caused by an insufficiently large max_allowed_packet setting in your MySQL server's my.cnf file.

The standard default for MAMP in my experience is 1M, which isn't usually enough for Drupal (especially considering the size of some of the cache strings it generates).

Try increasing that setting gradually to see if the error disappears. I'm sure a quick google search will tell you how to do that in MAMP.


Copy filefield image to different filefield field I am upgrading an older D6 site to D7. Way back we made the mistake of creating separate image fields for different content types. So instead of just creating a field field-image and reusing it, we have a field-event-image, a field-testimonial-image and so on (and a field-image). Well, besides the excess clutter, we need to create a view that shows a flexslide that sources nodes from multiple content types and it only allows one image field. So I would like to move all the images into the field-image field. I have seen a number of potential ways to achieve this result but no luck so far. Using migrate module is probably the most elegant, but seems over my head. VBO with Rules seems good and I have seen some examples but I get stuck creating the rule.

Any suggestions to my dilemma? Thanks

I fixed it by running SQL on the database directly through phpmyadmin.
First I added the destination field to the content type.
Then, I went into phpmyadmin and ran this: (change your field names as appropriate.

INSERT field_data_field_image SELECT * FROM field_data_field_event_image;

and

INSERT field_revision_field_image SELECT * FROM field_revision_field_event_image;

After it ran successfully, I went in and checked the content. All good. Then I was able to delete the old field. Problem solved! Thanks.


Smart way to compare drupal instance files with official release to search for modified files I was asked to update (just install new core and modules versions) a Drupal site that uses roughly 100 (yes: hundred) contributed modules. I suspect that some of these modules might have been modified, maybe including core.

I'm looking for a smart way that would allow me to utilize git (or some other tool) to automatically search for files that differ from the ones available in official release for specific module version (contributed or core).

I could use drush to dump installed modules names and versions or use some shell script to read that data from *.info files. Then I could use that to generate git commands. So in theory it is not that difficult. But that's just a theory :)

So any input on this would be helpful from people who did similar things. Any caveats? Maybe other approach or just some code examples?

Or maybe there is a Drupal module that can do this for me?

The Hacked! module is exactly what you're after:

  This module scans the currently installed Drupal, contributed modules
  and themes, re-downloads them and determines if they have been
  changed. Changes are marked clearly and if the diff module is
  installed then Hacked! will allow you to see the exact lines that have
  changed.


How to resolve an XMLReader warning produced by Wordpress Migrate module? I'm converting a Wordpress site to Drupal. To do so, I need to import a wordpress export file. But whenever I try to import my wordpress export file, I get this error:

Warning: XMLReader::open() [xmlreader.open]: Unable to open source data in WordPressBlog->__construct() (line 188 of /mnt/www/html/dev/docroot/sites/all/modules/wordpress_migrate/wordpress.inc).
Exception: Could not open XML file wordpress://blog.wordpress.2013-09-05.xml in WordPressBlog->__construct() (line 219 of /mnt/www/html/dev/docroot/sites/all/modules/wordpress_migrate/wordpress.inc)

As shown in the path names within the error mesages also (ie: 'wordpress_migrate'), I'm using the Wordpress Migrate module. For this module, only a 7.x version exists.
I'm not quite sure why it can't read the XML file. I've run the file through the xmllint command with no errors.
Can anyone help me with this?

I had the exact same error.  I uninstalled all the WordPress migrate and migrate modules (uninstalling migrate may not have been necessary), removed from site directory and then reinstalled.

I re-installed Migrate 7.x-2.6 and WordPress Migrate 7.x-2.3-beta2+4-dev.

After that the import worked.


How to have all the fields available in a display mode for content type D8 I'd like to be able to choose the date field or other fields that you can see in form display in 'custom display mode' for content types ?

How can I do that ?

Thank you.

You need to drag the items that you don't want to the disabled section. This works for both form display and front end display.

For your custom display mode, you should be able to select from each display mode:


Create views field template override for table style I have a view named studies that displays title, status. The status field should be "Active" or "Completed". This value is the result of comparing the timestamp of the date field that my content type has with the today timestamp. So I added the date field to my view as well, but choose to have it excluded from display. Then I created a global text field with the label "Status".

Then i tried taking my first steps into theming. What I need is to override the content of the Status field with either "Active" or "Completed" based on my code. I created a template called views-view-field--studies--nothing.tpl based on the suggestions of the Views theme information. The problem is that it doesn't matter what I write inside nothing gets displayed, not even just a simple <?php print $output."Hello World"; ?> (I did rescan the template files and Views sees my template, plus I flushed all caches)

My view right now has table style. I changed the style to unformatted list and voila the Hello World showed up! So am I messing around with the wrong template? Do I need to create a template for the table style of my view? Seems too excessive when I only need to override the content of one field.

What you are trying works fine for me under drupal6, so, I'd look at your theme information again and be perfecting sure that it is looking at the right theme when you switch styles from table to unformatted and so forth.  I did that once and had my views template file sitting in one theme and couldn't figure out why views wasn't picking it up in another :)


How to run a Drush command with the full site path? Im trying to get Drush working. When I type 'drush' into terminal I get a list of commands so I know its installed.

I dont have any path aliases set up yet so im trying to use the full path. When I type the following into terminal:

cd path-to-my-site drush dl views

I get this message:

unknown:omegav3 my-user-name$

Should the path-to-my-site be the base path? Im working locally with MAMP. I have different sites that arnt in the root folder so my local url for this site im trying to target is:

http://localhost:8888/omega/omegav3/

Your command should be like:

drush dl views

or:

drush dl views -r /path/to/site/root

To get help manual for commands run:

drush help

Please find better explanation for drush commands at GitHub.


How do I create a link to add a new entity form from the referenced entity I've created an entity (using Entity Construction Kit) that has an entity reference field referencing a node. I would like to create a link on that node to create a new entity. I want to do this on the node template file. I have looked into sandbox module Prepopulate Create Node Links but I'd rather just code it.

The entity_connect module will do that for you.


how to alter "other" field label or change the label name How to alter "other" field label or change the label name
Please see the image

Also,

How to constrain the sum of these responses to be 100?
Please see the image

For customizing the 'more items' see Issue #2953803: Allow multiple value elements item(s) label to be customized.

For 'How to constrain the sum of these responses to be 100?' you are going to have to write custom client-side and server-side validation code.


Programatically use search api I want to do something like this

    $index = search_api_index_load("node_index");
    $myQuery=new SearchApiQuery($index);
    $myQuery->condition('type', 'blog', '=');
    $data=$myQuery->execute();
    $results=$data['results'];
    print_r($results);

but for Drupal 8, using the search api. Is that possible?

$query = Index::load('my_index')->query();
$query->addCondition('search_api_language', $language);
$query->keys($search_string);
$query->range(0, 25);
$data = $query->execute();

Also I have a custom parsing function for the results:

function parse_results(array $results) {
$list = [];
  foreach ($results AS $item) {
    // The pattern is "entity:[entity_type]:[entity_id]:[language_code]".
    // For example "entity:node/1:en".
    $data = explode(':', $item->getId());
    $data = explode('/', $data[1]);
    $list[] = $data[1];
  }
  return $list;
}


How can i delete user profile picture in drupal 7? Is there a way that I can remove/delete user profile picture through programing? or How can i override existing image with my new one?

use code below in hook_user_delete($account)

// Load user by using user id
$user = user_load($uid);
// Get file id of profile photo
$fid = $user->picture->fid;
// Load the file object
$file = file_load($fid);
// delete profile photo from.
file_delete($file);
// Unset the image object (my case it's 'picture')
unset($user->picture);
// Save the user
user_save($user);


Can you use jQuery to display a view? I want to do something similar to views slideshow. The thing is my javascript is written already. I would like my javascript to be able to be integrated within the drupal framework from views. The JQuery just is a simple image slideshow like this one here.  I just would prefer that I could show all or specific view field content instead of putting in the url in the javascript the long way. I want these images to come directly from a content type. Can you show me how?

You could create a small module that will be called through ajax:

function MYMODULE_node_menu() {
    return array(//$items
        'MYMODULE/%' => array(
            'page callback' => 'MYMODULE_display_view',
            'page arguments' => array(1),
            'access callback' => TRUE,
            'type' => MENU_CALLBACK,
        )
    );
}
function MYMODULE_display_view($view_name) {
    // display your view depending on $view_name
   $view = views_get_view($view_name);
   $view->execute();
   echo $view->render();
}

Get a views html by making an ajax call using jQuery:

$(document).ready(function() {
   $.ajax('MYMODULE/YOUR_VIEW_NAME', {
           sucess:function(data) {
              // data will contain the html for your view
           }
   });
 });

You might find the following Drupal 7 Advanced Ajax helpful.


How to translate the description, and abstract metatag for the front page in a multilanguage site? I am using the metatag module. In admin/config/search/metatags I am controlling my metatags for my front page using Global:Front page. Here it is my configuration

How can I translate these metatags for other language. I can use tokens for the title but I don’t know how to translate the description, and abstract metatag.

Any solution for this?

My solution was to install and enable  the Translation table module. Then follow these steps

go to admin/config/regional/translate/translate
then filter by metatag and it will show all the metatags that you can translate.

That’s what it worked for me. If you have better solution please add it.


Create an author archive page with views I have two content types: article and author. The author content type has a bio, links to facebook and twitter etc. This author content type is connected to the article content type with an entity reference. I want to create a page that displays the author content at the top and then below that, a list of all the authors most recent articles.

I am trying to make a view block with a contextual filter to drop into the author page, but I cannot get it to work. I dont really understand views that well. Can anyone give me some pointers on what I need to do to set this up?

You'll want to create a view of articles and add a contextual filter for the node reference field.

How are you attaching the view to a node? Is it a views attachment? Is it a panel pane á la Page Manager? That will determine the specifics of how your view parses the argument out of the URL.


MailChimp + Drupal 8: How to install properly? (page could not be found) In order to install MailChimp in Drupal 8 I followed the instructions for the MailChimp Drupal module.

  Instructions for 8.x-1.x

  The 8.x-1.x release uses version 3.0 of the MailChimp API and bundles
  the library with the module. This is a temporary solution until the
  process for installing libraries via composer is finalized in Drupal
  8.

in admin/modules/install I added mailchimp 8.x-1.3
Checked that libraries is installed (Machine name: libraries; Version: 8.x-3.x-dev)
Enabled all four modules (mailchimp, mailchimp_campaign, mailchimp_lists, mailchimp_signup)

However, when trying to configure the module at admin/config/services/mailchimp the page could not be found.

How can I resolve this issue and where should I start looking?

PHP 7.1.6-nmm1
Drupal 8.4.0-dev

You should use Composer to fetch this module, as it has an external dependency noted in its composer.json file:

http://cgit.drupalcode.org/mailchimp/tree/composer.json

It seems to include an older version with the module, I'm not sure why, but the current version of Mailchimp API by Thinkshout looks to be 1.0.8. I don't see any installation notes. The module comes with 1.0.6... ?

Other than that, clear your caches and try to access the page again.


How to add a variable to a twig field template? On a node page I would like to add the node title to the output alongside another another field (the example field).

I have created a new field--field-example.html.twig but am unable to access the node title variable as it is not available in the field template.

I need to add the variables into the theme preprocess: themename.theme.

How do I add the variable in themename.theme and what would be the corresponding entry in the field--field-example.html.twig ?

Since you asked about passing the node title as a variable via the .theme file, you could use template_preprocess_field to do something like this:

  function themename_preprocess_field(&$variables, $hook) {
    if ($variables['element']['#field_name'] == 'field_example') {
      $variables['node_title'] = $variables['element']['#object']->getTitle();
    }
  }

then in your field--field-example.html.twig you could simply just use {{node_title}} to render the node title.

Also see 4k4's answer below.


How to change page CSS based on parent menu item? I'm building a fairly simple site, and I need to alter a background image based on what section the user is in. The main menu only has 2 levels. I'm unsure where I should hook into in order to be able to get the current section (i.e. the root menu item of the current page, see example below) so I can adjust the classes on the page. I was looking at this article as a possible solution, but I only want to alter CSS classes, and that seems like an awful lot of code for such a simple task.

Main Manu:
-- Section 1
   --- Page A
   --- Page B
   --- Page C
-- Section 2
   --- Page D
   --- Page E <- Active page, CSS class "section_2"
   --- Page F

If it is just additional classes you need, you can add additional and unique classes to menu items using the Menu CSS Names or Menu Attributes modules.

Or, you can effect the element of another DIV on hover using pure CSS like below...

HTML

Menu Item

Change This Background

CSS

#container {
    background:blue;
}

#menu-item:hover + #container {
    background:red;
}

See Fiddle here... Affect Another Div on Hover


How do I configure the Stock module in and know how many products are sold out of stock? I have installed the Stock module, but I don't know how to configure or include that to my product content type, nor do I know how to use it.

Do you have any idea or suggestion?

You can follow the below step:

Go to  Content management -> Content
Filter content for content type "Product"
Edit your product content
Click on "stock" link in top of page
Set the "Stock" and "Threshold" quantity and check "active" check-box save the form.

Edit:

Code snippets to display total and sold item from stock:

$output = '';

$array_sku = uc_product_get_models($node->nid, FALSE);

foreach ($array_sku as $sku) {
  $stock_level = uc_stock_level($sku);
  $stock_count = db_select('uc_order_products', 'up')->fields('up', array('nid'))->condition('up.model', $sku, '=')->execute()->rowCount();

  $total = $stock_level +  $stock_count;

  $output .= "
SKU:" . $sku . " Total :" . $total . ", Sold out:" . $stock_count . "
";

}

print $output;

Kindly see that above code will be check stock level for each different SKU of the product. If there is attribute of the product and each attribute has different SKU, then it will display the stock for each sKU of the product.

You can add this code in node--product.tpl.php file in your theme directory.


how to make a custom entity multilingual I made a custom entity (ty drupal console). but i would also like to make this entity translatable. I enabled all 4 multilingual core modules but i don't see the "translate" tab in my entity nor can i enable translation form the "admin/config/regional/content-language" page (it says N/A), but i can show the language selector which as no real effect.

is it possible to translate custom entity, if so, how? what am i missing?

You need the translatable = TRUE line in your @ContentEntityType annotation. You also need the setTranslatable(TRUE) line in your BaseFieldDefinition::create fields.


Commerce - Discount on three or more products in order I am moving my site from Ubercart to Commerce and would like to replicate a discount that I have set up in Ubercart.
I have an Ubercart coupon that automatically adjusts the price for a product if there are three or more applicable products in the order.
I have spent all day looking at Commerce Coupons and Commerce Discounts but have not found a way to do this yet
Is this possible?

You may want to look at these modules that provide some extra conditions:

Commerce Discount Extra provides a "Order has product(s) and quantity" condition that might match what you want.
Commerce Discount Product Quantity allows you to set up a discount based on the number of products in an order that belong to a category (taxonomy).


Configuring Modules in Install Profile I'm working on an install profile which brings in various modules and I was curious about the proper (or popular) convention for setting global variables  Right now I have two different ways of doing this:

In my settings.php file I set some variables directly in the $conf array:

  $conf['var'] = 'setting';

In the install function of my profile I set some variables using variable_set:

  variable_set('var', 'setting');

I recognize that the first one will permanently retain the setting until the php file is altered, while the other can be changed at any time.

Is there any popular opinion/convention on the method of setting these variables(in the context of using an install profile)?

Thanks!

In general using hook_install or hook_enable or a hook_update function in a module is prefered over hardcoding the value in settings.php of your drupal site.

Another option is to use the Configuration module or Features to encapsulate your database configuration to code to be enabled on the drupal website.


Redirect to a custom page in hook_init() I need to redirect users to a custom page using hook_init().

I have tried drupal_goto(), but it is not working fine. By using drupal_goto(), it is looping and it is not giving the correct result.

So, for that, I have checked a condition using drupal_get_destination(). But, it is not working correctly.

Here is the code:

$destination = drupal_get_destination();

foreach($compatible_arr as $key => $val) {
if(isset($browser_arr[$key])) {
    if(version_compare($browser_arr[$key], $val, '<')) {
        //print strpos($destination['destination'], 'browser-limitations');
        if(strpos($destination['destination'], 'browser-limitations') == '') {
            drupal_goto($base_url.'/browser-limitations/', array('query' => array('version' => $val)));
        }
    }
}

I am using this condition in order to check the browser version using the Mobile Detect module. But, I am not getting the correct result. Is it safe to use drupal_goto() in hook_init()? Or else, is there any function to use it?

If you define the redirect in hook_init, then it would work for non cached pages. But in case of Cached pages it would not work.

So it is recommended to use hook_boot instead of hook_init.

hook_boot would help you in redirecting for cached pages as well.


What happened to Drupal's performance? I just installed Drupal 7 again on my cheap shared host. The installation went fine... I copied the 1098 files via FTP and installed it within 2 minutes. The standard installation (with all modules in the core) took about 5-10 seconds. After installing, the site runs well. It's a cheap hosting, so sometimes it's a little slow, but it's acceptable.

Yesterday, I've installed the new Drupal 8 (which is why I installed Drupal 7 today to compare). The first thing I noticed are the number of files: 12327. I understand modules like Views are included in the core now, but an increase of the number of files of over 10 times seems a little odd to me.Is there another reason for this?

Once I copied all files, I've tried to install Drupal 8. What a nightmare. The installation page takes up to 20 seconds to load. When I want to start the installation, I'm getting a notice OPcache is not enabled in PHP. Is this the reason for the slowness? Is there an alternative available?

Continuing the installation, I'm getting random errors. Searching for them on Google doesn't help getting me more information. Something about a fixed bug months ago, that's all I could find. I had to restart 3 times before the installation succeeded.

The biggest issue is the performance. Installing all these modules during the default installation took about 5-10 seconds in Drupal 7. It took about 20-30 minutes in Drupal 8. Okay, some more modules are included now, but this seems very odd. As I had to retry 3 times, it took me about 2 hours just to install Drupal 8. After installation, it was unusable slow, so I had to remove the whole installation.

I'm wondering if someone knows more about this issue. Does Drupal 8 require like 20 times more resources than Drupal 7 to run properly? Or is all of this because of the missing OPcache? Am I the only one with this issue?

Any advice would be welcome as I'd like to try the new features. Drupal 7 runs perfect on my cheap hosting, but Drupal 8 is a real nightmare.

I'm not sure what other technical information might to relevant to find/resolve this issue.

D8 requires more resources and yes, you should have hosting with opcache enabled, which is included by default in PHP 5.5.

Drupal 8 has so many files because it includes symfony and other projects and everything is a class.

FTP is a very bad idea for D8 and web in general in 2015. Look for a better way to do web hosting.

That said, it should not take that long. I suggest you open a bug report  and provide as many details as you can about your specific PHP version, hoster, the errors that you had, ..


How can I show the root taxonomy term in a view field in Drupal 7? I have a view with a taxonomy term field called Location in Drupal 7 and I want to show the first / root level of the term hierarchy in each view item field, aka the Country level.

My Location field in not mandatory, so I also want to show items with no Location. Meaning that I should mark all my term relationships as not required.

I have tried using relationship to the taxonomy term, and to the parent of the taxonomy term. And then a parent filter on the parent of the taxonomy term with value = empty. By this way I managed to show the root level of my taxonomy field only, but not items with no Location. As trying to make my relationship on taxonomy term not required, throws an exception. I guess this is due to the fact that then it tries to find the parent of the term and if it the term is empty, it throws the exception.

Any suggestions on how could I show the root term (Country) and, at the same time, items with no Location?

In the 'Fields' section of the view add your taxonomy field (Location). Select the Formatter that you want and then in the settings of the field, in the fieldset 'Multiple field settings' change the 'Display' option from 'all' to '1'.

Enjoy


Query Drupal User Table for: date created < $today - '100000' I would like to select users from the Drupal users table where the date created was older than 1 day ago. Then delete those users. This code isn't correct but it will give you an idea of what I am trying to do I just don't know the right DB query. '

$users = db_select('user', 'created') //I know this is not the right DB query
$count = count($users);
if($count > 0){
  $users = user_load_multiple(array_keys($users['user']));
}
$today = getdate();
if ($users < $today - '100000' ) {
 user_delete($user->uid)
}

I am thinking about using user_load_multiple() to load the users in to an array to perform the delete action.

You can achieve this using EntityFieldQuery as shown below:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
  ->propertyCondition('created', strtotime("-1 day"), '<')
  ->propertyCondition('uid', array(0,1), 'NOT IN');
$result = $query->execute();
if(!empty($result)){
    user_delete_multiple(array_keys($result['user']));
}


Why does drupal use .yml and not officially recommended .yaml Per yaml page https://yaml.org/faq.html they recommend .yaml as file extension but I see drupal uses almost exclusively .yml, how so? And does adding .yaml to file extension even work for drupal 8 or will it be skipped?

Drupal uses '.yml' because Symfony uses '.yml'

This was discussed in https://www.drupal.org/project/drupal/issues/2091669

I am assuming that '.yaml' would not work, but I haven't tried it. For consistency reasons it is best to stick to '.yml'.

EDIT: Looks like Symfony has started recommending '.yaml' from version 4.0. Can be seen by comparing this page https://symfony.com/doc/4.0/routing.html with the 3.4 version


table content_type_answer show to merge it with node table I have a {content_type_answers} and this table doesn't has a title row, how can i merge it with {node} to get node titles?

$result = db_query("SELECT {node}.title, {node}.nid FROM {content_type_answers} cta, node WHERE {cta}.nid = {node}.nid");
while($node = db_fetch_object($result) {
    $nodes[] = array($node->title, $node->nid);
}

Question: how can i select {node}.title from table {content_type_answers} if in this table no title row at all?

$q = db_query("
SELECT node.title, node.nid
FROM content_type_answers cta, node
WHERE cta.nid = node.nid");
    while ($r = db_fetch_array($q)) {
      $rows[] = $r;
    }
    print theme('table', $header, $rows);


Possible to build Relation Type between two specific Content Types? I have created Content Types: Person, Story, Company, Series, Article, Basic Page, plus other content types in the Node bundle.

I want the Relation Type between Person and Story only (i.e. "is author of", "authored by") but all online instructions I read say that the Relation Type should be between bundles. However, that scope is too wide.

The display page shows
Entity Collector
Relation Type "is author of"
Select an entity "" (is null)

This was a question of interpretation of what I could see. What I couldn't see was that the Relation Type had been created, and I did not know how the "relations" were populated. Watching Johann Falk's screencast another time showed me how to do this.


How can I pass a long javascript string to PHP hook_menu in Drupal? On mysite/build-order I have a long order code that I'm assembling using Javacsript and sending via _GET in the URL to a hook_menu page for processing.

It can be as long as this (or longer), and am sending it to the create-order page like this:

<script type="text/javascript">
    //...building code
    var orderCode = "sku:OR-4x4>qty:2>prc:55.00>nfo:OR-4x4,sku:CVR>qty:1>prc:50>nfo:OR-4x4,sku:PF>qty:15>prc:2>nfo:OR-4x4 (sdfsdfg),sku:EM>qty:2>prc:12.95>nfo:OR-4x4 (sdfsdfg),sku:SC>prc:25>qty:4>nfo:Some description,sku:DB>qty:10>prc:4>nfo:Some description,sku:ES>qty:10>prc:3>nfo:BlahBlah,sku:OR-4x4>qty:2>prc:55.00>nfo:OR-4x4,sku:CVR>qty:1>prc:50>nfo:OR-4x4,sku:PF>qty:15>prc:2>nfo:OR-4x4 (sdfsdfg),sku:EM>qty:2>prc:12.95>nfo:OR-4x4 (sdfsdfg),sku:SC>prc:25>qty:4>nfo:Some description,sku:DB>qty:10>prc:4>nfo:BlahBlah-visiondelimiter-Phasellus laoreet lorem vel dolor tempus vehicula. Curabitur blandit tempus ardua ridiculus sed magna. Quisque placerat facilisis egestas cillum dolore.-visiondelimiter-eventName";

    var url = '/create-order/' + orderCode;
    window.location.replace(url);
</script>

Ive implemented a hook_menu setup in my custom module called "create_order_menu" and it works fine.

function mymodule_create_order_menu($ordercode){

    // do stuff with $ordercode

}

It all works fine. The only problem is that the order code string passed through the URL can sometimes be twice as long and it trips a 404 Error in the mysite/create-order page. When I shorten the code, it works. When I lengthen it again, it breaks.

Is there a better way to send such a lengthy variable to my hook_menu page setup?

I would suggest that you consider some pretty substantial changes to how you're doing things.

I would recommend using an AJAX request, probably with POST rather than GET,  and don't try to do the redirect.   Just update the interface with a "success" message for the user.


Blank pages or wsod on a recently migrated site to a godaddy server only after logging in Just recently I finished my friend's site on my local wamp server. Looks great on that server. Now I tried to migrate the site to a Godaddy shared hosting account. I was able to get it all setup with the database up to date and everything, but the second I log in the the backend of Drupal, it white screens. Again tried a different browser, the site came up fine until I logged into the admin again. At this point I can't get any page to load, not even the home page. I can delete my cookies in the browser to log myself out but that's about it. So stumped its not even funny...

Check the official Drupal page for "white screen of death" (WSOD), you will useful guidance to help you to find the problem.

As my suggestion, enable temporaly the error report for php, adding on the index.php the following lines:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

Another thing that you could do is to go to admin page of your Godaddy shared hosting account and enable the option error.

A last thing, check if you have copied the .htaccess file too on the directory of the web hosting server.


Upload and Save an Image in the Server Im currently developing a module that must have a capability to browse/select and upload an image to the server.

function myid_user_page_form(){

    $form = array();

    $form['id']['myphoto'] = array(
        '#type' => 'item',
        '#markup' => '
'
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Save',
        '#attributes' => array(
            'id' => 'myid_save',
        ),
        '#submit' => array('formsave_action'),
    );
    return $form;
}

function formsave_action($form,&$form_state) {

}

How will I upload an image(#img_myphoto) to my server?

Try to implement following code

function myid_user_page_form(){
$form = array();
$form['myphoto'] = array(
  '#type' => 'managed_file',
  '#title' => 'File Upload',
  '#upload_validators' => array('file_validate_extensions' => array('png gif jpg jpeg')),
  '#upload_location' => 'public://my-folder/'
   );

$form['submit'] = array(
 '#type' => 'submit',
 '#value' => 'Save',
 '#attributes' => array('id' => 'myid_save'),
 '#submit' => array('formsave_action'),
 );
 return $form;
}

function formsave_action($form,&$form_state) {
    $file = file_load($form_state['values']['myphoto']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
}


How to apply an image style based on a condition (a date for ex.)? I'm looking for a way to apply a grayscale image style to a content type image field when certain conditions are met. A date is reached (date field) for example

Can the rules modules do this ?

Thanks for the suggestions & ideas

Yes you can do it with rules module with the help of Field formatter conditions module

  Adds conditions to field formatters. Configuration happens on the
  "Manage Display" screens of every entity type on a per field basis
  when clicking on the cogwheel on the right.

Supports

Rules
Field API fields
Display Suite fields (only branch 2)

Simple conditions and actions

Hide source field when target field is empty.
Hide source field when target field is not empty.
Hide source field when current user has specific roles.
Hide source field on specific pages.
Hide source field when target field contains a specific string.
Hide source field when target field doesn't contain a specific string.
Hide link field if title is empty.
Hide date field if from/to has expired.

Rules actions

Hide a field.
Change image style.

Rules should always be a 'A field is rendered' event before they can be selected in the conditions dropdown on the "Manage Display" screens per field.


unable to get custom service to return result using services module I'm learning about web services and implementing it in drupal 6 and am trying to use Services module with its REST server for implementing a web service to add a user.

Since there is an existing functionality for all CRUD operation for users, I am trying to implement my custom code to register a user by using a HTTP POST of the respective data using REST as a part of the challenge. I implemented custom user resource in my module (awesomeness.module) and got it to show up in the list of resources with the respective operation (Create).

/**
 * Implements hook_services_resources().
 */
function awesomeness_services_resources() {
  return array(
    'awesome_registrant' => array(
      'operations' => array(
        'create' => array(
          'file' => array('type' => 'inc', 'module' => 'awesomeness'),
          'callback' => '_create_registrant_from_awesomeness',
          'help' => 'Creates or updates user from the
                     json data initiated by the Awesomeness request.',
          'access callback' => '_create_registrant_from_awesomeness_permissions',
          'access arguments' => array('dummy'),
          'access callback file' => array('type' => 'inc', 'module' => 'awesomeness'),
          'args' => array(
            array(
              'name' => 'user_data',
              'type' => 'string',
              'description' => 'The json data of User posted
                                by Awesomeness to register information.',
              'optional' => FALSE,
              'source' => 'data',
            ),
          ),
        ),
      ),
    ),
  );
}

The corresponding callbacks for the request and access in awesomeness.inc are as below

/**
 * Callback function to create or registrant from the web service request
 */
function _create_registrant_from_awesomeness($user_data) {
  watchdog('AwesomeWebservice', "I am called");
  $user_info = var_export($user_data, TRUE);
  watchdog('AwesomeWebservice', $user_info);
  return "Is called";
}

/**
 * Access callback for the registration Web service.
 */
function _create_registrant_from_awesomeness_permissions($access = TRUE) {
  // any logic on access restriction goes here, currently
  // setting true to check that calls can be made as an anonymous user
  return TRUE;
}

I created an endpoint and enabled Create for awesome_registrant and made the POST request with POSTER add-on for firefox set the Content type as application/x-www-form-urlencoded
and the following json data in content body
{"username":"awesomeuser@kungfupandafan.com","password":"epicawesomeness"}.

However I merely get a response code of 200 and nothing more where I expect the callback to return "Is called".

Enabling the debug mode shows only the Server info object but not the controller or the data about the return value unlike the core services like node retrieve.

Also for sake of clarification application/x-www-form-urlencoded is enabled for the REST web server. Any help on what I might have missed or where I have erred would be greatly appreciated.

Finally figured it out and boy was it bad. The endpoint I was supposed to hit was http://mysite.com/myawesomeendpoint/awesomeregistrant but instead I hit http://mysite.com/myawesomeendpoint. Hope this helps some one.


How to assign a link or path to a button in drupalgap? I put a navbar in the footer and placed some buttons. The display is good, but I cannot find a way to assign the link to a button like usual. The node/123 in the  does not work.

/**
 * Implements hook_block_info().
 */
function footer_intrfc_block_info() {
  var blocks = {};
  blocks['footer_intrfc_block'] = {
    delta: 'footer_intrfc_block',
    module: 'footer_intrfc'
  };
  return blocks;
}

/**
 * Implements hook_block_view().
 */
function footer_intrfc_block_view(delta, region) {
  //var content = {};
  var content = '
';
  content += '
';
  content += '
Home
';
  content += '
Saved
';
  content += '
Sponsors
';
  content += '
Setup
';
  content += '

';
  if (delta == 'footer_intrfc_block') {
    content['my_out'] = {
      markup: ''
    };
  }
  return content;
}

The link of node will show "Error Loading Page". I wonder where I can set my link by path: 'node/123' like in setting.js

I also tried:

content += '
Saved
';

and

content += '
Saved
';

but they do not work.

Try this in your hook_block_view():

var content = '
';
content += theme('item_list', {
  items: [
    l('Home', '', { attributes: { 'data-icon': 'home' } }),
    l('Saved', 'node/1029', { attributes: { 'data-icon': 'action' } }),
    l('Sponsors', 'node/969', { attributes: { 'data-icon': 'star' } }),
    l('Setup', 'node/1021', { attributes: { 'data-icon': 'gear' } })
  ]
});
content += '
';
return content;

Whenever linking in DrupalGap, the key is to use the l() or bl() functions which will properly assemble a link or button link for you. Here's the docs page with more info: http://docs.drupalgap.org/7/Pages/Navigating_Pages


Drupal Multisite, same module name, different site We have a module that needs to be the same name, but its functionality will change for each site.

Is it an ok practice to put put them in sites/site1/modules/MODULE_NAME and sites/site2/modules/MODULE_NAME

Will this cause any problems with drupal if they have the same name, but are in different sites?

As long as they are in the individual sites' directories, the are only visible to the sites they are associated with. Should be no problem.


How to setup event registration and paypal payment? We have events and we take registrations for them. Entity Registration module is installed for that purpose and it's working great. Now, since those events are paid events, we want to implement PayPal payment method as well.

The problem is we need to combine the registration process and the paypal payment into one process. That said, user should click the button Register & pay and that should do 2 things:

Register the user for the event (this is already working as a part of Entity Reg module)
Redirect the user to PayPal payment gateway

Any suggestions on how to achieve this?

You should use Registration Commerce module. This module acts as a integration point between entity registration and drupal commerce enabling you to implement paid registration using entity register. Also use Commerce paypal for paypal integration with drupal commerce.


Product Variation Token to fetch field of Product Display (Commerce) I am currently trying to automate some stuff, including the product sku as new products are created. For this I am using the AutoSKU module together with Token.

The idea is that every product display has a Base SKU, which I want to define once per product display.

So when you add a new variation to that product display, I want AutoSKU to also fetch whatever string has been put into said Base SKU field, named field_device_sku .

Stuff like [commerce-product:field-device-sku] unfortunately does not work, for the field belongs to the product variation's parent product display.

Is there any way pulling this off without unnecessarily redefining the 'base SKU' inside every product variation?

TL;DR:
For pictures famously say more than 117 words, here an admin panel screeny which might make it clearer what I am talking about and struggling with:

Fetching the desired SKU of the coverage and texture is no issue thanks to taxonomy, but the base sku string I just cant figure how to get. I am starting to doubt it's even possible if it's not defined directly in the product variation.

Any help or hints would be highly appreciated!

although I solved this issue a while back just by applying the same Device term reference field on every variation form, maybe someone else happens to stumble upon this sometime:

just as I was messing with some rules yesterday, I found out about a token that deal with exactly this!
I just gave it a shot and it does exactly what I was looking for: refer to fields on the node that was used to create the variation.

the token that does this:

[commerce-product:field-product-node:0:

so, for example, the token in my case would look like this:

[commerce-product:field-product-node:0:field-device-name:field-device-sku]

(note that the screenshot in my original post is outdated, as I now determine the device name and SKU via a taxonomy term reference field-device-name)

keep in mind!:
although this may keep you from having to include the same field on the product variation, I reckon this is less reliable. you may run into trouble, if you happen to create (or edit!) a product variation from a different node that does not have the reference field (or has other input). note that even when editing an already existing product, the SKU will be re-generated on submit. so make sure you only edit the product from within the original node (or any node that has the same field with the same value), if you dont want the value of the token-generated field to change.

however, I could be wrong and it may be just as reliable, if the field-product-node:0 always references to the same node on which the variation was originally created, regardless of where you edit it later on. – someone will have to test this (and preferably report back) if he/she is interested in the exact behavior of this node reference token.
if anyone knows the answer, I would be interested in hearing how this behaves exactly. but since I'm sticking with the extra field in the variation, I do not rely on this method now.

hope this helps someone else in the future. (: