Is it possible to create content and link it to an existing menu item? I have a menu tree with links all directing to 'front'.

On creating content I don't want to create a new menu item but want to have an extra option under the Menu settings saying 'Add content to existing menu item'.

What is the best way to achieve this or is there a module available that handles this situation (D7)?

I guess you have to write a custom module. This may be a similar situation.


How do I alter myuserpoints table? I am using the Userpoints module. Using that, when I click the "My Score" link I am viewing a table with list of points.

There are 6 headers and 6 rows displaying. In that table, I need only 3 headers and 3 rows to display.

As of now, the module shows the following headers:

Points
Approved
Date
Operation
Category
Description

What I need to display is the following headers:

Points
Date
Description

How can I achieve this?

Here is the way:

  hook_menu_alter()

/**
 *Implemantation of hook_menu_alter()
 */
function your_module_menu_alter(&$items) {
  $items['myuserpoints']['page callback'] = 'userpoints_list_my_userpoints_custom';
}

By using menu alter write your custom function and change the table structure as per your need. And it's done :)


SQL Query to get all Products? I have been given a broken site and a database that was formerly running Drupal commerce via Commerce kickstart. The site was hacked when Drupalgeddon happened, and I can't get the code to update (lots of missing component errors).

So I think we need to start over from scratch here, and I would like to know what the SQL query might be to get all of the product data out of the database? Is this something that can be done directly in SQL?

There isn't an easy solution for this since the field data is stored in multiple tables and is based on configuration which is also stored in the DB.

You're better off trying to use Registry Rebuild and Commerce Repair to get the site working and then using export tools to get the data.


Is there a Ping Module? I'm creating a support site for a hosting company in D7 and one of the features that they have asked for is for drupal to ping each of the servers, (I have a content type called Server which has ipaddresses attached to it) and report back the status.  I want to set it up as cron job.  Is there a module for Drupal that I can add that gives me this feature?  if not can you give me any pointers how to get started on building one?

Thanks

Kieran Briggs

The multiping module will provide this feature in Drupal 7, since the ping module is not part of core anymore. The D7 branch hasn't been started, but there is a patch that you can test that ports the module to Drupal 7. If you test it and it works for you, please comment on that issue, the more people that review that patch the closer the module will get to a full D7 release.


test abitrary url against current page I need to test a series of links to see if any of them match the page that is being processed.  I'm having trouble finding a solution that will match all possible pages (a node, a view page, a page created by a module, etc) and will consider path aliases.

(It would be convenient to start with all parameters of $test_url stripped of the domain name and leading/following slashes.)

function _is_current_page($test_url){
   $test = FALSE;
   ...
   return $test;
}

Test case 1:

// current Url: domain.com/blog/year/month/article_name
// current Nid: 1234
// alias for above: domain.com/popular_article_name

_is_current_page("blog/year/month/article_name") -> true
_is_current_page("node/1234") -> true
_is_current_page("popular_article_name") -> true

Test case 2:

// current Url: domain.com/blog/calendar
// current Nid: _none_ (generated by view or module)
// alias for above: domain.com/blog-calendar

_is_current_page("blog/calendar") -> true
_is_current_page("blog-calendar") -> true

Help greatly appreciated : )

Excluding edge cases (querystring, hash tags, etc), this seems to work for all my test cases:

/**
 * Determine whether a given url matches the current page.
 *
 * @param string $test_path     A file path (no domain, no querystring, etc)
 * @return boolean
 */
function _nwr1_is_current_url($test_path){
    $test_path = trim($test_path, '/');
    $test_norm_path = drupal_lookup_path('source', $test_path);
    $this_nid = (arg(0) == 'node' && is_numeric(arg(1))) ? arg(1) : FALSE;
    $this_norm_path = ($this_nid) ? "node/$this_nid" : FALSE;
    $success = FALSE;

    // test by source (eg node/XXXX - preferred)
    if($test_norm_path && $this_norm_path && ($test_norm_path==$this_norm_path) ){
        $success = TRUE;

    // test by path
    }else if($test_path && current_path() && ($test_path==current_path()) ){
        $success = TRUE;
    }
    return $success;
}


Hide a Prepopulated email textfield I am trying to prepopulate the following fields on a commerce add-to-cart form and then hide the email field:

Recipient name: (textfield) = field_recipient_name
Recipient email: (email field) = field_recipient_email

So far i have been able to pre-populate these fields using views, panels, and prepopulate modules. My challenge is this:

If the email field is already prepopulated with a value, hide this field from the user who intends to buy a gift for the recipient, otherwise the field should be exposed so that user can manually enter the email of the gift recipient. Thanks

Perhaps you can use the Conditional Fields module to check whether the field has a value (sort of a 'not empty' check).

Conditional Fields is described as follows:

Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition.


Uploaded files don't appear on the page My research
I have browsed some of the other similar questions asked regarding this but the fixes do not work for me so I figured I'd ask a new question in the hopes that I can help myself and hopefully others that have the same issue. I have also checked the drupal help forums which again does not fix my issue.

What I want to happen
This is using Drupal 7. I want to make it so that when creating a news article, I can upload files that can be downloaded when people view the page.

What happens when I try to do this
I have added the field successfully and when creating the page, I can upload the file and it shows in the preview. However, when I save the page, although the file shows as uploaded in the 'edit' side, it does not show on the public page.

What I've tried
Additionally, when checking in the files through FTP, the files gets uploaded to the sites/default/files/ directory. I have checked, double checked and tripled checked the permissions which I even set to 777 briefly so permissions doesn't seem to be the issue here.

I have tried commenting out some lines in the sites/default/files/.htaccess file which is one fix I found but unfortunately didn't work for me.

I have checked user permissions which, again, isn't the issue as I'm an admin with every permission checked.

I have also copied the exact settings from another website where this feature is working in case I missed something very simple but this didn't work either unfortunately. The file upload field is set to display and I believe that it's set up appropriately although it is possible I'm missing something extremely simple.

I'm more than happy to update my question with further information if anyone needs any more to help me out. I'm completely baffled on this one so any help would be greatly appreciated.

So after a lot of digging, I realised that this issue was due to the Panels module.

I had only added the field the usual way you would; through the content type when it turns out you need to configure it through the Panels view (which I was completely unaware of until today).

You would think that configuring it though the content type would be enough but evidently not.

Nonetheless, hopefully my question and answer will come in useful to someone one day who encounters a similar issue to mine.


Why does user_load($id) NOT return FALSE when an invalid id is passed in? I'm making a module that lets users manage database records for various organizations.  I'm using Drupal 7 and an very new at it.  I'm logged in as the admin user. I have a menu item 'cb' that checks args and returns content generated by various functions, here it is in the menu:

function org_menu() {
  $items['org'] = array(
    'title' => 'My Orgs',
    'page callback' => 'org_show_orgs',
    'access callback' => TRUE,
  );
  $items['org/create_org'] = array(
    'title' => 'Create New Org',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('org_create_form'),
    'access callback' => TRUE,
  );
  $items['org/search_orgs'] = array(
    'title' => 'Find Orgs',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('org_search'),
    'access callback' => TRUE,
  );
  $items['org/cb'] = array(
    'type' => MENU_CALLBACK,
    'page callback' => 'custom_callback',
  );
  return $items;
}

And this is the cb function that determines what I am trying to do, and calls the appropriate content function:

function custom_callback () {
  if ( arg(2)=="edit" )
    return org_edit_org();
  if ( arg(2)=="view" ) {
    return org_show_orgs();
  }
  return "
Invalid callback function: '".arg(2)."'";
}

and the actual org_get_orgs function:

