Programmatically override permissions in Drupal 6 I'd like to know if there's any way to programmatically override Drupal's permissions defined in admin/user/permission.

What I've managed so far is to block a user's certain action.
However, if a user is not permitted to perform an action (eg. "create custom_type content") and my module's access callback for this action returns TRUE the result is a white page. No PHP error, warning, or log entry. If FALSE is returned, I get an access denied page, as expected.

The method I used to implement custom permission is through hook_menu_alter(). Specifically, something like this (a common one for Drupal 6):

function mymodule_menu_alter(&$items) {
  $old_access_callback = $items['node/%node']['access callback'];
  $old_access_callback_add_customContent = $items['node/add/custom_type']['access callback'];

  $items['node/%node']['access callback'] = '_custom_node_access';
  $items['node/%node']['access arguments'] = array(1, $old_access_callback);

  $items['node/add/customContent']['access callback'] = '_custom_node_access';
  $items['node/add/customContent']['access arguments'] = array(1, $old_access_callback_add_customContent);
}

function _custom_node_access($node, $old_access_callback = "node_access"){
  //check if user has permission to view the node object
  //or add new content and return TRUE or FALSE
}

Note that with 'node/%node' item, everything works as expected.
When _custom_node_access() returns TRUE for a user that have no permissions to perform the certain action (add), I get a WSD.
One way I found to avoid this behavior is to return my calculated result && user_access("create custom_type content") so that I can, at least, get an access denied page.
Do you have any suggestion for this behavior?

Finally, _custom_node_access() seems to run more than one time every time the '/node/add/customContent' path is visited. Is there any particular reason for this?

It's been only few months since I started using Drupal so it's very likely that I'm missing something about permission...

There is a way to override programmatically drupal's permissions defined in admin/user/permission. Example:

<?php

function set_permission($rid, $permission) {
  $result = db_result(db_query("SELECT perm FROM {permission} WHERE rid = %d", $rid));
  if (is_array($result)) {
    $permissions = array_flip(explode(', ', $result));
  } else {
    $permissions = array();
  }
  $permissions[$permission] = true;
  db_query("DELETE FROM {permission} WHERE rid = %d", $rid);
  db_query(
    "INSERT INTO {permission} (rid, perm) VALUES (%d, '%s')",
    $rid,
    join(', ', array_keys($permissions))
  );
}

function unset_permission($rid, $permission) {
  $result = db_result(db_query("SELECT perm FROM {permission} WHERE rid = %d", $rid));
  if (is_array($result)) {
    $permissions = array_flip(explode(', ', $result));
  } else {
    $permissions = array();
  }
  unset($permissions[$permission]);
  db_query("DELETE FROM {permission} WHERE rid = %d", $rid);
  db_query(
    "INSERT INTO permission (rid, perm) VALUES (%d, '%s')",
    $rid,
    join(', ', array_keys($permissions))
  );
}


Restrict users from creating certain title I want to restrict the users from creating contents with certain title. I require the following functionality.

Example :

Prevent users from creating a content with title, say ABCD
Prevent users from creating a content which has the words, say ABCD in the title.

Is there a module for this purpose. I'm new to drupal and I searched drupal.org but couldn't find a module. Thanks in advance

I would look into using a combination of automatic nodetitles, field_validation and clientside validation. Basically once you have those three installed you can create a new text field on your content type which you will use as the title. In the validation settings for that field you can then set it up to not accept certain rules (see this post). Under the edit section of the content type you can set auto nodetitles to use your new field (and hide the title field) as your title.


Different aspect on different browsers I'm using Drupal 7, Webform module, and Bootstrap Sub-Theme.

I'm facing a browser problem and an admin/end-user problem.

As a French speaker I would like to have my error messages in French.

In Safari (as admin), it shows errors in red box as in this example:

This is my result in Chrome (as admin):

And this is my result in Firefox (as anonymous):

Chrome (as admin) is working with translation automatically (as shown in the example above), but not Firefox (as end-user).

Safari and Chrome (as admin) use a different way to display errors.
Safari got red box for every errors.

Chrome uses a red box just for web form validation (module) errors.

I would like to have errors in French and in red box for end-user as well.

End-user have to answer a Captcha.

Any suggestions to resolve these issues?

Even though you didn't mention it, this is clearly a multilingual site. Which implies that "language detection" is involved (to decide each time in which language a page (or webform) needs to be displayed.

Your problem related to the usage of French or English language might be because of the "language detection" configuration.

So check this configuration via Configuration -> Languages -> detection and selection: experiment a bit with the correct order that should be used. Often times, this should be changed to something like 'URL, Default, User', and not something like 'Default, URL, User' (which I assume you're currently using, and which might explain the difference in the language used in different browsers).

The browser differences to display the errors (red boxes, etc) might be some browser dependency and/or something in your sub-theme (custom or not?). With the few details provided it is hard to tell what might help to resolve that part of your question. I recommend you move that part to a different (new) question, or enhance your question to provide more details about the sub-theme.


Webfrom Validation on textfiled when using default value I am having a problem where I need to use the default value of a text field to initially populate the from visually. Unfortunately after doing this the field validates as if it has been filled out by a user.
I am attempting to do a custom validation function to check against the default value of the field. So if the field has its default value to still validate as a mandatory field normally would.

The following is my attempt to do this. Am I going in the right direction?

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

    if ($form_id == 'webform_client_form_6'){
       //kpr($form);
        $form['#validate'][] = 'MY_MODULE_validate_form';
    }

}

function MY_MODULE_validate_form($form,&$form_state){
if ($form_state['submitted']['full_name']['#default_value'] == "Full Name") {
    form_set_error('full_name', t('You Must enter your full name'));
    }

}

Any help is much appreciated.

Sorry that this isnt a direct answer to your question, but it seems to me to be bad practice to use a default value in an input field and then disregard it as a submission. Would a placeholder not  be more appropriate for your requirements?
You could even style the placeholder to look like form input via CSS


Isn't it possible to have multiple buttons  along with a submit button? I have a simple Drupal 7 form, with 3 dropdown select lists and a submission button. I want to add another button to the form which does some function (but not submitting the form). I want to bypass the validation part for the form and directly run the submission handler of that button.

The button I am using is the following one.

$form['my_fieldset']['click'] = array(
  '#type' => 'button',
  '#value' => 'click me',
  '#limit_validation_errors' => array(),
  '#executes_submit_callback' => FALSE,
  '#submit' => array('my_module_click_submit'),
);

FYI, all the select lists have #required=>TRUE, and #type=>'submit' for the button also doesn't work.

When I click it, it shows the error about the fields being required. How can I avoid that error, avoid validation handlers are run, and just run the code in my_module_click_submit()?

Also, I dont know why, but even if I fill the entire form and then click this button, the page just gets refreshed and my_module_click_submit() does NOT run. What's wrong?

I haven't put anything fancy inside my_module_click_submit(); I just wanted to see if it works. The submission handler I am trying is the following one.

function my_module_click_submit($form,&$form_state) {
  drupal_set_message('Click me button is clicked');
}

Jaypan gave me the answer.

  Required checks happen irregardless of validation - they happen before any other validation even occurs.
  You cannot skip the default _validation() function, it is always executed
  When you choose limit_validation_errors(), anything that is not part of that array is not submitted.

  As such, you will want to explicitly declare your submit and validate functions for the original submit button, and leave the second button as-is, using the default submit and validate functions:

function some_form($form, &$form_state) {
  // Form definition not shown.
  $form['submit1'] = array(
    '#type' => 'submit',
    '#value' => t('Submit 1'),
    '#validate' => array('my_explicit_validate'),
    '#submit' => array('my_explicit_submit'),
  );

  $form['submit2'] = array(
    '#type' => 'submit',
    '#value' => t('Submit 2'),
  );

  return $form;
}

// my_form_validate is not created, since we don't want to validate the second submit button, but we do want the submit function.
function my_form_submit($form, &$form_state) {
  // You need to check which submit button was pushed, as this function
  // will be run for both buttons, but you only want do something if it was the
  // secondbutton.
  if($form_state['values']['op'] == $form_state['values']['submit2']) {
    // Second submit button's submit function.
  }
}

function my_explicit_validate($form, &$form_state) {
  // Validation for the first submit button.
}

function my_explicit_submit($form, &$form_state) {
  // First submit button's submit function.
}

  To deal with your required issue, you will need to not set #required => TRUE for the elements, and check them manually in your validation function (the function explicitly declared for the first button). If you want to have the required marks, I think you can manually add them to the element title, or you can override the theme function for those elements and manually add them there.


How do I create a simple checkbox in a content entity? I just want a boolean checkbox with a label beside it. How do I do it?

Use type boolean_checkbox and display_label:

$fields[$open] = BaseFieldDefinition::create('boolean')
    ->setLabel(t("My Checkbox Field"))
    ->setDisplayOptions('form', array(
      'type' => 'boolean_checkbox',
      'settings' => array(
        'display_label' => TRUE,
      ),
      'weight' => '0',
    ))
    ->setDisplayConfigurable('form', TRUE);


Little customization to gratis theme I am using the Gratis theme, but there is a little problem.

Here is the screen shot of the block region demonstration:

Yellow are the regions. I want to make the 1,2,3 marked area into one top nav where I have logo, main menu and other links. How to do that?

The main menu (third party system) is a different area. Say 4th area. Not concerned with that.

Here is the page.tpl code for these top 3 areas

`

  <?php if ($page['top_links']): ?>

      <div class="l-top-wrapper l-setwidth" <?php if (!empty($set_width)) : print 'style="max-width:' . $set_width . ';"' ; endif; ?>>

          <?php print render($page['top_links']); ?>

  <?php endif; ?>

    <header class="l-header l-setwidth" <?php if (!empty($set_width)) : print 'style="max-width:' . $set_width . ';"' ; endif; ?>>

      <?php if ($logo): ?>

          <a href="<?php print $front_page; ?>" title="<?php print $site_name; ?> » <?php print $site_slogan; ?>">
            <img id="logo-img" src="<?php print $logo; ?>" alt="<?php print $site_name; ?> » <?php print $site_slogan; ?>"/>

        <?php endif; ?>

      <?php if ($site_slogan || $site_name) : ?>

            <?php if ($site_name) : ?>

                <a href="<?php print $front_page; ?>">
                  <?php print $site_name; ?>

          <?php endif; ?>

              <?php if ($site_slogan) : ?>

<?php print $site_slogan; ?>

            <?php endif; ?>

        <?php endif; ?>

    <div class="l-setwidth" <?php if (!empty($set_width)) : print 'style="max-width:' . $set_width . ';"' ; endif; ?>>

      <?php if ($main_menu): ?>
        <?php print t('Show Navigation'); ?>

          <?php print t('Hide Navigation'); ?>

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

      <?php endif; ?>`