function org_show_orgs() {
  global $user;
  $acctid=arg(3);
  if ( !$acctid && $user->uid==0 )
    return array('my_content' => '
My Orgs
Please log in to view your orgs.'.
                    '

Find Orgs
', drupal_get_form('org_search'));

  if ( $acctid ) {
    //return "case1 arg0=".arg(0)."
arg1=".arg(1)."
arg2=".arg(2)."
arg3="
    //              .arg(3)."
arg4=".arg(5)."
acctid=$acctid

";
    $account=user_load($acctid);
    //return "case2 arg0=".arg(0)."
arg1=".arg(1)."
arg2=".arg(2)."
arg3="
    //              .arg(3)."
arg4=".arg(5)."
acctid=$acctid

";
    if ( $account===FALSE )
      return "
Invalid acctid "+$acctid+"
";
    else
      return "
account was not FALSE
";
  }
}

cb() gets called correctly and the org_show_orgs() function gets called as expected.  arg(3) is the user id, so I can allow a user to view another user's orgs.

I hit the url
http://example.com/?q=org/cb/view/1
and it works - I see admin's orgs.  If I pick a userid for another user, it works - I see their orgs as well.  The problem is when I tinker with the url and pass in an id of a user that doesnt exist - then I get all kinds of weirdness.  For example, if I hit

http://example.com/?q=org/cb/view/4

If I uncomment that case2 line, I clearly see all my variables are correct:

case2 arg0=org
arg1=cb
arg2=view
arg3=4
arg4=
acctid=4

but if I try to test if $account===FALSE, I get the maintenance page.  If I change the id to 3, I get an 'access denied' page.  If I change the id to 2, I see a 'page not found' page.  If I try return print_r($account,TRUE); I get the menus and a completely blank content cell.  No error, which I'd get it it was a non-array object.  If I try get_class($account) after I retrieve it, I get the menus but no css, and everything is just listed down the left side, no regions, themes, nothing.

Besides the $account issue, is there a better way to be doing this than that callback menu, or is that the drupal way?

The account test probably is working, but this is wrong:

return "
Invalid acctid "+$acctid+"
";

If the $acctid is an integer, it's evaluating that and returning an integer.  The proper php concatenation operator is '.' (without the quotes), change your return statement to

return "
Invalid acctid ".$acctid."
";

It'll evaluate to the string you're presumably expecting.


SASS for module CSS? I have worked in Drupal projects where SASS was used to generate CSS files in a theme (with gulp or compass).

I have also worked in Drupal projects where a lot of the CSS (without SASS) was living in custom modules, to style Drupal components (views plugins, ds layouts, field formatters, etc).

I am now wondering what would be the best way to combine both worlds:

Have SASS sources distributed in distinct (custom module) directories, and some in the theme.
Allow to include sources from other modules. Of course dependencies must be declared accordingly.
Allow contrib modules, or "corporate" modules that are meant to be reused, to ship with SASS sources.
Watch the entire tree with gulp or compass, without watching the toplevel dir.
Generate the CSS files in a common directory, or in distinct directories, I don't care that much.
Have some way to control which generated CSS file is included on a page.

The main limitation of SASS seems to be that it is limited to one directory, where you keep all the source files and that you watch with gulp or compass, and one output directory for the finished CSS files(s). At least this seems to be how it is commonly used. This is not ideal if I want to distribute the CSS across module directories.

For now the question is quite open-ended, perhaps someone already did this and can describe a workflow / architecture.

Platform

The project I am asking this for is currently on D7, but will move to D8 soon. I would be interested in both, but will mark it as "8", and hope I can then apply a similar technique to D7.

Theme CSS vs module CSS?

Some developers have quite strong opinions about the location of CSS files, accepting only the theme as a valid place for anything front-end related. You are free to share such opinions, but please don't make this the only part of the answer!

Is this a Drupal question?

Perhaps the individual technical obstacles are not specific to Drupal. But my use case is, and I am hoping that someone else had a similar scenario.

By concept a contrib module will hardly ever be able to use SASS, because SASS simply is not part of Drupals distribution. But that doesn't mean your local environment cannot use shared SASS resources for custom themes and custom modules.

E.g. in all our projects, the project-specific theme is a sub-theme of a shared, immutable base theme providing defaults and mixins. We are compiling with a bash script using standalone SASS with the --load-path argument:

sass ./web/themes/custom/PROJECT/scss/THEME.scss ./web/themes/custom/PROJECT/css/THEME.css --load-path ./web/themes/custom/SHARED_BASETHEME/scss

in ./web/themes/custom/PROJECT/scss/THEME.scss

@import "default_settings"; /* lives in SHARED_BASETHEME, bunch of $variables with !default */
@import "settings"; /* lives in PROJECT, partially overrides default_settings */

I'm quite certain there is something similar for the Node-Version of SASS (or in Gulp). With a black belt in in Bash-Fu (or in your case: Gulp-Fu) this can be extented to any custom module and any custom theme and vice versa.

Example with multiple themes:
We had one project using Domain access module and one sub-theme per sub-domain and we handled bulk theme compiling with a bash script:

for D in ./web/themes/custom/*/;
do
  if [ -d "${D}" ] && [ "${D}" != "./web/themes/custom/SHARED_BASETHEME/" ] && [ "${D}" != "./web/themes/custom/EXCLUDE_ME_2/" ]; then
    echo "Creating sub-theme ${D}"
    sass ${D}scss/THEME.scss ${D}css/THEME.css --style expanded --load-path ./web/themes/custom/SHARED_BASETHEME/scss
  fi
done


Link a view to another view I have a view block and I want to add a field link so that will displays a view of the content types that I have create not a content type itself is this possible?

You can put almost anything you want in a Views Header or Footer, so if you added a Global Text Area field there, you could put in a link to a page display of a view that shows your content types, and that should do what you want.


Disable autofill username & password on drupal How can tell the browser not to save drupal usrrname and password? I am newbie. So having difficulty understand many functions. Any easy way to configure drupal for this? Thanks

Auto-completion of common fields (text, password, select, textarea, date-related, time-related, numeric, email, and uri controls) is a browser feature but you can tell browsers to turn off auto-completion on form fields by using the autocomplete attribute.

You can use hook_form_alter or hook_form_FORM_ID_alter to add this attribute to your fields.

Example:

/**
 * Implements hook_form_alter().
 */
function example_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'YOUR_FORM_ID') {
    $form['YOUR_FIELD']['#attributes']['autocomplete'] = 'off';
  }
}

Example altering the log-in forms:

function example_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'user_login_block': // Log-in block form.
    case 'user_login': // Log-in form.
      // Username
      $form['name']['#attributes']['autocomplete'] = 'off';

      // Password
      $form['pass']['#attributes']['autocomplete'] = 'off';
      break;
  }
}

You can check out these posts for more info on module development - Module Developer's Guide and Creating Drupal 7.x modules. You can also download the excellent Examples module for reference.


How to prevent non-English characters from turning into jumbled words? Whenever I move database, even within the same server the non-English characters change into words that are unreadable. My site is not multilingual (it will be in the future) but users post products titles with accents and in French, Polish or another language. How do I retain the characters and prevent the jumbled words? Thank you.

This is a bit of a guess, but it sounds like some part of the process isn't UTF-8 clean.  If Drupal is displaying everything properly, then it sounds like the database actually is UTF-8.  This leaves phpMyAdmin.

I would log into phpMyAdmin with Firefox.  Right-click, and do View Page Info.  Make sure the encoding say UTF-8.

Then install the Live HTTP Headers plugin.  Download a backup and restore one with the plugin running.  Make sure the Content-Encoding is always UTF-8.

If any of them aren't, then you have some server-specific configuration to fix.

Personally, I think phpMyAdmin is a terrible tool and a security risk.  I use the legacy MySQL Administration Tool for most of my server work and a fair number of backup tasks.  You can also try the Backup and Migrate module for taking and restoring backups.  You can also use the sql-* and/or bam-* commands in drush.


Ajax on Add another item of field collection I'm calling an Ajax function in a field collection. But after hitting 'Add another item' button, form looses Ajax effect. I want to bind the Ajax with form event after clicking on 'Add another item' button. Can anyone help?

Sounds like you need to use Drupal.behaviors and not just document.ready for your javascript.

  Drupal uses a "behaviors" system to provide a single mechanism for
  attaching JavaScript functionality to elements on a page. The benefit
  of having a single place for the behaviors is that they can be applied
  consistently when the page is first loaded and then when new content
  is added during AHAH/AJAX requests.

More info on Drupal.behaviors here


login programmatically with remember me feature I'm trying to create a custom login form, since I need it to be ajax based. And I can't use the existing modules that do this. So far I have achieved this by setting the global $user object to the loaded user and calling user_login_finalize(). But now I need to make the login persist and I have no idea how the default drupal login does it. Any tips are appreciated. Thanks

UPDATE:

The duplicate question indicated by Pontus Nilsson does not mention in any way how to make the login persist nor how to use the default drupal remember me or the RememberMe module functionality.

UPDATE 2:

I must elaborate that I have installed Remember Me module to make the persistent login optional for the user. Is that a reason why I needed to go through all this hassle explained in my answer to make the programmatical login persist?

This is how I accomplished the remember me feature. Since I didn't find any specific resources on this matter, the proposed solution may or may not be optimal and correct, although it works fine.

You use the following code to login a user programmatically:

$user = user_load($uid);
$login_array = array ('name' => $user_first_query->name);
user_login_finalize($login_array);

After that you have to decide whether to persist the login or not using the provided check box in the login form:

//at this point we need to persist the login by saving the user again
//with the remember_me data. But doing so, resets the user picture.
//So we need to preserve it somehow.
$user_picture_id = $user->picture;
if($_POST['remember_me']) {
    user_save($user, array('data' => array('remember_me' => (int)$_POST['remember_me'])));
}
else {
    unset($user->data['remember_me']);
    user_save($user, array());
}

//restore the user picture id
db_update('users')
    ->fields(array(
         'picture' => $user_picture_id,
    ))
    ->condition('uid', $uid)
    ->execute();

For the part where I have done unset($user->data['remember_me']); I have made sure that the rememeber_me data does not exist from a previous login. I think this should be done in the modulename_user_presave() hook but I couldn't implement it there.

Remember that since the main question is how to persist a user login, I have not provided a full login procedure, for example you should authenticate the user's credentials using the user_authenticate() function.


Sort View by the order of the arguments I have a view that receives some arguments from a questionnaire. In the questionnaire I calculate a list of nodes that's sorted by how well they correlate with the questionnaire. Once my view receives these arguments it will just sort them by their node id, and not the custom ordering I already applied when sending the arguments.

Is there any module that will display my nodes in a view, in the same order the arguments are received from the previous page?

I already tried views_arguments_extra, but this cannot achieve what I'm trying to do.

An example:

in my questionnaire I have determined that the 5 following nodes have the highest correlation:

7: 86%
8: 83%
12: 82%
1: 80%
2: 79%

I will then send this top 5 as an argument to my view.

So I also want my view to have that order:

7
8
12
1
2

I dont know of anyway to sort a view buy the arguments it receives. So this may not be really what your looking for but currently there's no other answers here and hopefully one of these alternative suggestions will help you.

Suggestion 1)

On your questionnaire submit function use views_get_view_result http://api.drupal.org/api/views/views.module/function/views_get_view_result/7 send the arguments to your view as normal you'll get back your 5 top hits but not sorted correctly. You can then reorder the results and manipulate the order the results appear in and print out your manipulated view.

Suggestion 2)

Using Views PHP module http://drupal.org/project/views_php you can create your own sorting with php. You can pass your view the data you need with url's or $_POST get that data in your view and create the sorting using that.

In a nut shell, I dont know how to do what you want, heres a couple of avenues I would probably try..


Custom form submit handler is called, but node is not saved There are many questions about a custom form submit handler not being called, but in my case, the handler is being called; however, the entity is not being saved.  Specifically, I have a custom submit handler on a content type; when I press the button to call the handler, nothing is saved in the database:

function MYMODULE_form_node_CONTENTTYPE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  $form['actions']['submit_publish'] = array(
    '#type' => 'submit',
    '#weight' => 999,
    '#button-type' => 'danger',
    '#value' => t('Submit for approval'),
    '#submit' => array('MYMODULE_draft2submit_callback'),
  );
}

function MYMODULE_draft2submit_callback(array &$form, FormStateInterface &$form_state) {
  $form_state->setValue('moderation_state', 'submitted');
}

So I thought since the node is not being saved, maybe I have to do it manually.  Following this article, I did this:

function MYMODULE_draft2submit_callback(array &$form, FormStateInterface &$form_state) {
  $form_state->setValue('moderation_state', 'submitted');
  $node = $form_state->getFormObject()->getEntity();
  $node->save();
}

However, in this case, the node is saved, but none of the submitted values (the node body, for example) are saved; everything added by the user is ignored, as is the setValue() in my callback.

I only want to set the moderation_state in my custom form submit handler; in all other ways, I want my custom submit handler to be the same as the normal submit handler (i.e., I want it to save the node).  What am I doing wrong?

As pointed out by @Ismini, the entity has to be saved in the submit handler.  The way to do this is, as pointed out by @4k4, to copy the submit handlers for the new button from the original submit handler.  The corrected code is shown below.

function MYMODULE_form_node_CONTENTTYPE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  $form['actions']['submit_publish'] = array(
    '#type' => 'submit',
    '#weight' => 999,
    '#button-type' => 'danger',
    '#value' => t('Submit for approval'),
    '#submit' => array_merge($form['actions']['submit']['#submit'], array('MYMODULE_draft2submit_callback')),
  );
}

function MYMODULE_draft2submit_callback(array &$form, FormStateInterface &$form_state) {
  // Getting the entity.
  $entity = $form_state->getFormObject()->getEntity();
  // Changing the moderation state.
  $entity->set('moderation_state', 'submitted');
  // Saving the entity.
  $entity->save();
}


Trying to get a property of a non-object in 'mymodule_node_access()' In a custom module, I try to make this code work :

function mymodule_node_access($node, $op, $account) {
  if ($node->type = 'devis' and $op = 'view') {
    $field_language = field_language('node', $node, 'field_project');
    $project_node = node_load($node->fields->field_project[$field_language][0]['value']);
    if ($project_node->uid == $account->uid) {
      return NODE_ACCESS_IGNORE;
    }
    else {
      return NODE_ACCESS_DENIED;
    }
  }
}

I get the following notice:

  Trying to get a property of a non-object in mymodule_node_access()

I don't know where the problem is.

$node in hook_node_access() can be either a string for the content-type or a node object.
I had to test if it was a string or an object.

if (is_string($node)) {
  return NODE_ACCESS_IGNORE;
}
else {
  // ...
}


How can I uncollapse a footer menu? I'm theming with Boostrap right now in Drupal 8 and created a footer menu with a bunch of links. The menu is displaying collapsed right now, but I want it to be uncollapsed and display like a default navbar.

While bootstrap displays as collapsed

Edit all of your footer's child menu links and check-mark on each of them show as expanded.


how to achieve a sliding effect to show the rest of elements in a grid, with views I have a view set to grid, displaying 5 items per column. I set it to display 5 items at a time too, but I have 10 items total. What i want to achieve is, when I click on page 2, instead of having it load the rest of thumbs, for them to slide into the position of the first 5 items displayed. It would be something like SlideShow effect, scroll to the left, but instead of displaying a single frame, displaying 5 at a time.

Im using drupal 6x, views, (cck of course), and have slideshow installed but I couldn't manage to figure it our on my own. I appreciate any prompt response.

Here is an example of jquery slide show.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>jQuery Animating an Element</title>

        Animating an Element

Animate Me

    <button id="right">Grow Right</button>
    <button id="text">Big Text</button>
    <button id="toggle">Move Div</button>


Dynamically linking from author name(s) in a View to a nodes by author View I need to have a View that includes an author name with each node that also links to another View showing all the nodes by that author.

Currently I've got a home page View that always shows the most recent node for a particular content type. I added the field 'display name' (a custom field I created for users) to the View so it shows 'First Name' 'Last Name', and that works well.

I also see I can make it a link in 'rewrite rules' but that would be a hard-coded link to a particular author's page. It needs to be dynamic and link to whichever author's page belongs to the author writing the particular article that will be displayed in the View block.

Anyone know how to do this?

Assuming that authors are the user that created the piece of content and not an entity reference field, and that you're using D7:

Create a clone of the current view that you're using, assuming that you want the author's list of nodes to have the same layout/fields/what have you that the current view you're working with does, and create a new page for it.
For the path of the new view, create a path that includes a wildcard (%) such as /posts-by-author/%
Under Advanced, add a Contextual Filter for Content: Author uid. When you put in a user's UID in the "Preview with contextual filters" box above the preview and hit Update preview, it should show you that user's posts.
Now, back to your original view. Assuming that you're using a display format that requires fields, add the Content: Author uid field to your display and set it to "Exclude from display".
Under "Add" there's a "Rearrange" option when you click the arrow next to the Add option. Rearrange the fields so that the UID field is above the name field. This will allow you to use it in the name field when you create a link.
Under "Rewrite results" select "Output this field as a link" and enter the link path with [uid] replacing the wildcard symbol.

Now, when you click on an author's name, it should take you to a page that displays all the nodes created by that author.


How can I display a node create form in a Panel pane? I'm trying to build a Panel page with two columns that are stacked side-by-side. I need the left hand column to display node/add/story, and the right hand column to display node/add/page. How can I do this?

One simple solution is installing formblock. But that won't allow to save the nodes at the same time.

If you dont mind programming, this should be of help.


Passing variables to a block template I am using the following code, but it doesn't work.

drupal_block.module

function custom_blocks_theme($existing, $type, $theme, $path) {
  return [
    'custom_blocks__front_apps' => [
      'variables' => [
        'app' => NULL
      ],
    ],
  ];
}

BlockTest.php

  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#theme' => 'custom_blocks__front_apps',
      '#app' => 'test value',
    ];
  }

custom_blocks__front_apps.html.twig

Hello: {{ app }}

My block is empty.

What is wrong with the code?

I think you should write it like below code.
   /**
    * Implements hook_theme() to add the template definition.
    **/
    function lotus_theme($existing, $type, $theme, $path) {
      return [
        'lotus_template' => [
          'variables' => ['test_var' => NULL],
        ],
      ];
    }

In your controller file
public function build() {

    return array[
      '#theme' => 'lotus_template',
      '#test_var' => $this->t('Test Value'),
    ];

  }

Then in your lotus-template.html.twig
<p> This is the lotus template with a value of {{ test_var }} </p>

Source Define a custom template for module output


Can I disable module menu items? I have a module with a menu which I build like this:

in moduleName.module

function moduleName_menu() {
  $items = array(
    'title' => 'whatever',
    'page callback' => 'something_callback',
    ...
    'type' => MENU_NORMAL_ITEM
  );
  return items;
}

Now I want certain items to be disabled (Clicking them should do nothing, similar to using disabled="disabled" on a <input type="button">). I tried adding '#disabled' => true, as I would do for form items, but that didn't work. How can I disable menu items?

UPDATE

I tried using myTheme_menu_link to disable the menu items. So in the code above, I add 'disabled' => true or 'disabled' => false to certain menu items. Then, my theme_menu_link function looks like this:

function vitrine_menu_link(array $variables) {
    $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  if (isset($element['disabled']) && $element['disabled']) {
    error_log('Hoping to see this somewhere in the log');
    $output = '' . $element['#title'] .  '';
  }
  return '
' . $output . $sub_menu . "
\n";
}

I test it by emptying all caches, which rebuilds the menu, but still, the error I'm trying to log never get's logged. It seems as though my 'disabled' => true never makes it to this function...

This can only be done on the theme layer. Try taking a look at theme_menu_link().


Suppress watchdog a specific log message I would like to tell watchdog not to write the "Cron run completed" to the log while leaving all other messages intact. How can I do this?

Thanks!

There is no special hook for this. The easiest way to fix this in Drupal 8 is overriding logger.dblog service.

According to the official documentation you need implement a class extending ServiceProviderBase and the alter() method as shown below.

<?php

namespace Drupal\example;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;

/**
 * Modifies the logger.dblog service.
 */
class ExampleServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    // Overrides logger.dblog service to exclude some unwanted log messages.
    $container->getDefinition('logger.dblog')
      ->setClass('Drupal\example\Logger\DbLog');
  }

}

The logger itself is extremely simple.

<?php

namespace Drupal\example\Logger;

use Drupal\dblog\Logger\DbLog as BaseDbLog;

/**
 * Logs events in the watchdog database table.
 */
class DbLog extends BaseDbLog {

  /**
   * {@inheritdoc}
   */
  public function log($level, $message, array $context = array()) {
    if ($message != t('Cron run completed.')) {
      parent::log($level, $message, $context);
    }
  }

}


How can I tell which site uses which database? I have a multi-site Drupal installation that's misconfigured. The settings information has been confused, and I need to map databases to particular sites. I am tasked with cleaning up the mess.

For any given database from a Drupal installation, what tables can I look at to see which site was using it?

Big giveaways will be in the variable table, especially the two rows with the names:

site_mail
site_name

As hopefully these are different for each one of your sites.

Perhaps this database query can help you:

SELECT * from variable WHERE name LIKE 'site_%';


Adding a website URL to a Profile Field Adding a users' website link (URL) to a field.
Can somebody please clarify the best approach to this using Profile2 as I cannot seem to find any option for "URL" type in any field. Maybe I'm having a blond moment or just cannot see the wood for the trees, but to save us hours searching online, can somebody advise on the simplest and most obvious solution to users being able to enter their 'website' link (ie: to link to an external URL such as a homesite such as a bandname.com, mybusiness.com).

I am also using Field Collection but presume any created filed type will be similar in setup.

I would envisage the user being able to add such a URL into their profile detial post registration in a similar way to the user DB on drupal.org (ala "Mywebsite").

Thank you.

There's no native URL field type in Drupal 7 but the Link module provides one with lots of features

  With this module links can be added easily to any content types and profiles and include advanced validating and different ways of storing internal or external links and URLs.

Profile2 profiles are entities so adding a link field to one will be an easy task through the UI.