I installed the theme on my computer and those elements are not printed using regions (as you said), are printed using the template file (and that's because there are no blocks with them, they are printed directly in the template file - except the menu that is printed using $primary_nav variable).

So, if you want something like you said, you need to add that content in blocks. Or, if you only want to add them in the same area or div in the page, just move them in the template file (for example, move "#menu-wrapper" in the "#header-bar" div, and you will have them together).


How to fetch group name from query? I'm using Field group Module, I have created 3 groups with name & ID as given below:

Group Name    | Machine ID
Stake Holders | group_sh1
Trends        | group_td1
Organization  | group_org1

I want to retrieve the group name in a custom module. By using "ctools" I'm able to retrieve the id  of the group, but couldn't get name of the group. Please find the code below for your reference.

ctools_include('export');
$objects = ctools_export_load_object('field_group', 'conditions', array(
    'entity_type' => 'node',
    'bundle' => DIGITAL_IQ,
  ));

$object = array_shift($objects);
if ($object && isset($object->data)) {
  dpm(field_group_unpack($object)children);
}

  --Result---
  0 (String, 9 characters ) group_sh1
  1 (String, 9 characters ) group_td1
  2 (String, 10 characters ) group_org1

How can I retrieve the group name?

//Get the Field information.
$field = field_info_instance('node', 'field_business_challenge', DIGITAL_IQ);

//Obtain group of that field.
$field_group = field_get_field_group($field);

//Get the name of the group from the Lable Attribute.
dpm($field->Lable);

There you go, you have the group name.


How may I schedule when comments can be Opened and Closed? I've been tasked to set up a Q&A styled project where we invite an industry leader, subject matter expert (SME) to answer questions for hopeful students in the same field. The individual requesting this project is a fan of reddit's Ask-Me-Anything styled interviews. So, yes, that is a big driver of this project.

We'll have a period of a week where the students can ask questions and two weeks where the SME can respond to those questions. In the fourth week, both can further respond with follow up questions or expanded responses. After that, the conversation will be available as read-only archive with nothing new added. I'm thinking nested comments would be sufficient.

Can I tell Drupal to open and close comments on certain dates, or even use a date field of when comments should be closed?
I'm okay with either using a contributed module (I haven't found one), Rules (I've not used very much), or custom code (My default, but there are people much smarter than me who have probably already done this better).

That should be as simple as:

function MYMODULE_node_view($node, $view_mode, $langcode) {
  if (/* Your logic to determine that comments are closed here */) {
    $node->content['comments']['#access'] = FALSE;
  }
}

(it'll probably need to be tweaked for your exact requirements, have a look at what else lives in $node->content['comments'] if you want to hide the form/existing comments separately).


Acquia Dev Desktop MySQL database troubleshooting on Mac OSX 10.11 I changed the Acquia Dev Desktop configuration, then when Apache web server and MySQL were restarting MySQL never got back online.

I have enabled the debug option in Acquia Dev Desktop.
The logs don't show any clues:

/Applications/DevDesktop/piscript.log
/Applications/DevDesktop/mysql/data/mysql.err

Workaround

I am using the MAMP mysql in the meanwhile, it has this convenient shell script:

/Applications/MAMP/bin/startMysql.sh

Manually starting the MySQL server:

/Applications/DevDesktop/mysql/bin/mysqld --defaults-file=/Applications/DevDesktop/mysql/my.cnf

Viewing the log:

tail -50 /Applications/DevDesktop/mysql/data/mysql.err

If everything went right you should see the MySQL green dot in the Acquia Dev Desktop GUI.


How to show comment via views? I have a content type nodes with comments. I need to show latest comment via views. For this I created a views its just showing me comment status. not comment.

To create a view of comments for a particular content type, what you have to do is create a new view and select Comments in 'Show' select list as shown in the pic :

After that go to Filter Creteria section and select the particular content type to which you want to show the comments. Also select the Comment: Approved(Yes) filter creteria.


How to show a user's friends with only the Views and Flag module? Is it possible to show user's friends on a user's page (located user/%/friends) with Views by using only Flag module? So without the Flag Friend module or any other modules.

Step 1:

Use the Flag module to create a flag labeled "Friend" (or something like that). Here is such Flag definition (in export format) you could use for it (just import it in your own site):

$flags = array();
// Exported flag: "Friend".
$flags['friend'] = array (
  'entity_type' => 'user',
  'title' => 'Friend',
  'global' => '0',
  'types' =>
  array (
  ),
  'flag_short' => 'Friend',
  'flag_long' => 'Mark as friend',
  'flag_message' => 'User marked as friend',
  'unflag_short' => 'Unfriend',
  'unflag_long' => 'Remove as friend',
  'unflag_message' => 'User removed as friend',
  'unflag_denied_text' => '',
  'link_type' => 'toggle',
  'weight' => 0,
  'show_in_links' =>
  array (
    'full' => 'full',
  ),
  'show_as_field' => 0,
  'show_on_form' => 0,
  'access_author' => '',
  'show_contextual_link' => 0,
  'show_on_profile' => 1,
  'access_uid' => 'others',
  'api_version' => 3,
);
return $flags;

Step 2:

Use the Views module to create a view of users that flagged other users with that "Friend" flag.  Here is such view (in export format) you could use for it (just import it in your own site):

$view = new view();
$view->name = 'my_friends';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'My friends';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Friends';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access user profiles';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
/* Relationship: Flags: friend */
$handler->display->display_options['relationships']['flag_content_rel']['id'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['table'] = 'users';
$handler->display->display_options['relationships']['flag_content_rel']['field'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['flag'] = 'friend';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Field: User: Last login */
$handler->display->display_options['fields']['login']['id'] = 'login';
$handler->display->display_options['fields']['login']['table'] = 'users';
$handler->display->display_options['fields']['login']['field'] = 'login';
$handler->display->display_options['fields']['login']['date_format'] = 'long';
$handler->display->display_options['fields']['login']['second_date_format'] = 'long';
/* Field: User: Uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'users';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
/* Field: Flags: Flagged time */
$handler->display->display_options['fields']['timestamp']['id'] = 'timestamp';
$handler->display->display_options['fields']['timestamp']['table'] = 'flagging';
$handler->display->display_options['fields']['timestamp']['field'] = 'timestamp';
$handler->display->display_options['fields']['timestamp']['relationship'] = 'flag_content_rel';
$handler->display->display_options['fields']['timestamp']['date_format'] = 'long';
$handler->display->display_options['fields']['timestamp']['second_date_format'] = 'long';
/* Sort criterion: User: Created date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'users';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: User: Active */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'users';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'user/%/friends';
$handler->display->display_options['menu']['type'] = 'tab';
$handler->display->display_options['menu']['title'] = 'Friends';
$handler->display->display_options['menu']['description'] = 'Users marked as friends';
$handler->display->display_options['menu']['weight'] = '9';
$handler->display->display_options['menu']['name'] = 'user-menu';
$handler->display->display_options['menu']['context'] = 0;
$handler->display->display_options['menu']['context_only_inline'] = 0;

Result

After you enable the view, the result of it is that it'll show a tabular list of users, via path user/%/friends, and it will add a "Friends" tab on the user profile page (also).

Here is a sample of such table:

Name           ! Last login                  ! Uid
---------------+-----------------------------+----
Dries.Buytaert ! Monday, May 2, 2016 - 18:19 ! 19
Demo.User      ! Friday, May 6, 2016 - 12:16 ! 8


Describing an Entity Reference relationship I'm wondering how to describe, or add extra information to a Entity Reference relationship between two content types.

I have 'event' and 'people' content types. An event can have many people, and each person can be an either an organizer, presenter, facilitator, etc.

How can I model this relationship? Do I need to have an Entity Reference field for each type of relationship, or can I add the type of relationship as a parameter of a single Entity Reference?

Thanks!

If you want to stick with Entity Reference, you'll need to have a field for each type of relationship. ER relationships don't have the capacity for meta data.

If you can change, check out the Relation module.

  Relation is an API module and storage model for both simple and the most complex relations between entities. The module can handle both directional and symmetrical relations very well.

  Relations are entities and can therefore have fields. This makes Relation the most flexible and powerful relation model out there. (Still, using Relation with anything but the default SQL storage will not work in most cases.)

(emphasis mine). You could, for example, attach a field to the relation entity type, that linked to a vocabulary containing the event role.


How do I modify the result? Having an issue with HOOK_views_pre_render and HOOK_views_post_render, trying to alter the rendered output of the view. There are similar questions like: Hide view results with hook but I am not seeing the results as I am expecting under $view['result']

There is what looks like a full entity and not the markup that I'm expecting.

You can use HOOK_views_post_execute() and cycle through the results rows,  updating the row with something like:

        foreach ($viewExecutable->result as $key => $rr) {
          $title = $rr->_entity->getTitle();
          // update $title value...
          $viewExecutable->result[$key]->_entity->set('title', [['value' => $title]]);
        }


How to use Colorbox with external link? I have a site built with Drupal 8.3.7.
Modules 'Colorbox', 'Colorbox Load', 'Colorbox Inline' and 'NG Lightbox' are activated.
I can't make this kind of thing work:

giving that:

while it works perfectly in Drupal 7.
Any idea?

You could load external content replacing your href by

javascript:void jQuery.colorbox({html:''})

It will be something like:

<a href="javascript:void jQuery.colorbox({html:''})">colorbox-load external link


How to create html page via module drupal 7 I am new in Drupal. I have created  a form which saves the values to custom table how ever I want to display those items in a tabular format. Does any one know how  to create a custom page where I can display those items.

This is what I tried:
in module file

<?php $menu_items['user/campaigns/new_campaign'] = array(
        'title' => 'Campaigns',
        'type'=> MENU_CALLBACK,
        'page callback' => 'create_campaign_form2',
        'access arguments' => array('access content'),
        'file' => 'campaigns.create_campaign2.inc',
        'weight' => 1,
    ); ?>

in campaigns.create_campaign2.inc file:

<?php function create_campaign_form2()
{
    echo 'Some HTML here';

}
?>

But it displays only displays the text, the entire css is removed please let me know what should I do.
Sorry if the question is too basic.

Use Drupal's Form API. Basically your code will look like this:

<?php
    $menu_items['user/campaigns/new_campaign'] = array(
      'title' => 'Campaigns',
      'type'=> MENU_CALLBACK,
      'page callback' => 'drupal_get_form',
      'page arguments' => array('create_campaign_form2');
      'access arguments' => array('access content'),
      'file' => 'campaigns.create_campaign2.inc',
      'weight' => 1,
    );
?>

<?php
   $form = array();
   $form['selected'] = array(
     '#type' => 'select',
     '#title' => t('Selected'),
     '#options' => array(
        0 => t('No'),
        1 => t('Yes'),
     ),
     '#default_value' => 'Maybe',
     '#description' => t('Set this to Yes if you would like this category to be selected by default.'),
   );
   return $form;
?>

Notice the use of drupal_get_form() in the menu hook. This function takes the return value of create_campaign_form2, which it expects to be a PHP array, as an argument and uses that data to build the markup of the form.

This particular example will generate a form with only a select drop down. But check out the complete Form API reference for all (and there are A LOT) of the options and settings you have available to build your form. It might be intimidating at first, but the idea is quite simple: you create a PHP array that represents your form and then drupal_get_form() turns that array into a secure and well structured form. ALWAYS use the Form API to build forms in Drupal.


Editable webform fields in views I'm using drupal 7.41 and have used Webform for my leave applicaiton form and there are such approvals fields that I've displayed in views, I'd like to make it editable in views by checking multiple records and it can be approved on views list page, can anybody please suggest some hints?

function hook_views_post_execute(&$view) {
  // If there are more than 100 results, show a message that encourages the user
  // to change the filter settings.
  // (This action could be performed later in the execution process, but not
  // earlier.)
  if ($view->total_rows > 100) {
    drupal_set_message(t('You have more than 100 hits. Use the filter settings to narrow down your list.'));
  }
}


A PDF field open in a new window of Drupal I add a field which type is PDF. When I click the PDF file, I want the PDF file to open in a new window (using target="_blank").

How do I add such target="_blank" to the a label?

If you're looking for a quick fix for ALL pdf links on your site you could use a little bit of javascript to accomplish this as well.  This snippet finds all URLs ending in .pdf and sets the target attribute to be _blank (new window).

(function ($) {
    $(document).ready(function() {
        // Open PDF In New Window
        $('a[href$=".pdf"]').attr('target', '_blank');
    });

}(jQuery));

Since you're looking for just files of your field type you could certainly use a less generic selector, such as .field-name-field_pdf a[href$=".pdf"].  Best of luck!


RuntimeException when running drush commands in root folder I am setting up a local site for development on a ubuntu server 18.04 VM.
I pull our repo into my windows machine and then mount this onto the VM as a shared folder.
I run composer install and it finishes completely, but when I go to my site's docroot folder and run
drush st or drush cr, I get the following error message:
RuntimeException: Drush::$container is not initialized yet. \Drush::setContainer() must be called with a real container. in Drush\Drush::getContainer() (line 151 of /media/sf_anothercnas2/vendor/drush/drush/src/Drush.php).
Drush command terminated abnormally due to an unrecoverable error.

Drupal installation went through successfully. In my composer.json,
I have "drush/drush": "9.7.2"
Composer show confirms that the local drush version installed is 9.7.2 but when I run
drush --version, it returns 8.1.16

I still am not sure why I'm getting the RuntimeException, but I can work around this issue by running
vendor/drush/drush/drush st //or any other drush 9 commands


Using #states API with an image field as a control field On a form, is it possible to use #states to hide/show a field based on whether or not an image field has been filled in?

More specifically, I'd like to get this node form:

to only show the "Show featured image" checkbox if an image has been added. If it matters, I'm using the media browser widget for the image field.

I tried using #states, but it doesn't seem to work here. I had the following code in a hook_form_alter function, but adding an image didn't make field_image_show show up.

// Hide the "show featured image" field until a featured image is added.
if (isset($form['field_image_show'])) {
  $langcode = $form['field_image']['#language'];
  $form['field_image_show']['#states'] = array(
    'visible' => array(
      ':input[name="media[field_image_und_0]"]' => array('filled' => true),
    ),
  );
}

If it's not possible with #states, any idea how to handle it with custom JS? I tried the following JS, but it also didn't work.

$field_image_show = $('#edit-field-image-show');

var imageCheck = function() {
  if ($('#edit-field-image-und-0 .preview').is(':empty')) {
    $field_image_show.hide();
  }
  else {
    $field_image_show.show();
  }
}

// Check on initial page load.
imageCheck();

// Check when media browser does stuff.
// @nope This doesn't seem to actually ever fire.
$('#edit-field-image-und-0 input').change(function() {
  imageCheck();
});

You should be able to do it with #states just fine. Maybe double check your input name or try something a little different depending on what the html for that element looks like. This is the code I am using that works.

 $form['field_hero_image']['#states'] = array(
  'visible' => array(
    ':input[name="field_image[und][0][fid]"]' => array('empty' => true),
  ),
);

This causes it to only appear if there is no value for the input fid. Pertinent HTML:

<input type="hidden" name="field_image[und][0][fid]" value="1088">
<input type="hidden" name="field_image[und][0][display]" value="1">
<input type="hidden" name="field_image[und][0][width]" value="915">
<input type="hidden" name="field_image[und][0][height]" value="450">

Note:

'visible' => array(
    ':input[name="field_image[und][0][fid]"]' => array('value' => 0),
  ),

may work just as well (untested)


How to create hook for altering every node form? I tried:

mymodule_form_node_alter
mymodule_form_node_form_alter

and global hook:
function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form['#id'] == 'node-form') {
      #set message
  }
}

None from above works for me.
I need to create hook that invokes on every node form. if it possible.

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  // Do stuff.
}

It could be that it didn't work because you have to clear the cache after adding the hook.


Export a specific non-default database using drush sql-dump My Drupal 7 site connects to multiple databases using a $databases array like this:

$databases = [
  'default' => [
    'default' => [
      'database' => 'examplecom',
      'username' => 'example',
      'password' => 'sostrongpassword',
      'host' => '',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ],
  ],
  'nondefault' => [
    'default' => [
      'database' => 'notdefaultdb',
      'username' => 'notdefaultuser',
      'password' => 'notdefaultpass',
      'host' => '',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ],
  ],
];

Ideally I want to be able to do something like drush --database-key=nondefault sql-dump > myfile.sql but I don't see a way in drush to do that. Is it possible?

I tried creating a custom script to do this like:

drush_sql_bootstrap_further();
db_set_active('nondefault');
$sql = drush_sql_get_class();
return $sql->connect(FALSE);

And then calling that script with drush scr foo.php but the sql connect (or any other command) seem to work against the default database.

According to the Drush 8 docs, there is a --database=key option that does what you want.

I've verified it against a D8 site with multiple databases using the command:

drush @dev sql-dump --database="blog_import" > ~/tmp/blog_import.sql

The drush sql-cli command also has the same option so you should be able to import the dump using a command like:

drush @dev sql-cli --database="blog_import" < ~/tmp/blog_import.sql


Changing Pagination based on screen size Is it possible to change the amount pagination displays based on screen size? For example: I have a products page that I want to show 30 items on desktop, but on mobile I'd like it to only show 10 items.

I'm currently using the Loads More Views module, but that doesn't do what I need.

Thanks!

Short answer: No.

Long answer: The server doesn't know the screen size before it generates the HTML. The only way to do what you are suggesting would be to detect the screen size first, then redirect to one of two different views based on that.


How to add class to all forms automatically? I want to add .form class to all Drupal forms.  How can I add class to all forms by overriding theme function?

You can do something like this:

function MYMODULE_OR_THEME_form_alter(&$form, &$form_state, $form_id) {
  $form['#attributes']['class'][] = 'MY_CLASS';
}


How do I change drupal_core_path to /public instead of /web? I use Drupal VM and I have to change the folder from {{ drupal_composer_install_dir }}/web to {{ drupal_composer_install_dir }}/public.

When I do it and I run vagrant up, I get this error.

  An exception occurred during task execution. To see the full traceback, use -vvv.
  The error was: OSError: [Errno 2] No such file or directory: '/var/www/jb-inflatables/public'
  fatal: [jb-inflatables]: FAILED! => {"changed": false, "failed_when_result": true, "module_stderr": "Traceback (most recent call last):
  File \"/home/vagrant/.ansible/tmp/ansible-tmp-1560461183.6-73909259621121/AnsiballZ_command.py\", line 114, in <module>
  _ansiballz_main()
  File "/home/vagrant/.ansible/tmp/ansible-tmp-1560461183.6-73909259621121/AnsiballZ_command.py", line 106, in _ansiballz_main
  invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)
  File "/home/vagrant/.ansible/tmp/ansible-tmp-1560461183.6-73909259621121/AnsiballZ_command.py\", line 49, in invoke_module
  imp.load_module('main', mod, module, MOD_DESC)
  File "/tmp/ansible_command_payload_KaNSZF/main.py", line 327, in
  <module>
  File "/tmp/ansible_command_payload_KaNSZF/main.py", line 263, in main
  OSError: [Errno 2] No such file or directory: '/var/www/jb-inflatables/public', "module_stdout": "", "msg": "MODULE FAILURE See stdout/stderr for the exact error", "rc": 1

How do I have to change the config.yml file so that Drupal is installed in /public instead of /web?

You should be able to create a symbolic link to web called public.
ln -s web public
Your server will find the contents of web/ inside of public/ and vagrant will find what it needs in web.


Create a CSV file dump/feed whenever item of Content Type A is created I need to create a CSV dump/feed whenever a new item of "Content Type A" is created, with only that new item's info in the CSV. How can this be accomplished? For example, if 100 new items of "Content Type A" were created today, there would be 100 separate CSV files with the field values for each of those content items.

Thanks!

Look at Views Data Export. It can create a CSV from Node content.

It sounds like you need this to somehow be recurring over time ... this is a tall order and so I wont be providing much code, but will outline a possible solution:

Implement hook_cron_queue_info(). This is a cron task that runs off of a custom Queue. You can insert a NID every time a node is created into a custom queue you've created named MyCSVQueue. Every time a node is created it gets added to this queue -- when you process the queue you create individual csv files.
Use either hook_node_insert or Rules to place the NID into the work queue.
In your queue worker function you pass the NID to a custom view that uses a contextual filter to load the NID. Or, you may be able to use node_export to create the CSV data as well. You then simply use the Drupal File API and file_save() to store the csv file somewhere in your public/private drupal filesystem.

If the default Cron options of drupal dont suite your needs look at Ultimate Cron

EDIT

A slightly easier alternative:

Use:

Use either hook_node_insert or Rules to run a snippet of custom PHP code. Simply create a file directory using the File API in public files as: %files/csv_node_exports/MM-DD-YYYY. Your snippet can create the directory if it doesnt exist today yet.
then just export the node data to a CSV file. You may or may not have a NID yet ... you could always update the filename after the fact to reflect the actual NID assigned to the node.


How do i dynamically import changing feed links within a feed I am uncertain how to approach this.

I have a feed with housing cases that is changing constantly. The feed consists of a case number and a feed link to that particular house. Each house has so much information that it has its own feed. Over time, more will be added and these feed links will change.

For each of these feed links, I want to create a single node. My issue is that I don't really see a solution on how to create these dynamic feeds from the one "main" feed.

It's going to be about 75-150 feeds within the "main" feed. So I have this list of changing feed links that I need to dynamically import.

This is in Drupal 8 and I have been trying to use the module feeds to accomplish this.

It sounds like you need a custom implementation that will dynamically add feed importers based on a particular "Master feed import".

Personally I would do this with the migrate API instead of feeds as it gives you much higher flexibility for data manipulation and queue control for large datasets.


How do I change the output of theme_comment_submitted()? How to change the default theme of comment_submitted in drupal?

Input:

$variables['submitted'] = theme('comment_submitted', $comment);

Output

My expected result is

To print the Name in first and time in second.
Should not truncate.

How can this be done?

Add a function in your template.php located in your theme's directory.

function phptemplate_comment_submitted($comment){
  return t('Submitted on @datetime by !username.',
    array(
      '!username' => theme('username', $comment),
      '@datetime' => format_date($comment->timestamp)
    ));
}


Syntax for getting plain field value in computed field I have a couple of simple computed fields that combine other fields (such as first name and last name) but I'm not getting the right values from the fields. I sometimes get only the first letter of a text field (maybe just on the Title field), and when I call a longtext field I'm getting all the HTML markup when I really only want the plain text version of the field.

Here's an example where I'm trying to combine a pile of fields for purposes of searching them from one box:

$omnisearch = $entity->title[LANGUAGE_NONE][0]['value']."
".$entity->body[LANGUAGE_NONE][0]['value']."
".$entity->field_prerequisites[LANGUAGE_NONE][0]['value']."
".$entity->field_keywords[LANGUAGE_NONE][0]['value']."
".$entity->field_teachers[LANGUAGE_NONE][0]['value']."
".$entity->field_organizing_center[LANGUAGE_NONE][0]['value']."
".$entity->field_location[LANGUAGE_NONE][0]['value'];
$entity_field[0]['value'] = $omnisearch;

So is there a better parameter than 'value' to pull the plain/sanitized text from the field? And why am I only getting the first character of the title? I only theoretically grok arrays, so the answer may be obvious to others. Thanks for your help!

I'd suggest you to start by understanding the structure of your entity. You could do something like
<?php print_r($entity); ?>
 to print on screen your entity object and understand how to reference each one of its fields.

You'll discover that you could get your title just by using $entity->title (in your example you are getting the first letter because you are treating it as an array).  You could also find that not all your fields might be have by the 'value' key.

Once you do that, you could get the fields values using field_get_items(). A basic example:

$items = field_get_items('node', $entity, 'field_keywords', $entity->language);
$item = array_shift($items);
$keywords = $item['value'];

And maybe you could take it one step further and wrap that in a reusable function:

/**
 * Get a node field's first value.
 */
function YOUR_MODULE_node_get_field_single_value($node, $field_name, $key) {
  $items = field_get_items('node', $node, $field_name, $node->language);

  if (!empty($items)) {
    $item = array_shift($items);
    return isset($item[$key]) ? $item[$key] : NULL;
  }
  else {
    return NULL;
  }
}

And call it like this (assuming that this field has a single value in it):

$keywords = YOUR_MODULE_node_get_field_single_value($entity, 'field_keywords', 'value');

Please note that the above function is just an example, your field might have multiple values in it. In that case, you'll need to iterate the array returned by field_get_items.


Drush Jailed by Jailshell My web host (Bluehost) recently switched shell access from bash to Jailshell. That simple switch has sent Drush on vacation. It has been months and the host has not been able to find a solution (or isn't looking). Below are a couple of error messages returned from drush status. The problem isn't the PHP version. The problem is Jailshell.

  Parse error: syntax error, unexpected T_STRING, expecting
  T_CONSTANT_ENCAPSED_STRING or '(' in
  /home2/username/.composer/vendor/drush/drush/includes/preflight.inc on
  line 8 user@domain.com [~/public_html/clientfolder]# drush status

  Warning: Unexpected character in input:  '\' (ASCII=92) state=1 in
  /home2/username/.composer/vendor/composer/autoload_real.php on line 23

  Parse error: syntax error, unexpected T_STRING in
  /home2/username/.composer/vendor/composer/autoload_real.php on line 23

Any assistance would be greatly appreciated. Thank you.

There's no assistance available, really, this is out of your hands and can only be fixed by the server admins.

Your three options are:

Convince your hosting provider to upgrade the version of PHP you have available in the shell. If they tell you they don't know how to do that, go to option 3.
Downgrade drush to something that works with old versions of php
Change your hosting provider to one who's got their act together. Your current provider hasn't, clearly.


Determine front page for specific language I'm using I18n and I am trying to choose which front page to use for each language.

I actually get the following message for every page :

  The requested page "/en" could not be found.

Same for /de (deutch).
Has anyone met this problem before ?

Found it. It was in "Administration » Configuration » System" that I didn't set the default front page !


How do you override Commerce checkout pane output? I downloaded the commerce bitcoin module and I'd like to override the current output of the pane. There is no theme_ function to override. How can this be done?

The code is below:

 1 <?php
  2
  3
  4 /**
  5  * Implements base_checkout_form()
  6  * Display the bitcoin address at the checkout
  7  *
  8  */
  9 function commerce_bitcoin_pane_checkout_form($form, $form_state, $checkout_pane, $order) {
 10
 11
 12
 13
 14   $output .= t('Total amount %total BTC', array('%total' => $bittotal)) . '
';                                                                                15   $output .= t('Check Blockchain.info Payment Status') . '
';
 16   $checkout_form['commerce_bitcoin_pane_field_display'] = array(
 17     '#markup' => $output
 18   );
 19
 20   return $checkout_form;
 21 }

Checkout panes are fieldsets within the context of per-page checkout router form. You can use a hook_form_alter() to modify the contents of the entire page that a form is shown on. For instance, if you want to modify objects that appear on the checkout page (which is the first one in Commerce Core), you'd use this hook:

MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state) {
  // Make the customer profile billing pane's locality field a bit smaller.
  $form['customer_profile_billing']['commerce_customer_address']['und'][0]['locality_block']['locality']['#size'] = 20;
}

Where commerce_checkout_form_checkout is commerce_checkout_form_ concatenated with the current checkout router step. See commerce_checkout_router(). Each of the panes within the page exists within this form. As Ryan also points out in the comments, the main form traps errors and other items to present them inline with the checkout pane, so a payment error won't show up at the top of the page, but it will show up above the payment pane for instance.

If you're wanting more info on how to theme checkout, I'd recommend you go review the code for Commerce Responsive UI and mimic what it does.

This includes the complete pane which is still a form. If you want to override the form completely, you can just change the callback that is called when the completion pane is being built:

/**
 * Implements hook_commerce_checkout_pane_info_alter().
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  $checkout_panes['checkout_completion_message']['callbacks']['checkout_form'] = 'MYMODULE_completion';
}

Then, you put your own output into the new callback. Just copy what commerce_checkout_completion_message_pane_checkout_form() does and put your own content in.


views... two random nodes to vote on I'm trying to use views to show two random nodes for voting on.  I would use something like: filter: Node:terms(with depth), fields:Node body/ title, Sort criteria:GLOBAL:random.  Now, how can I render two random nodes for voting?  Would I have to render them on a custom page-"newpage".tpl.php?  I'm thinking if I used a custom template I would make two 50% regions, have them float left/right, have one height:150px region footer for the voting(below the nodes), then maybe use "popups" so it looks cleaner?  Any ideas on this?  For starters, I'm not sure how I would generate "2" random nodes and have them render in the appropriate "left/right region".  Thank you.

Just create them as blocks and place them on a static page together in any region you wish. (Keep it simple)


“Structure->Block” showing when permission is not given to user I have user role 'Admin', who can see 'taxonomy terms' under 'Structure', I have given same permission but it is showing 'Block' and 'Views' too.

Is there any workaround in Drupal 8?

Any help would be great. Thanks

You've probably given them the Administer blocks and Administer views permission as well. Withdraw these permissions and the links should disappear.


Why are some place holders '@' and others '%'? For example:

watchdog('alerts', 'Message for %user was sent.', array('%user' => $user));

and

drupal_set_message(t('options: @options', array('@options' => $form_state['values'])));

Is there any difference?

Have a look into the function definition of the format_string()
 function which is used by the t() function:

Each type of placeholder has a way in which this function intrepretes it:

@variable: Escaped to HTML using check_plain(). Use this as the default choice for anything displayed on a page on the site.
%variable: Escaped to HTML and formatted using drupal_placeholder(), which makes it display as emphasized text.
!variable: Inserted as is, with no sanitization or formatting. Only use this for text that has already been prepared for HTML display (for example, user-supplied text that has already been run through check_plain() previously, or is expected to contain some limited HTML tags and has already been run through filter_xss() previously).


Need help with my form with duplicate file and resetting form Need help with my form for uploading an image on my theme's settings. I have a form that uploads an image that can be used as a background image. I have two problems with my form: first is how to delete the uploaded file or reset the form and second is an error message appears when uploading the same file again after resetting the theme's settings.

This is my form code I'm using:

<?php function tsaudio_form_system_theme_settings_alter(&$form,&$form_state) {

$form['slideshow'] = array(
'#type' => 'fieldset',
'#title' => t('Background'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);

$bg_path = theme_get_setting('bg_path');if (file_uri_scheme($bg_path) == 'public') {
$bg_path = file_uri_target($bg_path);
}

$form['slideshow']['bg_path'] = array(
'#type' => 'textfield',
'#title' => 'Path to background image',
'#default_value' => $bg_path,
'#disabled' => FALSE,
);

$form['slideshow']['bg_upload'] = array(
'#type' => 'file',
'#title' => 'Upload background image',
'#description' => 'Upload a new image for the background.',
);
$form['reset'] = array(
'#type' => 'markup',
'#markup' => '<input type="reset" value="Reset All Values" class="form-submit">',);

$form['#submit'][] = 'tsaudio_settings_submit';}
function tsaudio_settings_submit($form, &$form_state) {
$settings = array();
// Get the previous value
$previous = 'public://' . $form['slideshow']['bg_path']['#default_value'];

$file = file_save_upload('bg_upload');
if ($file) {
$parts = pathinfo($file->filename);
$destination = 'public://' . $parts['basename'];
$file->status = FILE_STATUS_PERMANENT;

if(file_copy($file, $destination, FILE_EXISTS_REPLACE)) {
  $_POST['bg_path'] = $form_state['values']['bg_path'] = $destination;
  // If new file has a different name than the old one, delete the old
  if ($destination != $previous) {
    drupal_unlink($previous);
  }
}
} else {
// Avoid error when the form is submitted without specifying a new image
$_POST['bg_path'] = $form_state['values']['bg_path'] = $previous;}

}?>

And this is the error message I get when uploading the same file again after resetting the theme's settings to default.

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062
Duplicate entry 'temporary://ctrldailybg4_1.jpg' for key 'uri':
INSERT INTO {file_managed} (uid, filename, uri, filemime, filesize,
status, 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); Array (
[:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] =>
ctrldailybg4.jpg [:db_insert_placeholder_2] =>
temporary://ctrldailybg4_1.jpg [:db_insert_placeholder_3] =>
image/jpeg [:db_insert_placeholder_4] => 1344028
[:db_insert_placeholder_5] => 0 [:db_insert_placeholder_6] =>
1436760809 ) in drupal_write_record() (line 7316 of /homepages
/9/d539887599/htdocs/towersignal_com/includes/common.inc).

As described in the docs file_save_upload
file_save_upload($form_field_name, $validators = array(),
$destination = FALSE, $replace = FILE_EXISTS_RENAME)

the last parameter $replace

$replace: Replace behavior when the destination file already exists:
FILE_EXISTS_REPLACE: Replace the existing file.
FILE_EXISTS_RENAME: Append _{incrementing number} until the filename is unique.
FILE_EXISTS_ERROR: Do nothing and return FALSE.


How do I add a non-exposed field to node programatically? I need to add a non-exposed field to a node programatically. By non-exposed, I mean a field which users will not be able to interact with. I need to be able to store data in this field through hook_folder_form().

There's always the accepted answer to Add field in hook_node_info();, but that seems to imply that we're talking about exposed fields.

You can add field via structure->content types-> manage fields in your content type, add field that you want to hide.

to hide field in a edit-form/node you can use

function yourmodulename_form_alter(&$form, &$form_state, $form_id) {
if (!empty($form['type']['#value']) && $form['type']['#value'] == 'formtypename') {
hide($form['fieldmachinname']);
]


How do I import a database through a Drush(PHP) script? I am trying to write a Drush script locally to speed up some repetitive tasks. I am running in to issues importing a database through the script. I have tried using drush_invoke and drush_invoke_process to run the equivalent of drush sql-cli < C:/path/to/mysql.sql.

I have tried several different variations with the $commandline_args and $commandline_arguments with no luck and Google has not been helping me much.

Does anyone have the correct syntax for this? I would also be fine with another method that works. I would prefer one that allows for a user input path to the SQL file but hard coded would work for now.

EDIT: I am using drush scr to run the script. Just in case it makes a difference.

EDIT 2: The accepted answer from greg_1_anderson works great. To allow for using the path to the file as an argument I found that drupal_get_option works. Just add the argument --arg_name=arg_value like drush scr script.php --file=path/to/file. Then call the arg in the script file.

Full solution:

$file = drush_get_option('file');
$options = array(
  'file' => $file,
  'file-delete' => FALSE,
  'strict' => FALSE,
);
drush_invoke_process($self, 'sql-query', array(), $options);

Basically, you want to run some php code to import an SQL database dump from a file.  There is code that does this in the implementation of drush sql-sync.  It looks like this:

  $options = $global_options + $target_options + array(
    'file' => $destination_dump_path,
    'file-delete' => TRUE,
  );
  $return = drush_invoke_process($destination, 'sql-query', array(), $options, $backend_options);
  if ($return['error_status']) {
    // An error was already logged.
    return FALSE;
  }

You could also call drush sql-sync with appropriate options for a more full-featured solution (e.g. if you want to import a local database to a remote site).  For an import to a local site, though, it is more straightforward to simply use the snippet above, which essentially runs drush sql-query --file=/path/to/dump.sql.

n.b. You may simply remove (or make empty) $global_options, $target_options and $backend_options. You should also take of the file-delete flag, unless you really would like Drush to delete your sql dump for you after it has imported it (e.g. for temporary files).


Rule to delete other node of same type before saving content I have designed one content type which can be created by registered users via "Form Block" Module. I am now trying to create a rule which will allow each user to only have one existing node of that content type. If they decide to create a node of that content type again, the previous node should be deleted.

I'm having trouble with the rule that would accomplish this. There are no errors, but nothing appears to be being deleted.

Event =

Before saving content

Conditions =

Content is of type (Parameter: Content: [node], Content types: NeuroTrans pt1)

Data comparison (Parameter: Data to compare: [node:author:uid], Data value: [site:current-user:uid])

Action =

Delete entity (Parameter: Entity: [node])

Here's an export of the rule that I have created:

{ "rules_delete_previous_neuro_pt1" : {
"LABEL" : "Delete current user\u0027s previous NeuroTrans pt1",
"PLUGIN" : "reaction rule",
"REQUIRES" : [ "rules" ],
"ON" : [ "node_presave" ],
"IF" : [
  { "node_is_of_type" : {
      "node" : [ "node" ],
      "type" : { "value" : { "neurotrans_pt1" : "neurotrans_pt1" } }
    }
  },
  { "data_is" : { "data" : [ "node:author:uid" ], "value" : [ "site:current-user:uid" ] } }
],
"DO" : [ { "entity_delete" : { "data" : [ "node" ] } } ]

}
}

**Using the "code" entry mode for this post doesn't appear to preserve the formatting quite perfectly.

Any guidance would be much appreciated. Thanks!!

Daniel,

What I think is happening is that you're trying to delete the actual node that the user is about to save (it hasn't been saved yet)!

It doesn't look like you're finding the user's PREVIOUS node to delete first, you're just trying to work with the current one.  :-)

Of course - since this current node hasn't even been saved yet (your event is prior to saving), there is nothing to be deleted.

The rule will have to be more complicated, with your finding an existing node by the current user first...

Hope this helps.


Views check access by PHP I've got 2 roles on my system -uzman and isveren- and several views that need to be restricted to either uzman or isveren. For that purpose, I have been trying to check access control with PHP. I can't use role based access check because then administrator would see all because he has access to all views. Anyway, I am using

<?php
if (in_array("uzman", $account->roles)) {
return TRUE;
}
?>

which works, but I see many undefined offset:4 messages in dblog (4 is uzman's rid). What is the correct way to check access with PHP in Views module?

The correct way is to create a custom module and implement hook_permission() to define an appropriate permission:

function hook_permission() {
  return array(
    'administer my module' => array(
      'title' => t('Administer my module'),
      'description' => t('Perform administration tasks for my module.'),
    ),
  );
}

Grant that permission to the roles that require access to it, and then use user_access() to make the access decision:

if (user_access('administer my module', $account)) {
  ...
}

As AyeshK points out in the comments, you don't actually need the second part - Views has n plugin for access based permissions already, which you can configure through the UI. So once you've added the permission and granted it to the relevant role(s), it'll be easy to get what you're looking for.


db_select based on userid: uid I have a dilemma i just can't figure out, and i need your help. The thing is, I wish to display the ip address of the logged in user in my custom form. The problem i have is how do i make it based on the logged in user?

The following is the code i used:

  $hostname = db_query("SELECT hostname FROM {accesslog} WHERE uid =
  :uid LIMIT 1', array(':uid' =>33));

  echo "Hostname:" . $hostname . "";

If you want the logged in user info, try the following (I have not tested, but it should work).

global $user;

$hostname = db_query("SELECT hostname FROM {accesslog} WHERE uid = :uid LIMIT 1', array(':uid' =>$user->uid))->fetchField();

The global $user object will return information from the currently logged in user.  You might want to put some authentication in to check that the user is logged in if this is used in an area where anonymous users can visit.  Maybe wrap it in an if statement like I've done below:

if (user_is_logged_in() == TRUE) {

  global $user;

  $hostname = db_query("SELECT hostname FROM {accesslog} WHERE uid = :uid LIMIT 1", array(':uid' => $user->uid))->fetchField();

  echo 'Hostname: ' . $hostname;
}
else {
  echo 'You are not logged in.';
}


How to change path of taxonomy facet I am using facet search on my site. The search paths for taxonomy term facets are of the pattern "search/term-name", but I would like them to be of the pattern "search/term-tid".

Is this possible? How can I change this?

Please try this:

/**
 * Implements hook_facetapi_searcher_info_alter().
 */
function mymodule_facetapi_searcher_info_alter(array &$searcher_info) {
  foreach ($searcher_info as &$info) {
    $info['url processor'] = 'term_facet_url';
  }
}

Create a folder inside your mymodule directory, and name it facetapi.

Next is create an .inc file and name it, url_processor_term_facet_url

So you should have this structure:

mymodule/facetapi/url_processor_term_facet_url.inc

Inside of your url_processor_term_facet_url.inc, add the following code.

<?php

/**
 * @file
 * A custom URL processor.
 */

/**
 * Extension of FacetapiUrlProcessor.
 */
class FacetapiUrlProcessorTermFacetUrl extends FacetapiUrlProcessorStandard {

  public function getQueryString(array $facet, array $values, $active) {
    $params = $this->params;
    unset($params[$this->filterKey]);
    return $params;
  }

  public function getFacetPath(array $facet, array $values, $active) {
    // Change the line below to your desired taxonomy term path, currently it
    // is set to 'taxonomy/term/[tid]'. And also make sure only taxonomy terms
    // are affected. Check other parameters to pull the data you might need.
    $path = 'taxonomy/term/' . $values[0];
    return $path;
  }

}

I hope it helps.


Create a connection using FileTransferFTP I want to create a FTP connection using the FileTransferFTP class.

How can I do it?

The code used to create an FTP connection is similar to the following one.

try {
  $ftp = FileTransferFTP::factory($jail, $settings);
  $ftp->connect();
  // Copy the files.
}
catch(Exception $e) {
  // An error happened.
}

$jail is the directory to which the operations are restricted. Any tentative to write files externally to this directory will raise a FileTransferException exception.

$settings contains:

$settings['username']: The username
$settings['password']: The password
$settings['advanced']['hostname']: The hostname for the FTP server (default to localhost)
$settings['advanced']['port']: The server port (default to 21)

FileTransferFTP::factory() returns the instance of the sub-class that takes care of the file transfer, if there is one, or raises an exception, if there aren't sub-classes.

The code currently executed from FileTransferFTP::factory() in Drupal 7 is the following one.

  $username = empty($settings['username']) ? '' : $settings['username'];
  $password = empty($settings['password']) ? '' : $settings['password'];
  $hostname = empty($settings['advanced']['hostname']) ? 'localhost' : $settings['advanced']['hostname'];
  $port = empty($settings['advanced']['port']) ? 21 : $settings['advanced']['port'];

  if (function_exists('ftp_connect')) {
    $class = 'FileTransferFTPExtension';
  }
  else {
    throw new FileTransferException('No FTP backend available.');
  }

  return new $class($jail, $username, $password, $hostname, $port);

Future versions of the class could implement the method differently, and create different instances of the FileTransferChmodInterface interface basing on different conditions.

In Drupal 8, the class has been renamed Drupal\Core\FileTransfer\FTP.


Querying the user list from the database There is a need from a different team in our organization to provide a periodic export of users, roles, and users-roles relationship data in a certain Aveksa-specific format.

Where (which table(s)) are the list of Drupal 8 users and roles stored in Drupal database? I've looked at all the tables listed in the schema and examined their records, and could not find anything that resembled user/roles data.

I figure querying the database is the way to go rather than looking at the /admin/people section of Drupal and scraping the data from there.

If you're set on scraping this out of the database, you could try looking at the user__roles table that Kevin mentioned in his comment above:

mysql> SELECT * FROM user__roles;
+--------+---------+-----------+-------------+----------+-------+-----------------+
| bundle | deleted | entity_id | revision_id | langcode | delta | roles_target_id |
+--------+---------+-----------+-------------+----------+-------+-----------------+
| user   |       0 |         1 |           1 | en       |     0 | administrator   |
+--------+---------+-----------+-------------+----------+-------+-----------------+
1 row in set (0.00 sec)

But since this is Drupal, you have other methods at your disposal.

For example, you could create a View of users and roles, and then use Views Data Export to export.

This module also exposes a drush command that can execute the view (interactively, or via scheduled jobs from the system crontab) and save its results to a file.

drush views-data-export [view-name] [display-id] [output-file]


How do I change the search key length? I'm using Search API and Fuzzysearch in D7, and it's unable to search for three letter words. Unfortunately, we have a TON of 3-letter acronyms at work, so these need to be searchable. I've looked in the Search API and Fuzzysearch settings, but can't see where to change the length of the search keys.

I get the following error message when searching:

  The following search keys are too short or too common and were
  therefore ignored: "api".

go to admin/config/search/settings and change the length of Minimum word length to index to 2 and re-index the site.


Enable users to view their own profile, without enabling "View user profiles" This may be a really stupid question, but we can't see how to make it work.

We have a Drupal 7 site with several different rôles and one of them should not be able to see the user profiles of the others. Now I thought that would be simple, by unchecking the "View user profiles" permission in the People admin.

But that prevents them accessing their own profiles as well. From what I can gather, there isn't a simple way of making this be the case, so I'm looking for any sensible suggestions on how I can make it happen -- code edits, modules, whatever.

Thanks everyone! (And let me know if I need to provide more information about our configuration or Modules we have installed.)

You could do this with a custom rule, as follows:

{ "rules_users_view_own_profile_only" : {
    "LABEL" : "Users View Own Profile Only",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_view" ],
    "IF" : [
        { "NOT user_has_role" : { "account" : [ "site:current-user" ], "roles" : { "value" : { "3" : "3" } } } },
        { "AND" : [] },
        { "NOT data_is" : { "data" : [ "site:current-user:uid" ], "value" : [ "account:uid" ] } }
    ],
    "DO" : [ { "redirect" : { "url" : "http:\/\/www.yourdomain.com\/denied" } } ]
    }
}

That basically checks to make sure the user isn't an admin or on his own account page before directing to yourdomain.com. If you use the CustomError module, you can redirect to an access denied page.

You might also want to check out the Edit own user account permission module - you might be able to enable that and disable "View user profiles" and get the results you want, although I haven't tried that.


How do I use a node as the homepage? I feel like I'm misunderstanding something at a fundamental level when trying to author my drupal site. Two content types, both created by me, are available - faq and page. The faq type is a basic question + answer type, and will be pulled into an FAQ list block which I created. The page type is for a generic authored page, and has a body property of type entity_reference_revision which allows content to be authored using Bootstrap Paragraphs.

Some sources online say that you just have to check the "Promote to front page" box to get a node to be the front page. Others say that you have to provide a URL path for the node. I've tried both, and neither causes the site's front page to display the authored page I've created.

Instead, on the front page, I see a list of the items that have been promoted to the front page.

How can I get my authored node to replace the content of front page, so that if I navigate to the root route (/), I see the authored page?

Set the front page in Admin > Config > Site Information. “Promoted to frontoage” is not what you think it means in this context.


How to force initial imported node to not have draft status using feeds? I'm using the Feeds (7.x-2.0-alpha9) and the Workflow modules. My imported nodes are automatically going to draft state and only go to done state when there is a second import of this node and the data is updated.

How can I automatically make the state on imported nodes be "saved" not "draft"?

I tried adding a rule upon feeds presave, but it never gets to the save since it is a draft.

Even though this question is related to the Workflow module, the solution you're looking for should come from the Feeds and/or Rules module, as further explained in my answer below.
1st attempt: Feeds Rules module
The Feeds Rules module might be what you are looking for. Excerpt from its project page:

... provides some Rules integration for the Feeds module.
It provides:

Feeds processor: a processor for Feeds to create content via Rules. (Currently only simple data types like text and integer are supported).
Rules Event: Feeds After Import
Rules Data: Feeds Source (properties: ID, imported)

Recommendation: this might work, however there is only a dev version available for this module ... my advice = no go.
2nd attempt: Native Feeds module
The Feeds issue about Rules integration & enable modules to customize imports adds a hook hook_feeds_before_import(). Here are some quotes from that issue (bold markup added here):

... such that a rules integration could use it to customize the imported entities before saving + to skip saving.
Based on the hook we could add an event for it + an action for skipping the import. The entity could be manipulated with the usual rules actions else too.

Of course, in the question here the goal is to not skip saving. But instead "customize the imported entities before saving" and/or "manipulate the entity with the usual rules actions". More specifically: set the value of "state" to "Saved".
Recommendation: much better already, but it is not exactly right yet (and requires using a hook, i.e. writing some custom module) ... There has to be a Rules based solution ...
3rd (and Final) attempt: A rule that should do the job
Inspired (challenged) by the "I tried adding a rule upon feeds presave, but it never gets to the save since it is a draft" part of this question, I created a rule. Here is the export that rule, which I believe should be a perfect answer to the question (also because it doesn't require custom PHP code ...):
{ "rules_update_entity_after_import_via_feeds" : {
    "LABEL" : "Update field imported via feeds",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "workflow_rules", "feeds" ],
    "ON" : { "feeds_import_node" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_workflow_status" } }
    ],
    "DO" : [
      { "workflowfield_field_set_state" : {
          "node" : [ "node" ],
          "field" : [ "node:field-workflow-status" ],
          "workflow_state" : { "value" : { "3" : "3" } }
        }
      }
    ]
  }
}

To get this to work, I enabled the Workflow API module (of course ...), and also it's submodules  Workflow UI,  Workflow Field and Workflow Rules.
My Workflow itself has only status "Draft" and "Done" (identical to the question here).
The rule above only applies to "node", and only for those "nodes" that have a field defined with machine name "field_workflow_status" (if you want to use another field name, change the rule accordingly and it should work also ...). In my case I used "Article" as the content type, though the "entity_has_field" prevented that I had to hardcode the content type in my rule ...
Obviously, and to be complete, Feeds and Rules are also part of the solution.


Remove output of author username and blog link of news snippets from search results I currently have this in template.php to remove the 'username's blog' link from blog entries.

function phptemplate_links($links, $attributes = array()) {
    unset($links['blog_usernames_blog']);
    return theme_links($links, $attributes);
}

How would I go about using unset to remove the 'username's blog' link from the search results page?

Consider using Display Suite module.

To make changes to search results for article content type, Goto admin/structure/types/manage/article/display and enable the search result custom display.

Then visit admin/structure/types/manage/article/display/search_result and add or remove the fields as per your requirement.


Panels to do a specific layout for one content type edit mode How can i use panels to do a specific layout for a content type only for the add and edit form ?
I'm a newbie on panels but not on Drupal.I'm using panels 3 on D7.
will be great to give me examples or tutos ..

thanks

Page manager (which, technically isn't the same thing as Panels), manages the url node/% differently from node/%/edit.

When you to go Pages, you need to enable the node edit task, and make configuration to that page, not the node view one.


How to display country base node We are working on drupal 6.26, Our requirement is as follows.

In the admin/cms section we will assign country to a node.
In the front end when visitor visits web site according visitor, respective country node will be displayed.

I searched some modules but I am bit confused.

Please advice us some good module.

Take a look at the Smart IP module. It may be what you are looking for. Excerpt from the module's project page:

  Identify visitor's geographical location (longitude/latitude), country, region, city and postal code based on the IP address of the user. These information will be stored at session variable ($_SESSION) with array key 'smart_ip' and Drupal $user->data object with array key 'geoip_location' of the user but optionally it can be disabled (by role) at Smart IP admin page. Other modules can use the function smart_ip_get_location($ip_address) that returns an array containing the visitor's ISO 3166 2-character country code, longitude, latitude, region (FIPS), city and postal code. It provides a feature for you to perform your own IP lookup and admin spoofing of an arbitrary IP for testing purposes.


Extracting arguments from dynamic URLs I am new to Drupal 7 and am trying to do the following:

1) I have a node that's aliased to domain.com/inventory - the node has code that'll generate dynamic content.

2) My site creates dynamic URLs like domain.com/inventory/ABCD and I need to know how to a) figure out that I'm on the /inventory page and b) extract the argument "ABCD" from the URL.