Client needs Ubercart member sign up function, but there is error with edit/option_prices I have a Drupal 7 client with Ubercart installed. They would like to add a Membership feature to their site where the members can receive a discount on their products and services.

We have Ubercart Price Per Role installed (in spite of it not being updated since 2013 which makes me nervous), which has added a nice little Member Price field in Product. I have added a test Product Class called Memberships to allow for membership levels.

I understand that a Role can be assigned to a Product Class through Attributes and Options to allow for membership expiration dates. Attributes and options have worked just fine for other products, but when I clicked the link for 'Note: "Price" column is the default option price. To set option prices per role use the options prices form.' 'I get The requested page "/?q=node/test/edit/option_prices" could not be found.'

Now it is entirely possible that I am trying to do it all wrong and that fixing that error won't get me the solution I'm looking for.   So, I would also like to hear hetherw I just headed down a rabbit hole, as well as finding out why the edit page cannot load.

If there is a problem it sounds like it's an issue with the menu tab links being generated for your nodes; node/test/edit/option_prices isn't a valid path, it should should be something like node/$nid/edit/option_prices.

The module enables that path if the UC Attributes module is enabled. It sounds like you've installed that module so I would substitute "test" with whatever product NID you're trying to test. Once you've confirmed it's working there, you can troubleshoot why your tab link is generating a bogus path.


Programmatically add more than one taxonomy term in Drupal 7 Just a quick question. I'm creating a node and adding a term to the node like this:

 $newNode->field_tags[$newNode->language][]['tid'] = "a digit here";

Fine, but how do I add more than one term per node? I've tried a comma-separated string of digits and an array of digits but neither work.

You can just keep adding to the array the way you're already doing:

$newNode->field_tags[$newNode->language][]['tid'] = "a digit here";
$newNode->field_tags[$newNode->language][]['tid'] = "another digit here";

Or you could loop instead:

$tids = array(1, 2, 3);
foreach ($tids as $tid) {
  $newNode->field_tags[$newNode->language][]['tid'] = $tid;
}


how to use hook_views_query_alter() to modify where condition? I'm trying to modify the where condition of a views query. till now I was successful with altering "order by", but I have no idea how to alter the where condition. I want to check the search_term and if it was in uppercase, transform it to lowercase so the query can find it. also there are some special characters in my language (persian) that I need to replace them before the query runs. anyone can help me where to start or what hooks or views_handlers to use?

<?php
/**
 * Implementation of hook_views_query_alter
 * @param type $view
 * @param type $query
 */
function nashreneydev_views_query_alter(&$view, &$query) {
  //krumo($query);
  //krumo($view);
  if ($view->name == 'custom_search') {
    $search_term = $view->exposed_raw_input['combine'];

    **//$query->where[0]['conditions'][0]['field']= "?????";**
    $view->query->orderby[1]['field'] = "CASE node_type WHEN 'product_display' THEN 1 ELSE 2 END";
    $view->query->orderby[1]['direction'] = "ASC";
    $view->query->orderby[0]['field'] = "CASE node_title WHEN '".$search_term."' THEN 1 ELSE 2 END";
    $view->query->orderby[0]['direction'] = "ASC";
    //krumo($view->query->orderby);
  }
}
?>

the devel result for where condition is as follow right now. :views_combine is equal to %s%.

  CONCAT_WS(' ', node.title, ' ', field_data_body.body_value, ' ',
  field_data_field_author.field_author_target_id, ' ',
  field_data_field_translator.field_translator_target_id, ' ',
  field_data_field_book_tags.field_book_tags_tid) LIKE :views_combine

To add a new where clause you can use, add_where

For example :

$query->add_where(1,'taxonomy_term_data_node.tid', $value, 'NOT IN');


How to render a variable which is having a wysiwyg type format? I am creating a variable in admin section that is of form type #type = text_format to get wysiwyg kind of editor. But having difficulty while displaying the field value in template file.
I am trying to print like below in template file:

print_r(variable_get('web_pagetext', ''));

But in frontend its showing like below:

Array ( [value] => text, text..
[format] => full_html )

How I can remove Array([value], [format]) and only text to get displayed.

You should use check_markup for that:

$item = variable_get('web_pagetext', ['value' => '', 'format' => '']);
$formatted_text = check_markup($item['value'], $item['format');


Maintenance mode says it's on, but site is still available Before attempting to do some module updates, I enabled maintenance mode on the site. I then noticed that the site was still available to all visitors, even though the Configuration->Development->Maintenance Mode page said that maintenance mode was enabled.

I have cleared all caches (via admin pages and drush) several times already, and have checked the settings.php file to see if there was a manual override set. I have also turned the setting on/off several times, logged out and logged back in, etc.

I've never seen this happen before. What else can I try?

Have you checked the permission "use the site in maintenance mode" to see whether it is enabled for other users?


How can I run cron.php via crontab? I'm trying to run cron.php via a cron job set up in crontab on my server via the following command (running every 2 minutes purely for testing while I try and get it working - it will be every 6 hours when fixed);

*/2 * * * * /usr/bin/php -q /var/www/www.mysite.com/crontab-cron.php >>/var/log/server-cron.log 2>&1

The crontab file was needed to work around an error with the include file locations and looks like this;

<?php
$doc_root = dirname($_SERVER["SCRIPT_FILENAME"]);
chdir($doc_root);

include_once './cron.php';
?>

However now I'm receiving the error (shown in the cron log file)

PDOException: SQLSTATE[28000] [1045] Access denied for user &#039;root&#039;@&#039;localhost&#039; (using password: NO) in lock_may_be_available() (line 167 of /var/www/www.mysite.com/includes/lock.inc).

I've come across a few suggestions mentioning creating a new database user with the same permissions and changing those details in settings.php but that's not making any difference.

Any ideas how to get this working? I just need to run the cron job via crontab.

You could run the cron URL that Drupal provides in Administration > Configuration > System > Cron.

And in your crontab, instead of invoking the cron.php file individually (won't work), you just have to invoke a URL. This can be done with wget, lynx, curl, etc. E.g.:

With wget:

0 * * * * wget -O - -q -t 1 http://www.example.com/cron.php?cron_key=<key>

Configuring cron jobs using the cron command


How can I apply some value with HTML tags to a form element? I've assigned some value with HTML tags to a form element, say the element is called name.

When it returns the form, it exactly prints the value along with the HTML. What I want in return instead, is the style applied to the text.

In this what I'm trying to do is hook_form_FORMID_alter().
This is the page where comments are listed(admin/content/comment). In this, for each comment I'm showing the subject comment and author etc. Also a collapsible tree for editing the comment with pre filled values in the fields.

$form['name'] = '<b>Fazeela</b>'
return $form;

Use css.

Example:

If your $form['name'] is a div with an id wrapper,

Fazeela

Include a css file in your module file, particularly in hook_init function.

function NameOfYourModule_init(){
   drupal_add_css(drupal_get_path("module", "NameOfYourModule") . "/mycss.css");
}

mycss.css file

#wrapper{
    font-weight: bold;
}


Changing the logic for an exposed taxonomy select in a view So, I have a view of a content type, and this content type has three unique taxonomy terms it are: Alpha, Beta, and Both.

Currently, my view lists all nodes of this type, and I've added an exposed filter that lets the user select one and only one of the three terms above, like so:

Both -> Show only content tagged Both

Alpha -> Show only content tagged Alpha

Beta -> Show only content tagged Beta

What I would now like to do is extend the behaviour of the filter so that the following happens:

Both -> Show only content tagged Both

Alpha -> Show only content tagged Alpha and Both

Beta -> Show only content tagged Beta and Both

So as you can probably see, if something is Both, then it is also Alpha and Beta. Obviously the taxonomy terms themselves don't contain this semantic information.

I cannot use "All" to represent Both because then selecting Both -> Alpha, Beta, Both.

So I'm thinking that somehow I could make Alpha and Beta a child term of Both, and Better Exposed Filters might allow this logic to work? Or will I need to use a hook - if so, which hook and any ideas about how I might approach it?

You need to use hook_views_query_alter(). And the logic would be as below.,

Both -> Show only content tagged Both
When the user selects the Both, make no changes in the hook, just return the default result. So by this way the contents tagged under Both will be displayed.

Alpha -> Show only content tagged Alpha and Both
Now use the alter hook, by default the query will have alpha's tid in it. Here you need to add the Both's tid to the query. So now the Alpha and the Both will be displayed.

Beta -> Show only content tagged Beta and Both
Now use the alter hook, by default the query will have Beta's tid in it. Here you need to add the Both's tid to the query. So now the Beta and the Both will be displayed.

In simple term, just use the alter query and add the Both's tid to it. So that we will get the Both's content in all cases.


What are the issues with overriding nodes with views? I am thinking that I have a couple of content types that views would be better at displaying my content. e.g. If an image field is blank, show this default image (this is only a basic example where a view would be preferred over Drupal's default node. i.e. I want to create a view with the node id as an argument and set the views page path to node/%. Are there any drawbacks to this?

You could, however, do something like this in node.tpl.php:

<?php if ($node->type=='FANCYTYPE'): ?>
  <?php print views_embed_view('name_of_fancy_view', 'default', $node->nid); ?>
<?php else: ?>
  // the rest of the normal node.tpl.php stuff here
<?php endif; ?>

or create a node-TYPE.tpl.php (D6) or node--TYPE.tpl.php (D7) with just the Views logic inside.


Conditional display of views based on comparing node taxonomy and user taxonomy I'm using drupal 7 and working on a site that displays nodes based on a user's taxonomy option. A quick example, i want users to make a blog entry and select a taxonomy option "Target audience". The target audience contains selected "Interests" of logged in users. Both "target audience" attached to node and "Interest" attached to user profile are from the same taxonomy vocabulary, so that when a user selects a target audience, he matches a user interest.

Is it possible to build a single view of all blog enteries and then display parts of the view based on certain conditions like "if blog entry is tagged with taxonomy value which is equal to the interest of logged in user,  then display blog enteries which match the logged in user's interest.

Another use case is this: taxonomy value location = New York. Blogger makes a post and selects target audience = New York. User logs in with selected location = New York (mandatory during registration), view checks if target audience = user location, then displays only posts tagged with "New York". Another user logs in with location = Washington, but there are no posts with tag = Washington, views empty field is then displayed or default display is used (when all conditions fail).

I'm also using panels. currently with panels, to achieve this, i have to build a separate view for each user with selected taxonomy option. This makes it cumbersome because, for instance, to display for all users logged in from 52 cities, you have to create 52 views. My intention is to build a single view that decides what to display based on the checked conditions.

Help is greatly appreciated. Thanks

First, your view needs to be set up with a display of type "Content Pane". For this to be possible you need to enable the Views Content Panes module which is part of Ctools.

Next, you need to add a contextual filter (also called an argument) for your taxonomy field. The option to do this is under Advanced on the Views UI for the view. The process is similar to adding other parameters to a view, so I'll not cover it in detail.

Once the contextual filter has been added you need to ensure it can be supplied by the panel you are going to add it to. To do that, click on the Edit link next to "Argument input" under Pane settings. Set the source of the argument to be "from context" and the required context to be "term ID of first term".

On the panel editor, you need to add a context for the logged in user. On the contexts tab for the panel, select "user" for the type of context to be added, then press the add context button. Choose suitable identifiers for the user context and select the "logged in user" option, then hit Finish.

Now from the same tab, under Relationships, you should be able to find an option to add a taxonomy context via the user context. It'll be labelled something like "Taxonomy term from User (on User: fieldname [field_fieldname])". Add it and assign it a meaningful identifier.

Now finally you should be able to add your view display pane to the panel. On the content tab, you'll find it under "View Panes" on the add content dialogue. After you click on it you should see the settings for it, which should consist of a selector linking the contextual filter from the view to the context from the panel. If there is only one taxonomy term context available, the correct value will probably be already correctly set. Save everything and test.

Good luck!


Rules reaction: "After updating an existing user account" reacts on user login I have a rule that I use to create a group node for user when user gets a new role. A group node was created for the user when she got the new role but unfortunately a group keeps getting created for the user whenever she logs in. Not sure of what is going on. How do I fix this? Thanks!

What event are you using to trigger the node creation? It sounds like maybe there's a "User has logged in" event somewhere in the chain.

The Rules module can be flakey. (I love it but it drives me crazy sometimes.) If you can't figure it out, you could try to preempt the problem by adding a check to the event where you create the group node to see if a group node already exists before adding one.


View that only shows content that have a certain date? I have a view that I am using to list events, specifically "today's events." it was relatively easy to create it, say that I want it to sort by time, but what I am wondering, is how can I  filter it to only show events that are happening on the day that it is displaying. I am using the date module's CCK in order to create the date. I would assume that I would use the date start time, but I can't figure out how to filter that start date.

Filter by the start date with granularity of day.  When you setup the filter, you can specify operator Is equal to and in the Date default field use the keyword now to default to the current date at runtime.


How to add a Custom Operation in the Book Admin Edit Form's Operations? As the title says I want to know how to add a custom operation in the drupal 8 book admin edit form's operations. I need this for my module in which I want to provide Add Sub Page operation for the user.

Upon clicking on the operation, I want to execute a function to add a new page to the parent page. I know how to add pages programmatically (Thanks to Lisa regarding help for adding pages in the book) , the only thing that I need is this operation entry in the drop down list.

Can somebody please help?

You can override the bookAdminTableTree() method in the BookAdminEditForm class by extending core/modules/book/src/Form/BookAdminEditForm.php with your own custom form class. You can copy the bookAdminTableTree() method's code and then add an item to the $form[$id]['operations']['#links'] array for 'add-sub-page' (or whatever you want to name the new operation.)

Then alter the existing /admin/structure/book/{node} route (book.admin_edit) in book.routing.yml with a route to your new custom form class.  See www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones and the setDefault() method in the Route class: api.drupal.org/api/drupal/vendor%21symfony%21routing%21Route.php/class/Route/8.2.x

This is a helpful tutorial that describes the overall approach: https://www.jaypan.com/tutorial/drupal-8-extending-core-configuration-extending-core-forms-and-overriding-core-routes


Setting up Multiple Databases on a current site I'm having issues with my current shared hosting provider due to my core database exploding upwards of 1GB due to cache_form. I've been looking at trying to offload the cache and revisions databases into different databases entirely and set them away in order to hold down the load. I think my understanding of how is ok but I want to be sure as this is a current live site.

I declare the default database then declare where each table is explicitly in the prefix array. If this is accurate then I will just do it that way, if not then I'd like to know where I'm going wrong. Do I need to explicitly declare ALL my databases first in settings.php or do I need to declare just my default and let it work that way?

I think I figured out what to do in order to pull this off. The issue was that the documentation in default.settings.php was rather lacking but I managed to piece it together. You do have to set your tables up explicitly and your databases as well. It has not helped the issue at all, and frankly it concerns me due to the issues with Drupal 8 coming that frankly might not be usable. So I'm going to pursue a different course of action on this.


How to remove inner div from create block in drupal 7 Here, i struggling to remove inner div from create block in drupal 7.Here my working code with wrong result:

<?php  if($page['footer_bottom_left']){ print render($page['footer_bottom_left']);} ?>

  <?php  if($page['footer_bottom_left']){ print render($page['footer_bottom_right']);} ?>

I used string_tags before render it remove entire html tags. But i need to remove only block div and content div.Here my wrong result:

Plan du site

Acessibilite

Credits

Mentions legales

Correct format:

Plan du site

Acessibilite

Credits

Mentions legales

How to remove inner div from custom block in drupal 7.Kindly guide me..?

The markup you require removing comes from one or more template files. While i have no idea what theme you are using, ill assume its one that hasn't overidden the default template files..

If you go and get the file modules/system/region.tpl.php and copy it to your theme folder you can remove the markup you do not require. e.g. delete <div class="region region-footer-bottom-right">

To get rid of the rest of the markup you will have to override the block template in the same fashion, to only remove the markup from 1 specific block you can use naming suggestions here https://www.drupal.org/node/1089656

note: Flush the caches for the theme to pick up the presence of any new template files.


D7 Rules - Unable to get data value & Unable to evaluate action in custom module I am working on a module that gets the order data upon commerce checkout completion and sends it to an api elsewhere for processing. In testing, everything was working fine until I called my method from my rule, which led me here.

I am wondering if my inexperience with Drupal has caused me to make an error in defining my rule. Any additional information that can point me in the appropriate direction is always welcome.

I have researched this topic rather intensely and did not find any solid remedy, please don't assume I have not searched. I assure you I have, I have been stuck on this issue for 4 days now :/  Thanks in advance.

Here is my rule:

function my_module_rules_action_info() {
  $actions = array();
  $actions['my_module_sync_inventory'] = array(
    'label' => t('Sync inventory'),
    'callbacks' => array(
      'execute' => 'my_module_rules_sync_inventory'
    )
  );
  return $actions;
}

and here are the defaults:

function my_module_default_rules_configuration() {
  $rules = array();
  $rule = rules_reaction_rule();
  $rule->label = t('Sync Inventory on Checkout');
  $rule->tags  = array('Commerce Cart', 'Commerce', 'Inventory', 'Sync');
  $rule->weight = 20;
  $rule->active = TRUE;
  $rule
    ->event('commerce_checkout_complete')
    ->action('my_module_sync_inventory');
  $rules['my_module_sync_inventory'] = $rule;
  return $rules;
}

this is the callback

function my_module_rules_sync_inventory() {
  global $user;
  $data = commerce_cart_order_load($user->uid);
  // ... process data
}

For any future readers who encounter this issue:

It turns out the answer all along was using the hook_commerce_checkout_complete in my module, rather than trying to insert an action with rules.

Here is an example I used for debugging:

function MYMODULE_commerce_checkout_complete($order){
  $file = fopen("checkout_debug.json", "w") or die("Unable to open file!");
  fwrite($file, json_encode($order, JSON_PRETTY_PRINT));
}

of course the reason I used json_encode is because $order is not a string and I could pretty print it.

Hope it helps someone, eventually. Thanks again.


Automatic Google translation when there is no real translation I have a multilingual site.

I want it so that if a user has chosen French as they preferred language, but no French translation exists for a particular page, then an automatic Google Translation is displayed.

I have tried doing things like installing the Google website translation module:
https://translate.google.com/manager/website/
but this of course cannot display the proper translation if one exists because it does not integrate with Drupal. I have also looked at options like GTranslate https://www.drupal.org/project/gtranslate, which has a Drupal module but that does not integrate properly with Drupal multilingual sites.

Any suggestions for a solution to this? The only way I can think of doing it is to The Translation Management Tool (TMGMT) module and to use Google translate all pages and have those Google translations as proper Drupal translations, although this has disadvantages as well in that it will be cumbersome to do with this hundreds of pages. Any ideas?

I have an idea that we can achieve using gtranslate language dropdown (hidden) and drupal langauge dropdown

Steps
in hook_preprocess_page check node has translation if yes make the page is not google translatable using class "notranslate"
if it has not translation then pass the language code to javascript and call google translate function

For Exampel:
/**
 * Implements hook_preprocess_page().
 */
function hook_preprocess_page(&$variables) {
  $variables['attributes']['class'] = [];
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();

$variables['attributes']['class'][] = 'node-' . $nid;

if(isset($variables['node'])) {
    $nid = $variables['node']->id();

    if($variables['node']->hasTranslation($language)) {
        $variables['attributes']['class'][] = 'notranslate';
    }
    else {
        $variables['#attached']['drupalSettings']['language'] = $language;
    }
}

}

In Custom.js

doGTranslate('en|' + drupalSettings.language);


Use term reference field in node--custom.tpl.php I am building a website with Drupal 7, this website contains a blog. For some reasons I use a custom content type for blog posts call bog_post. In this content type I add a "Term reference" field (is machine name is "field_blog_categories").

To custom the layout of blog post I override node--blog_post.tpl.php. My problem is to display the term reference field. When I print the php var corresponding to that field "$field_blog_categories" I get :

Array ( [en] => Array ( [0] => Array ( [tid] => 8 ) ) )

As you can see the term name don't appear. I thought to get the name by tid. I try

taxonomy_term_load($field_blog_categories['en'][0]['tid'])

but it return nothing.

Any help to get the term name will be appreciate !

If taxonomy_term_load() return false then

the supplied argument (tid) is either non-numeric
Or there is no term with this id.

To check if there is any term against this id try

`taxonomy_term_load_multiple(array($tid), array());`

If taxonomy_term_load_multiple() returns empty array then it is clear there is no term with this $tid.


Permission to see hidden fields There is a node type with hidden fields. Anyone can find nodes of that content type from the search form, and see open information. To see all the fields, users must make a request to the node owner, who decides the users who can see, or not those fields.

Is there any module with this purpose? Is there any other way?

I think you can accomplish this with the field permissions module. You can then specify that users without permission cannot view the field.

Secondly, create a new user role for the people who can see the field. When a user makes a request to see the field, you can set the field permission to view the field by assigning the new role to that user.


Flag, flag link, and flagging: create an advanced relationship On my site I have two content types:

event – with node flag “Attend” and Entity Reference field
band

And flags:

“Attend” – node flag - with Entity Reference field
“Accept” – flagging flag – connected to “Attend” flag

Each user can create unlimited number of Bands (he is manager of each Band) and create unlimited number of Events.
On Event creation form I add Entity Reference field with list of user Bands. This way band which he choose will become an Event organizer.
And now: other Users can click on flag “Attend” in Event node. On next step they need to choose witch of their bands will participate in this event (entity reference field)

Quick example:
“User 1” create “Band A”, “Band B” and “Band C”
“User 2” – “Band D”
Events and attendance:
“Band D” is the  organizer of the “Event A”. “Band A”, “Band B”, “Band C” want to attend.
“Band  A” create “Event B”. Attend: “Band D”,
“Band D” create “Event C”. Attend: “Band B”, “Band C”

In views I create a private page with table of events of each user. I add all necessary relationships to show Events of each user with list of bands which use “Attend”.  Please imagine it as a table:

Band A – 1 event:

Event B

Band D – “Accept flag”(flag link)

Band D – 2 events:

Event A:

Band A - “Accept flag”
Band B - “Accept flag”
Band C - “Accept flag”

Event C:

Band B - “Accept flag”
Band C - “Accept flag”

User (author) creator of the event using flagging flag can decide which band he Accept for event.

Problem:
When Band D click “Accept” for Band B under Event A the status also change in Event C.
Do you think it is possible to separate this?
I hope I have described all process clear enough.
Thank you!

Using Drupal rules module you can set up the right triggering conditions. It is possible to use rules to alter the data in fields arbitrarily, however your question is a little confusing because bands are also described as users, so you would need to make use of user related fields in the rules configuration. Take a look at the large rules documentation section and this intro to the rules module to get an idea. Flag module is compatible with rules.


Have administrators approve user accounts after users confirm their e-mail addresses and set passwords For my current Drupal 7 project I set up the account creation process the following way:

User can register for an account.
User will receive an email telling him that the account needs to approved by the administrator
Email is being sent to the administrator asking him to approve the account.
Once the administrator has approved the account another email is sent to the user with a link, leading the user back to the portal to set his new password and to log in.

What I am after is a slight change to this process:

I want the user to get the email first to set his password and therefore confirm his email address.

Once that is done I want the email being sent to the administrator to approve the account.

Is that possible?

Thanks, Uwe

Easiest way is kinda like what frazras said, leave the regular auth process but use rules to send an email to admin group/role when a user confirms registration.

You'll probably want to use views to create a view then that looks for the user role (the default confirmed user) and create a confirmed or approved user role (be sure to strip the user role of all permissions & grant permissions to your new role that are how you want them). In the view you are creating make sure to exclude anyone that's a member of any role other than just user & maybe anon.

The link to that view in an email to admins makes it easy to monitor You could probably put in a link to approve via the email though I'd strongly advise not letting users approve users without verification unless you're comfortable with your ability to secure it.

http://drupal.org/project/Rules
http://drupal.org/project/views


How can I get uploaded files sent to webforms to be attached to an email? In Drupal 8, uploaded image files sent to a Webform are uploaded to a private area.
The image files are referenced in the email that is sent to the administrator for that form, but unless they are logged in and access the email through the webforms results interface, they cannot see the file. It appears as a broken image in the HTML email.

I've installed SwiftMailer and Mail System modules per https://www.drupal.org/node/2837024 but installing and enabling the modules has not solved the problem.

The steps to get uploaded files to be sent as attachments to be included in emails from Webforms go as follows:

Install SwiftMailer and Mail System Modules
In Mail System Module Configuration, add Webform Module and set Handler and Mailer to Swift Mailer
In Swift Mailer Configuration, Messages tab, set to HTML (may not be necessary, but it worked for me.
In Structure..Webforms..[your webform name]..Settings..Email/Handler..Edit..Advanced Tab set the check box for include files as attachments

The body of the email still has a broken image, but the files are attached.
I believe I can modify the body of the email to just include the fields that I want by expliciting naming each one, however, if you uncheck the fields that are "broken" in Included Email Values (hoping to continue to use [webform_submission:values] in the body template) the email does not show the broken connection but it also no longer includes the attached file(s)


Drupal 8: Best practice to get nid in form_submit I can get nid from within form_submit by using one of those snipet:

$form_state->getFormObject()->getEntity()->id()

or

\Drupal::routeMatch()->getParameter('node')->id()

If feel this is a little bit overkilling... what is the best way?

You're looking for $node = $form_state->getFormObject()->getEntity().

Oh, saw that you actually mentioned that. This is the correct way to do it.


Is it possible to change a view from a user view to a node view? I have a view that has a couple of displays and a lot of complex field definitions. I now realize the view may have been created by cloning the wrong starter view. Something went wrong such that the view is based on user and the base_table = 'user' when it should be based on nodes. Can I change it to be based on nodes? Or is there a quick way to add my display and field definitions to a newly created node view, perhaps by exporting both and copying over bits of the code? I'm using Views 2.

There is no automatic way to convert a user view to a node view or vice versa.

Although you probably could get away with manually combining the fields from the export of your user view with a plain export of a new node view, it would be faster and a lot less problematic to just open the old view and your new view side by side in two browser windows and recreate everything.

Unfortunately a lot of Drupal site building is just checking checkboxes...


Drupal Calendar, why some events appear as "all day" events even if they are not "all day" events? Why some events appear as "all day" events even if they are not "all day" events in Calendar Views?

As you can see, these events have just a start date defined at 00:00. But they are not "all day" events:

This is probably an old "bug" in calendar: https://drupal.org/node/881224
Have you tried to give your dates an end date?


Views: changing the language for taxonomy terms Is there a way to display taxonomy terms in a language given by a Views argument, i.e. to override the user's language preference? The field formatter "Plain text (localized)" doesn't do the trick.

Example:

Tab one: English

Africa

Story 1
Story 2

Middle East
Europe

Tab two: Français

Afrique

Histoire 1

Moyen-Orient

Histoire 2

Europe

The stories are a single content type, but completely different pieces of content (not translations). I'm using quicktabs to render this.

Edit: the taxonomy terms are already translated via the i18n module, the question is about getting Views to display the translation I want.

By default views doesn't allow to filter the taxonomy terms by the language, only with nodes.

But, you can use the Internationalization Views:

http://drupal.org/project/i18nviews

After you enable the module go to relationships and add "Content: Taxonomy terms on node"
Then you can find " Taxonomy term: Language " under filters. This should do the trick.

Good luck.


Url problem due to htaccess I uploaded my website here . But when I check the url it doesn't change when I click another page. I used the Rewritebase in my .htaccess to have clean urls. The url should be like kantoorleenknegt.be/contact ....

This is not really a drupal question. You are seen the website through a frame
The real url is http://31.186.174.215/~leenkneg/ where the urls work as expected.

To answer your question after the info you gave.
One solution is to add an A record to the DNS of the domain. So every http traffic will land to your site but without the users notice and the can have the emails where they want.

So you will have the hosting and the can keep the emails.


Customize Order Items table on admin order screen On the order edit admin screen at /admin/commerce/orders/270/edit, how do you customize the Order Items table? I've been looking all day and can't figure it out. There's a view that controls this same table on a user's orders tab, but it doesn't seem to affect this screen. All I want to do is add a column for the item's SKU and I would have thought that to be a pretty straightforward change.

Thanks!

I mentioned this above in a comment, but the reason this takes more work than editing a View is because there's no simple way for a field widget to use Views to build part of a form. You can easily use Views to render content, and you can even use Views to construct a complete form, but using it to embed part of a form inside another form is not likely to happen.

There is a more straightforward way to customize the table if you're interested, based on the fact that the Inline Entity Form module gives you two ways to override the fields shown in the table of its "complex" widget.

If you anticipate making more holistic changes to the behavior of the inline form, you might consider setting a custom inline_form handler for order items via hook_entity_type_alter():

use Drupal\custom\Form\CustomOrderItemInlineForm;

/**
 * Implements hook_entity_type_alter().
 */
function custom_entity_type_alter(&$entity_types) {
  $entity_types['commerce_order_item']->setHandlerClass('inline_form', CustomOrderItemInlineForm::class);
}

Your handler class would inherit the default OrderItemInlineForm class and override its getTableFields() method to return a different fields array that adds your SKU field in the right place:

namespace Drupal\custom\Form;

use Drupal\commerce_order\Form\OrderItemInlineForm;

/**
 * Defines the inline form for order items.
 */
class CustomOrderItemInlineForm extends OrderItemInlineForm {

  /**
   * {@inheritdoc}
   */
  public function getTableFields($bundles) {
    $fields = parent::getTableFields($bundles);

    $fields['sku'] = [
      'type' => 'callback',
      'callback' => 'custom_order_item_sku',
      'label' => t('SKU'),
      'weight' => 2,
    ];

    $fields['unit_price']['weight'] = 3;
    $fields['quantity']['weight'] = 4;

    return $fields;
  }
}

Alternately, you can just implement hook_inline_entity_form_table_fields_alter() to do the same thing:

/**
 * Implements hook_inline_entity_form_table_fields_alter().
 */
function custom_inline_entity_form_table_fields_alter(&$fields, $context) {
  // Note: you'd want to check the context here to only alter the desired table.
  $fields['sku'] = [
    'type' => 'callback',
    'callback' => 'custom_order_item_sku',
    'label' => t('SKU'),
    'weight' => 2,
  ];

  $fields['unit_price']['weight'] = 3;
  $fields['quantity']['weight'] = 4;
}

Note that when you define the field for the Inline Entity Form table to include, since the SKU doesn't come from the order item itself (which is what is rendered in that table), you can't just use the 'field' type - you have to define a custom callback. Your callback is a simple function that can load the purchased entity from the order item, confirm it has a SKU, and then return it for display:

/**
 * Returns the SKU for the product referenced by an order item.
 */
function custom_order_item_sku($entity, $variables) {
  // Extract the purchased entity from the order item.
  $purchased_entity = $entity->getPurchasedEntity();

  // If the purchased entity couldn't be loaded or doesn't have a SKU...
  if (!$purchased_entity || !$purchased_entity->hasField('sku')) {
    // Return a placeholder string.
    return '-';
  }
  else {
    // Otherwise, return the SKU itself.
    return $purchased_entity->getSku();
  }
}

I tested this myself locally and it worked like a charm. : )


Display node in view only I've created a views slideshow which uses a custom content type for each slide.
However I want to prevent any user to access these nodes using the url itself like .../node/1.
There seems to be a module from another stackoverflow post, but it's not supported by drupal 8.

You'll want to use the Rabbit Hole module for this.

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

You can block the view route for nodes by content type.


What will happen if I restore backup DB with empty session table? It seems that only the session is really big compared with other tables.
Is there any bad effect to Drupal site if I restore my backup Mysql file after deleting all the rows in session table?

The main issue is that people will need to log in again.

A side effect of this is that any session data that your site may have saved for users will also be gone.  This is usually a nuisance, and not a major problem, though.

Personally, I have never had any problems caused by either not restoring {sessions} or manually clearing out the table, either via DELETE FROM {sessions} or a drush command.


Removing text from the Drupal interface I remember in Drupal 6 there was a module that did text substitution easily (from text that appeared anywhere in the interface). Does that exist in Drupal 7? I just want to remove the word "From" everywhere it appears on this Drupal commerce site:
http://hum.homedns.org:8888/acmefilterbags2/product-category/featured-kits
thx!

UPDATE: I tried String Overrides, thought that would do it, but did not. Any ideas?

I think it's not a text of Drupal Interface.

Add .price_prefix { display: none } to your theme's css file and it will disappear.


Can I manualy add modules in Drupal 7 just by pasting them in the modules folder? I am unable to install modules in Drupal 7. I'm working on localhost so I don't have FTP, but it seems that they made it impossible to install them otherwise.

In Drupal 6 I would of just paste a module, refresh and there it was. Here I have to specify the FTP.

If you have a single site setup:

Contrib modules go in /sites/all/modules/contrib/

Custom modules go in /sites/all/modules/custom/

Custom themes go in /sites/all/themes/

If you have a multi site setup:

contrib modules go in /sites/site_name/modules/contrib/

custom modules go in /sites/site_name/modules/custom/

custom themes go in /sites/site_name/themes/

I think some of the language in this post is dangerous, remember, do NOT put modules in the root modules directory, that is DRUPAL CORE.  Everything you code and download should go in the directories I've mentioned above.


What's best practice when working with the language[und]? I'm starting to use this form to access data in my module. (See comment #1.)

$node->field_test[$node->language][0]['value']

I thought that looked like a pretty good solution, but further down that same question I found this:

  Don't assume that 'und' is for fields of entities without language, it is also for fields that are not translatable, and without the entity translation module that is all fields. Moreover, there are differences in this between the various 7.x versions of Drupal.
  Better to use the field_get_items() function which will sort out for you under what language code the data is stored.

And now I don't know if what I'm using could break something down the road.

I find that using the Entity API module is a great help and also makes code more readable. The above code will not always work, since the language of the node and the language of the field can be different.

With the entity API module, and its wrapper, you can use the following code:

 $node_wrapper = entity_metadata_wrapper('node', $node);
 $field_val = $node_wrapper->field_test->value();

This should be bullet proof. One thing about using the entity module is that if you try to access a field that doesn't exist, you will get a nasty error and an exception thrown instead of a notice and wrong behavior.

To avoid this, you could do try/catch like this

try {
  $field_val = $node_wrapper->field_doesnt_exist->value();
} catch (EntityMetadataWrapperException $e) {
  $field_val = 'default/fallback value';
}

Or you can use isset() which EntityMetadataWrapper handles internally:

$field_val = 'default/fallback value';
if (isset($node_wrapper->field_doesnt_exist)) {
  $field_val = $node_wrapper->field_doesnt_exist->value();
}


How to get the feeds log entry from hook_feeds_after_import I have a feed and I want to email the log entries from feeds_log after it has completed a run. I thought that if I could get the feed_id, I could query the db to get the log entries.

I'm using hook_feeds_after_import(), which gives me access to the $source object, but in looking through some documentation, I don't see a way to get the feed_id.

How can I get the log entries from a feed run?

From hook_feeds_after_import($source), I have access to $source->imported, which is the timestamp value in feeds_log.request_time. So I have

$result = db_query('SELECT message, variables FROM {feeds_log} WHERE request_time = :imported',
    array(':imported' => $source->imported) );


How to change "Read more" and "Add new comment" link to an image in teaser view? On the project that I'm working on now I need to display the "Read more" and "Add new comment" links in my teaser as images in sepperated divs.

The problems that I have is:

I'm using "display suite" to show my content but it only gives me a "Read more" link no "Add new comment" link
I need to hide the tekst and display only the image. (see link "read more" part)

Here is a png of what i need to have:

Thx up front for any help you can give me!

You can display both links enabled the "links" field in "manage display" page. The "display suite" module redirect to default content types manager.

Path to this page; Administration » Structure » Content types » Your_content_type » Manage display. Don't forget to select the view mode "teaser" in the upper side of the page to display all the fields associated with this view mode.

If you want to change the output, you will have to code the changes. We have different alternatives to reach to the same place:

Implement in your theme template or in your_module.module the hook hook_preprocess_node .  We examinate this function:

/* Tip 1 => You have to change 'yourmodule' for the real name of your module.
* For example, when you create a file like apple.module where you will write your code,
* 'apple' will be the machine name to implement hooks. Following the example,
* the name of this hook in apple.module should be apple_preprocces_node()
*/

function yourmodule_preprocess_node(&$variables){

  // Change *your_content_type* for the machine name of your content type
  // In your database, node_type table, you can see the machine name of your content types
  // By default, Drupal comes with 2 content types called Article and Basic Page,
  // but i assumed that you created a new type.
  // The reason of applying a conditional statement is we only want to apply these changes to a specific type,
  // because it's probably that you will use them to build theme like articles to build a blog.
  if ($variables['type'] == 'your_content_type' ){

  // Change the link node read-more
  // I am changing the title of the link. The text stay in the code,
  // but it's invisible.
  // Default text received in array => 'Read more about ...'

    $variables['content']['links']['node']['#links']['node-readmore']['title'] = 'Read more about ...';

  // We only have hidden the text with the span tag.
  // With css you can display the image you want

     $variables['content']['links']['node']['#links']['submitted']['title'] = $variables['submitted'];
     $variables['content']['links']['node']['#links']['submitted']['html'] = TRUE;
     $variables['display_submitted'] = FALSE;

  // -----------------------------------

  // We apply tha same strategy

  // Change the link node add-comment
  // Default text received in array => 'Add new comment'

    $variables['content']['links']['comment']['#links']['comment-add']['title'] = 'Add new comment';
    $variables['content']['links']['comment']['#links']['comment-add']['html'] = TRUE;

  // With css, the link looks better.

  } // end if

}

You could build your own functions that build the output that you want. This possibility will give you a great power of customization. For example:

 function theme_link_YourContentType_readMore($variables){

   // Build your code and return it

 }

 function theme_link_YourContentType_addComment($variables){

   // Build your code and return it

 }

 // Finally, you need to tell to the system that apply the theme functions that have been built previously

 function yourmodule_preprocess_node(&$variables){

   $variables['content']['links']['node']['#theme'] = 'link_YourContentType_readMore';
   $variables['content']['links']['comment']['#theme'] = 'link_YourContentType_addComment';

 }


Cannot use string offset as an array in includes\form.inc on line 3575 Before creating "form" custom module, everything was fine. After creating this module, I have got the following error message:

  Cannot use string offset as an array in includes\form.inc on line 3575

I deleted the entire custom module folder, and cleared the cache as well. Still, I am getting the same error when modules page.

How do I overcome this error?

coding inside the form.module page is

        function form_menu() {
      $items = array();
      $items['form/form'] = array(
        'title' => t('My form'),
        'page callback' => 'form_form',
        'access arguments' => array('access content'),
        'description' => t('My form'),
        'type' => MENU_CALLBACK,
      );
      return $items;
    }

    /**
    * This function gets called in the browser address bar for:
    * "http://yourhost/form/form" or
    * "http://yourhost/?q=form/form". It will generate
    * a page with this form on it.
    */
    function form_form() {

      // This form calls the form builder function via the
      // drupal_get_form() function which takes the name of this form builder
      // function as an argument. It returns the results to display the form.
      return drupal_get_form('form_my_form');

    }

    /**
    * This function is called the "form builder". It builds the form.
    * Notice, it takes one argument, the $form_state
    */
    function form_my_form($form_state) {

        // This is the first form element. It's a textfield with a label, "Name"
      $form['name'] = array(
        '#type' => 'textfield',
        '#title' => t('Name'),
      );
      return $form;
    }

Deleting the module folder outright, without uninstalling it through the UI/Drush (even manually in the DB) is bound to cause a few problems.

To get rid of any errors caused by Drupal thinking the module files are still there, you can simply delete the row in the system table which corresponds to the relevant module; but make a database backup first, of course.

In case you haven't come across the pages before, you can disable modules at http://mysite.com/admin/modules and uninstall them at http://mysite.com/admin/modules/uninstall through the UI, or use Drush.


Taxonomy filters don't display results - Drupal 7 I've updated the taxonomy module to the last version, so after doing this I've noticed that clicking on one category or on one tag of my blocks inside the blog area will produce a page without results.

I've already checked if it was a pathauto fault, and it seems work fine and the settings inside there are right. The field in my blog content type concerning tags and categories are already there, and they are linked to the taxonomy vocabularies.

So at the moment I'm alone in the dark, does anyone knows how to help me in order to sort out this problem?

Many thanks.

So far I've found the right solution to this issue. I will write down it as who will have the same problem can sort it out.

To solve this problem I was just needing to create again the panel-page that I've used to create the taxonomy pages.

Why I was needing to do it? - It's simple, because when there's a new update if you have any entity that is pointing to a module's variable or whatever about that module and something is obviously changed in its implementation after the update, then this entity is pointing to the old representation of that variable/whatever of that module, so obviously drupal will show you an empty set as a result of a normal query.

I hope that this can help someone on the way in the future.

Have a good day drupalers!!
See ya next time ;)


Activate two menu items I am using Drupal 6. How would I programmatically activate two or more menu items when I am on a certain node page?


Reset a page with multiple exposed filters I have a view page which is the main page on my website. It is kind of a search using exposed filters. As I have many exposed filters I installed the module MEFIBS which allows me to split the exposed form into multiple blocks that you can place in different areas. I have enabled Ajax as I use the UI slider from Better Exposed Filters module. I am developing on localhost (D7).

Now, I want to include a reset button to this main page. BEF module provides "include a reset button" but in my case every exposed filter gets an own reset button which is not user friendly (this is due to the MEFIBS module).

I tried this approach by adding a simple html button and the script location.reload(true), expecting that the page reloads not from the browsers's cache rather than from the server. The reloading works but the filter settings don't get reseted and I don't know why.

Does anybody have expierience with that? Any advise what causes this problem? Or maybe another approach?

Thanks,
Thomas

Are the query parameters showing in the URL?  Perhaps you could simply direct users to a clean version of the page without the parameters...


How to render a region in custom module twig template I have rendered regions in page.html.twig using {{ page.region_name }}. But it doesn't work for the custom modules template. How can I render a region in custom template?

I'd recommend to install the Twig Tweak module: It provides (amongst others) an operator for that:
{{ drupal_region('my_region_name') }}


create text box search for multi select field in view I have a custom content type in my drupal installation called Stores. While creating a new content for Stores I have a checkbox where I can select multiple zip codes.

I have created a view with my store listing and I want to add an option for the user to have a text box where s/he can enter a zip code and the store list gets filtered based on this. I have exposed the zip code field as a filter in the view. However since this is a multi-select field the filter shows up as a drop down to the user instead of a text box. I want a empty free-flow text box instead of a drop-down with all the zip codes in it.

I really appreciate any help or pointers regarding this..

You are looking for Finder module, it will display the autocomplete dropdown list to the users.

  Finder allows Drupal site administrators to create flexible faceted
  search forms to find entities such as nodes or users based on the
  values of fields and database attributes.


How to pull a record from Salesforce and immediately push the node ID back to Salesforce I'm using the Salesforce Suite module.

What I'm trying to accomplish:

When a record is created in Salesforce, that record is pulled into Drupal and the new node content ID is pushed back to the Salesforce record (for reference in Salesforce).

I have a mapping set up as such:

Triggers

Drupal create (push)
Drupal update (push)
Salesforce create (pull)
Salesforce update (pull)

Fields

Title - Salesforce to Drupal
Content ID - Drupal to Salesforce

With this setup, it pulls the record into Drupal but the Content ID doesn't get pushed back to Salesforce. It will, however push when I update (just save) the node but we don't expect these nodes to be saved anytime soon after it's pulled in.

I've tried a few different ways leveraging the events dispatched by the Salesforce module but it always leads me to a race condition or a circle.

Here's how I did it...

Since content is set to push (immediately) on update, I added a hook_entity_insert() that responded not to the content insert but the "salesforce_mapped_object" entity.

This ensures that not only was the node/user created but a mapping was created.

/**
 * Implements hook_entity_insert().
 */
function MYMODULE_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->bundle() == 'salesforce_mapped_object') {
    $entity_info = $entity->get('drupal_entity')->first()->getValue();
    $type = $entity_info['target_type'];
    $id = $entity_info['target_id'];
    switch ($type) {
      case 'node':
        $node = \Drupal\node\Entity\Node::load($id);
        $node->save();
        break;
      case 'user':
        $user = \Drupal\user\Entity\User::load($id);
        $user->save();
        break;
    }
  }
}