Can you please help me?

If your node is 12, your internal path is node/12 when the alias is 'inventory'. In that case arg(0) gives you 'node' and arg(1) gives you '12'.

In the case of dynamic URLs like inventory/ABCD, I assume that the internal path is 'inventory/ABCD' (so that inventory/ABCD does not have anything to do with node 12). Then arg(0) gives you 'inventory' and arg(1) gives you 'ABCD'.


Adding validation to commerce pane form I want to add validation to the user's details form.

I've tried to use the #validate to add validation function, but nothing happens.

This is the Code:

function hotphone_checkout_form_commerce_checkout_form_checkout_alter(&$form,&$form_state)
{
 $form['#validate'][] = 'mymodule_validate_check';
}

function mymodule_validate_check(&$form, &$form_state)
{
  dpm('hererere', $form_state);
  die();
}

What am i doing wrong??

The current way to do this, as per Commerce API is, instead of adding a validate handler to the complete checkout form you extend the checkout pane definition and specify your own validate handler.

If your custom validation passes, fallback to the default  pane validation handler.

In this example, to add a custom validation handler to the shipping pane:

/**
 * Implements hook_commerce_checkout_pane_info_alter
 */
function MODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  if(isset($checkout_panes['commerce_shipping'])){
    $checkout_panes['commerce_shipping']['callbacks']['checkout_form_validate'] = 'MODULE_commerce_shipping_pane_validate';
  }
}