Thanks to @leymannx in the above comment for the guidance.


Is there a way to prevent a user from seeing a field on their user profile page? I'm looking to create a 'Last Updated' field in a user's profile. I was then going to create a rule that filled that field with the current date everytime the user's profile was edited. I want the information for admin purposes and don't want the user to see this info.

Is this possible? I'd prefer not to use a module.

EDIT: I would be fine with the field being on the user-edit page instead (but still hidden) if that's easier.

Is this possible?

Yes, but not out of the box with Drupal.

  I'd prefer not to use a module.

Not an option unfortunately, you need either a contrib or custom module to make this happen. You could theoretically do it in the theme, but that logic doesn't belong there.

Field Permissions is the go-to module for this.

Ah, just noticed your edit.

If you want the field to simply not be rendered, but you're happy for it to exist in the edit form, you can override the user-profile.tpl.php template in your theme, and just hide the field there:

<?php hide($user_profile['foo']); ?>

Or just hide it through the UI at admin/config/people/accounts/display if that works for your scenario.


Drupal single sign on local Is it possible to test signle sign from active directory on locally on your desktop?

Does it work with XAMPP / IIS?

Yes, you can test it against any Active Directory you can connect to.

But if you want a local copy of active directory, you can install a local copy of Active Directory Lightweight Directory Services (AD LDS) for Windows7 or equivalent.