/**
 * Checkout pane validation override to ensure valid shipping method for address
 */
function MODULE_commerce_shipping_pane_validate(&$form, &$form_state, $checkout_pane, $order) {

  // Do some validation tests here... omitted for brevity.
  if (!$valid) {
    drupal_set_message(t('Some validation error message'), 'warning');
    return FALSE;
  }

  // Fallback to default validator.
  if (function_exists('commerce_shipping_pane_checkout_form_validate')) {
    return commerce_shipping_pane_checkout_form_validate($form, $form_state, $checkout_pane, $order);
  } else {
    // Passed validation.
    return TRUE;
  }

}

  checkout_form_validate($form, &$form_state, $checkout_pane, $order):
  validates data inputted via the pane’s elements on the checkout form
  and returns TRUE or FALSE indicating whether or not all the data
  validated

More info:

hook_commerce_checkout_pane_info
commerce_checkout_form_validate


Install routinely failing after database authentication I am having the worst time installing drupal 7 on Ubuntu 14.04 on an amazon aws ec2 instance and I don't know why. I've never had this much trouble before. No matter how closely to a T I follow these instructions: https://www.digitalocean.com/community/tutorials/how-to-install-drupal-on-a-virtual-server-running-ubuntu-12-04 (i really can't imagine 12.04 being that different from 14.04, i'm not doing anything fancy) it always results in the following failure:

So I get the LAMP stack installed and set up and verify it's working correctly. And I create the database and the database user and verify that that's all working. And I download and move all the files to /var/www/html and start the install. Everything goes fine until I hit the database connection stage. I put in the credentials, it thinks, then the database connection page refreshes and the fields are empty. At this point I go and I check the database and there are 31 tables created by Drupal, so it is connecting and modifying the database.

So what else can I do but restart the install, and when I do it jumps to the site information page, so I add that information, save it and I get the following error:

Fatal error: Call to undefined function field_attach_load() in /var/www/html/includes/entity.inc on line 321 (which would otherwise be a WSOD, but at least I have development debug turned on)

If I just go to the site now, the default drupal page comes up but only with:
Page not found
The requested page "/" could not be found.

It's really throwing me here, I've Googled the error and the results are just so all over the place and I have no idea why I can't even get this thing installed before something goes wrong. This is not my first time installing a drupal site, have done it many times before on ubuntu servers from amazon aws and non-virtual servers.

Guess there are a ton of answers here for the exact same problem: https://www.drupal.org/node/1171756.

Don't really want to duplicate them.

update: In my case I needed to chown -R www-data the directory my drupal files were in, apparently ownership was somehow changed from the apache server, had to change it back. there you have it.


Drush not working on a docker based enviroment on ubuntu 16.04 I have set up a local dev docker environment with the Drupal social distribution. My issue is that Drush commands do not work and whenever I run a Drush command, it takes approximately 45 seconds to get a response. Generally, the output is always the same or similar to the following.

  [warning] proc_open(): unable to dup File-Handle for descriptor 2 - Too many open files exec.inc:243
  [warning] proc_get_status() expects parameter 1 to be resource, boolean given exec.inc:244
  [warning] proc_close() expects parameter 1 to be resource, boolean given exec.inc:245