Once installed, you will also need to configure to work with drupal's ldap module as normal. Then you will be able to work locally.

I have done this using XAMPP on a windows laptop.


Using a node reference in Drupal 7, is there a way to tell what the parent node is? I have a content type called Movie, it has a node reference to a content type called LeadActor. The LeadActor content type can have node references of its own back to several different Movies nodes.

When I have a page that displays the full content of a Movie, I've changed the node template to have a link to the LeadActor.

When a user uses the link to LeadActor from a Movie page, is there anyway for me to know what Movie the user came from when I'm on the LeadActor page?

I've thought about adding an extra argument to the LeadActor page link - the node id to the Movie, but I was wondering if there might be a cleaner way to handle this.

I'm using Drupal 7 and the node reference (references) module. I've also tried using the corresponding node references module - but so far I haven't been able to understand if this will work.

Thanks for your help.

Reading the text of your question, it looks like you don't necessarily need to know what the parent is but more where the visitor is coming from (and if it is a movie which one).

A possible solution, as you mentioned, would be to add some parameters to the URL.  A simpler option might be just a tiny bit 'o javascript.

Then use the referrer (previously browsed URL) and compare it against the list of movie URLs via JQuery.  If one matches, add a css class to style the link as an indicator.

Where

duck

duck

goose