I am unsure what the reason for this response is or what I may have done wrong to get to this point. I tried googling the warning errors but without getting a usable answer. If someone has had similar problems and managed to solve it, some directions on what to do would be appreciated.

I also want to state that outside the docker environment I have setup multiple Drush setups; Drush commands work normally without any delay outside of it.

My environment is Ubuntu 16.04 with 15.5 GB RAM, i7-6500U CPU 2.5 GHz x4 Processor, 200GB DDR disk.

I googled some more and found out that for running Drush inside a docker environment you need docker-compose run drush "drush command here" since Drush container gets run only for one specific command and then shuts back down, but now I am getting different errors.

docker-compose run drush cache-rebuild --verbose --debug gives this as output.

  Phar detected. Proceeding to drush_main().Drush preflight prepare loaded autoloader at  [0 sec, 2.92 MB] [preflight]
  Starting Drush preflight. [0 sec, 2.92 MB] [preflight]
  Cache HIT cid: 8.1.2-commandfiles-0-9c75c37463d39480ab97163ab2be3712 [0.01 sec, 2.96 MB] [debug]
  Scanning into /etc/drush for /.*aliases.drush(8|)rc.php$/ [0.02 sec, 5.02 MB] [debug]
  Scanning into /etc/drush for /self.alias.drush(8|)rc.php$/ [0.02 sec, 5.02 MB] [debug]
  Scanning into phar:///usr/local/bin/drush/includes/.. for /.*aliases.drush(8|)rc.php$/ [debug] [0.02 sec, 5.02 MB]
  Scanning into phar:///usr/local/bin/drush/includes/.. for /self.alias.drush(8|)rc.php$/ [debug] [0.03 sec, 5.03 MB]
  Scanning into /root/.drush for /.*aliases.drush(8|)rc.php$/ [0.04 sec, 5.03 MB] [debug]
  Scanning into /root/.drush for /self.alias.drush(8|)rc.php$/ [0.04 sec, 5.03 MB] [debug]
  Bootstrap to phase 0. [0.05 sec, 6.01 MB] [bootstrap]
  Bootstrap to phase 2. [0.05 sec, 6.01 MB] [bootstrap]
  Command cache-rebuild needs a higher bootstrap level to run - you will need to invoke drush from a more functional Drupal environment to run this command. [error] [0.05 sec, 6.01 MB]
  Command cache-rebuild requires Drupal core version 8+ to run. [0.05 sec, 6.01 MB] [error]
  The drush command 'cache-rebuild' could not be executed. [0.05 sec, 6.01 MB]

Hope that gives you a clue of what is the matter here.

When you run docker run ... or docker-compose run, Drush is running in the context of the container, not your host machine. So when it needs stuff like DB credentials, aliases, ssh keys, it looks for them in the container. If Drush cannot find such things in the container, Drupal cannot fully connect to Drupal and you get an error, usually the bootstrapping one.

I have a feeling your code isn't mounted to the Drush container, based on the fact that the alias scanning isn't picking up anything custom, only the usual alias paths. If the code is mounted, then probably the Drush container does not have the DB credentials. Do a drush status to check if everything is fine.


View for selecting an image associated with a node's child node? I am trying to compose a certain view. I have a content type lesson that contains exercise content types. Exercises reference a lesson nid through an entity reference field. Exercises have images. For a given lesson node, I am trying to build a view that returns the images associated with a lesson's exercises, and then choose one at random.

I couldn't figure out how to make Views return such a result set. And if someone can just explain this in SQL terms, irrespective of view, there is a fiddle: http://sqlfiddle.com/#!9/dbf63

Regards

Haven't figured out how to make Views return what I want but it seems this works, where I would pass the query the lesson node. But I really want to understand how to make Views produce the desired result!

SELECT *
FROM file f
INNER JOIN tab t on t.field_tab_fid = f.fid
INNER JOIN lesson l ON l.entity_id = t.entity_id
WHERE l.field_lesson_target_id = 672