chmod() and touch() operations not permitted After updating drupal8 for 8.7.0 and then to 8.7.1 versions i have next errors:

Warning: chmod(): Operation not permitted in Drupal\Component\PhpStorage\MTimeProtectedFastFileStorage->save() (line 76 of core/lib/Drupal/Component/PhpStorage/MTimeProtectedFastFileStorage.php).
Warning: touch(): Utime failed: Operation not permitted in Drupal\Component\PhpStorage\MTimeProtectedFastFileStorage->save() (line 100 of core/lib/Drupal/Component/PhpStorage/MTimeProtectedFastFileStorage.php).

This errors appears for all twig templates and only at first time page loaded. For second and other times no errors and template created in cache folder.
I set 777 permission for all files. Checked files owner. Was Reading many forums and nothing ...

I fixed this problem by updating owner of files, groups only not enough. Before i has owner as vagrant and group as www-data and now www-data for both.

But it's still strange for my. If i refresh page sometimes file generated and created anyway and warnings went one.


How to assign user with civicrm membership to specific role? I'm using D7 CiviCRM 4.4.6.

There are two roles in my site: authenticated user, member.

Those who registered in my site is authenticated user.
Only users who have active civicrm membership will assigned to both user and member role.

How can I configure the system so that when it run cron, those who have civicrm membership will be added "member" role?

Can't think of any better way to say this than the docs: http://wiki.civicrm.org/confluence/display/CRMDOC/CiviMember+Roles+Sync

makes it really simple and straightforward.

Good luck :)


Display block if content type has entity reference (tags) that contains specific term I want to display a block when a node contains a entity reference field when specific term is present.

I have tried numerous modules that did not work for me or perhaps I did not set them up right, term_condition token_conditions entity_field_condition (using the appropriate patch)

EDIT: it seems the term_condition works on a clean install after applying some pending patches on the issue queue.  So this probably is a problem with my installation.

The easiest solution is probably term_condition

Install/enable the module and then on the block layout of a certain block you will be presented with a term visibility setting where you can search for term that will be used as the visibility condition.

NOTE: Currently the module is incompatible with rules as rules has its numerous conditions on its own.  This issue has been reported here