http://sqlfiddle.com/#!9/dbf63/4


In Drupal 7 how to expose TID (term id) as a selectable field on the manage display section of the taxonomy page? How can I expose the TID of a the term as a field via the manage display section of the taxonomy page?

You can use Display suite, and create a custom field.

Install ds and ds_extras.
Configure ds_extras to enable custom fields.
Activate a display suite layout for your taxonomy term display.
Create a custom field, where you can put the tid as a token.


How to restrict one exposed filter per content area? On my Drupal 8 site a have a /search view page that contains two exposed filters. I would like to expose them in different areas, for example to use search bar in the navigation, and filter by content type in the "content" block. But if I pick in 'advanced' tab 'Exposed form in block' "Yes", then both my filters appear in the navigation bar.

How can I split my exposed filters into different areas?

There is a module that seems to do exactly that: MEFIBS - More exposed forms in blocks.

Apart from that you could follow a workaround mentioned on that module project page where you clone your Views Display, don't change the Path, only change the Exposed settings. You will end up with two different blocks that can be placed in different regions, but working on the same Views page.


Drupal 7 custom module menu hook is not working I have created D7 module called 'mymodule' and enabled it from module list page.
But the menu created inside the mymodule_menu() is not being called, instead redirects to 404 page.

Below is the mymodule.info file

name = my custom module
description = My module testing
version = 7.x
package = Custom Modules
core=7.x

Below is the mymodule.module file

<?php
echo 'Module is called';

function mymodule_menu() {

    $items['mydesk'] =  array(
      'title' => 'My Desk' ,
      'page callback' => 'show_mydesk',
      'access arguments' => TRUE,
    );
    return $items;
}

function show_mydesk() {
    echo 'show_mydesk';
}

Note: the echo 'Module is called' text is printing after enabled the module.
Any help to find out where I have missed something.

Thanks
Govind

You need to change access arguments with access callback.

Replace following code:

$items['mydesk'] =  array(
  'title' => 'My Desk' ,
  'page callback' => 'show_mydesk',
  'access arguments' => TRUE,
);

With:

$items['mydesk'] =  array(
  'title' => 'My Desk' ,
  'page callback' => 'show_mydesk',
  'access callback' => TRUE,
);


What was killed after the installation and enabling of Devel with Drush 7? I am not a Dev so I don't have a clue where would this come from.

I've installed and enabled the famous Devel module in my Drupal 7 site via Drush 7 on my CentOS online server after connecting with SSH.

After installing and enabling the module I got the message "Killed", not more not less.

My only question is - What was killed?... I've installed modules with Drush many times, on both Druapl 7&8, and both online and locally, and never had this message before. The install and enabling seem to have been successful.

Material I've found in Google and here deals with Drupal 6 and other commands.

In my case, increasing the value of memory_limit in php.ini solved the problem.

I had 128M and I just changed to 512M, for testing purposes, and the "Killed" message just disappeared.

Of course, don't forget restart your web server after that change.


URL redirect for changed url structure I changed my Drupal 6 website tag structure and got a new URL however old URLs are indexed in Google and are generating 404 errors.

My old URLs are

www.mydomain.com/topics/12345/widget
www.mydomain.com/topics/5783/widget2

numeral - 12345 in this URL was tag no in the database

new URL structure is

www.mydomain.com/topics/widget
www.mydomain.com/topics/widget2

Now I wish to create a redirect so that

mydomain.com/topics/12345/widget

goes to

www.mydomain.com/topics/widget

and remove the random numeral nos in URL.. How to do it?

You can use Path Redirect module. Module page says -

  This module allows you to specify a redirect from one path to another
  path or an external URL, using any HTTP redirect status.

As I see you are talking about taxonomy terms, so alternatively you can use Taxonomy Redirect.

  This module allows the administrator to change the destination of
  Taxonomy Term links.

  The module can now handle redirections at the term level.
  You can specify a replacement character for spaces and + characters.
  You can specify a list of characters or strings to remove from the path
  You can enter php code that will create your path at runtime (In 5.x-1.3, variables for term ID ($tid) and term name ($tname) are available to use in your php code).


How to add block to a single page that is not included in the allowed content type list? We have a block (block_description) that is some text that we want to be displayed on all the content type except the article content type. However, there is a requirement now to display the block on just one of the article content types.

How can this be done with the following settings below on the block?

Current settings (e.g. admin/structure/block/manage/block_description):

Content type: Basic Page (allowed)
Other facet: default values
Content Types: Not restricted
Pages: No restrictions
Roles: no restrictions

Goal:

Add block_description to just article-1 (a single Article content type page)

With Drupal 8 you can have multiple instances of a block.  So, the easiest way to have this block show on the article page would be to do the following:

In the structure->block layout page, go to the region you already have the block created.

Place a new block and select your description block again.

In the configuration settings, set the page restrictions to use:  /node/<nid> where  is the article you want the block to be displayed.  You can use aliases here but the nid is best because this supports alternate languages if you need them.

Note: I assume you already have a block instance set up limited to the other content types.  If not, repeat and use the content types restriction to limit it.


Parameters with uppercase letter? Is it possible to handle querystring parameters in webform module in Drupal 8.x with Uppercased letters like in this example?
example.com?collectionId=123 (notice uppercase "I")

Webform fields requires machine names (capital letters not allowed).
Currently i get forms pre-filled as expected using collectionid=123 instead of collectionId=123 but in my current scenario using the capital letter is a requirement in order to keep some legacy external process working untouched.

Any suggestions?

You need to write some custom code to lowercase the query string parameters before the webform is built and displayed.

Another hack would be to pass the query string parameter using a token [current-page:query:collectionId]


bootstrap-carousel.tpl.php not used I have the bootstrap D7 Theme as a base themen. I added a new content-type for my header images and then create a bootstrap carousel using the bootstrap carousel view type.

Now I do get a carousel which seems to work fine but it looks crap, so I'd like to style it etc.

So accomplish this I though I could just "overload" bootstrap-carousel.tpl.php. But it doesn't work - it works for other template files though. Even worse: The original bootstrap-carousel.tpl seems to never be used. (Which porbably is the reason why my carousell looks totally unstyled).

What could be the reason for this?

Permission should be fine since it all the same and as I said, overloading other template files works.

Edit: For the carousel feature I use the bootstraps views module. I kind of expected that the tempalte files from the base theme kind of overwrite the ones from the module but it seems that isn't the case. why?

Since the bootstrap carousel is based on a content type, you should be overriding node.tpl.php instead. Try dropping a node--bootstrap_carousel.tpl.php into your theme and making your markup changes there.


What is the purpose of entity_keys in ContentEntityBase? I'm trying to figure out what is the purpose of entity_keys in ContentEntityBase entities and what fields should be set as entity_keys.

For example in \Drupal\node\Entity\Node we have such entity_keys:

entity_keys = {
 "id" = "nid",
 "revision" = "vid",
 "bundle" = "type",
 "label" = "title",
 "langcode" = "langcode",
 "uuid" = "uuid",
 "status" = "status",
 "uid" = "uid",
}

Why exactly these fields are selected to be entity_keys? And, for example, why in \Drupal\comment\Entity\Comment status isn't in entity_keys?

entity_keys are basically an alias for fields. It allows generic code, like the storage backends, to access common fields that have different names, for example the ID. They need write the saved value, so the can't just use id() as most places.

Internally, those keys are also used by generic methods like id(), label(), getRevisionId() and so on, so they work out of the box.

There isn't really a reason that comment doesn't define status. Nothing really uses status, if you search for getKey('status'), there are no matches, while getKey('id') finds a lot.

Node only uses it internally for the isPublished().


Accessing a FieldItemList value within Twig I've tried several different ways to try access the value of a field item list value without success.

The item in question within Drupal 8 is a float text field and I need the unmodified number from this. The value gained from the standard content.field_latitude[0]['#markup'] call is rounded in some manner so I want to grab the one located in the #items object as shown in the screen shot below.

I can get this via a preprocessor in the theme file but want to avoid using a preprocess if I can and want to gain access directly in the twig file.

To get the value you've highlighted in the debug output in Twig:

{{ content.field_latitude['#items'].0.value }}

You can see this follows the path you've shown in the screenshot, but missing the protected values array. Instead it uses .value on the field item, which calls a magic method __get('value') to retrieve the protected property.

But as @MarioSteinitz commented it's better to use the node object:

{{ node.field_latitude.value }}

Because content is not an API like the methods of the node object. It is a render array which can change when you configure the field display differently or install a layout module.

And never use the |raw filter on user input!


Addressfield: format US state as two letter abbreviation? Using Drupal 7 with Address Field module.  How do I get the US state (i.e., the administrative_area) to show as a standard two letter abbreviation rather than the full state name?

What shows now is:

123 Main St
Somewhere, Florida 12345

I want the node to show:

123 Main St
Somewhere, FL 12345

UPDATE

In address.inc in the addressfield module files, there is a function addressfield_format_address_generate which defines an '#options' array of all the different states (an associative array with 2-letter state abbreviations as the keys and state names as the values).

In addressfield.module, there is a function _addressfield_render_address which I believe checks if there is an '#options' defined and if so, tries to get the value for the given key.

So it would seem if I want to change this behavior I somehow need to override _addressfield_render_address

As part of this commit, U.S. states (and other countries' administrative areas) will now use their two letter abbreviations when rendered in address formats. Additionally, we now properly provide a comma between the city and state.

Additional code to get this format will no longer be required as of Address Field 7.x-1.0-beta4.


How to write a rule for 'After sending email'? I have to write a rule for the event 'After sending email'. How can I do that?

For example there are three users user1, user2, user3. I need to enable a flag on a content type after admin sending email to those three users.

There is no Rules Event like "*after sending eMail". However, you can create a Rules Component for sending an eMail. For a sample of such Rules Component, refer to the answer to "Rule to store user's last post date and scheduled rule based 30 day reminder".

If you then "invoke this Rules component" any time a rule has to send an eMail, you basically created the equivalent of the Rules Event you're asking for. All that's left to do is to expand that Rules Component with additional Rules logic that you want to happen "after sending eMail" (... as in your question).