Theming contact page form How to add in Drupal 8 a custom (suggestion) default contact page template ?

Thank you

Way 1: Use drupal template suggestion:

You can enable the template suggestions by following changes as mention in
https://www.drupal.org/docs/8/theming/twig/debugging-twig-templates

Once you have the suggestions enabled you can see, drupal suggests few template possiblities for any page, you can use any of the suggested template.

https://cl.ly/1f2T0x1a1F2n

Way2: Declare custom template suggestions

Or you can customd define template based on any logic by implmenting hook_theme_suggestions_page_alter().

Example:

https://sqndr.github.io/d8-theming-guide/theme-hooks-and-theme-hook-suggestions/theme-hook-suggestions.html


in private message: also match last names in auto-complete of To-field I am using the private message module and I do understand that one can use realname integration in the "To"-field to send a message. The auto complete feature helps finding the name.

Suppose I want to write to "John Smith". When I start typing "Jo.." it auto completes to "John Smith", but when I start typing "Smi.." auto completion fails. For my website it would be very nice to have that feature, since sometimes people don't know other peoples first names, but the last names.

How could I alter private message in the easiest way? Do you think other people would be interested in a more comprehensive auto completion?

There is an issue in the Privatemsg queue with an incomplete patch, privatemsg_realname: Permits to search inside realname field using "LIKE %...%".  You're welcome to help re-roll and test the patch.

The patch is for 6.x-2.x but it could fairly easily be re-written for 7.x-2.x.


Sharing files privately individual users I'm trying to create a Drupal 7 feature whereby an admin uploads multiple files that are only visible/downloadable by a specific user. These files would be visible on the user's profile page or (alternative) a document page where a user would only see the files available to them. Ideas?

Drupal private files can only be downloaded by someone who has access to the node the file is attached to.

So you can set up a content type that allow an unlimited number of files attached to a node. Then you set up an Access Control List to that node, where you make sure only the specific user has access to the node.  Let the admin create one node per user, and upload all files to be shared privatly with a specific user to the user's node.

To mange access control lists to nodes, you can use Flexi Access module.


Replacement for Drupal 6's $form_state['post'] in Drupal 7 I have the following code (part of a module):

function whm_ui_edit_account_form($form, &$form_state, $account) {

  $res = whm_account_info($account);
  $account_data = $res[0];
  $current_state = array('values' => array(
    'user' => $account_data['user'],
    'domain' => $account_data['domain'],
    'email' => $account_data['email'],
    'plan' => $account_data['plan'],
  ));
  $form_state['values'] = array_merge($current_state['values'], $form_state['post']);

  $form = _whm_ui_account_form($form_state);
  $form['account']['password'] = array(
    '#type' => 'fieldset',
    '#title' => t('Change Password'),
    '#description' => t('Enter values here <b>ONLY</b> if you want to change this account\'s password.'),
    '#collapsible' => TRUE,
    '#collapsed' => empty($form_state['values']['pwd1']) && empty($form_state['values']['pwd2']),
  );
  $form['account']['password']['pwd1'] = $form['account']['pwd1'];
  $form['account']['password']['pwd1']['#required'] = FALSE;
  $form['account']['password']['pwd2'] = $form['account']['pwd2'];
  $form['account']['password']['pwd2']['#required'] = FALSE;
  unset($form['account']['pwd1']);
  unset($form['account']['pwd2']);
  unset($form['account']['email']);
  unset($form['account']['plan']);

  $form['current_user'] = array(
    '#type' => 'hidden',
    '#default_value' => $current_state['values']['user'],
    '#required' => TRUE,
  );
  $form['current_domain'] = array(
    '#type' => 'hidden',
    '#default_value' => $current_state['values']['domain'],
    '#required' => TRUE,
  );
  return $form;
}

The $form_state['post'] no longer exists in D7 (I'm porting an old module) and perhaps I'm insanely tired or just out of my depth :-p but I can't find a suitable replacement. The function is essentially looking to merge existing information with the information given in the form before submitting (I think).

Any assistance or if anyone can point me to an alternative to the post value being used previously it would be appreciated.

$form_state['post'] in Drupal 6 contains the values of the $_POST global, and a quick look at Drupal 7 shows that when accessing a form via the post method, $form_state['input'] will contain that same array.  Side note: if it is accessed via the get method, this will contain $_GET.


How to create a webform submission table with values from the form itself? I find the current webform submission table completely inadequate when forms are submitted by anonymous users - you can't tell one from another other than by its submission date which not helpful in many instances. I would like to create a new webform submission table that can display specific fields from the submission itself to help identify who the submission is from. Ideally if I could accomplish this with views that would be great, but I am not adverse to creating a module if need be. Has anyone done this before and what would be the best approach?

Thanks.

Unfortunately, the current stable release of the Webform module doesn't support getting to any of the webform submission fields through Views.

However, if you look at this issue on Drupal.org: http://drupal.org/node/680386, you'll see that integration with views is a highly desired feature!  That's why there's so much activity on it!  The good news is that (look at this comment: http://drupal.org/node/680386#comment-6480250) there's actually a patch applied to version 7.x-4.0-alpha6 of the Webform module, so you can test this new integration functionality.

Let us know if it works well!


Token Replacement via Lazy_builder I've spent the best part of the last day or two trying to implement lazy_builder (as seen in this brilliant tutorial https://github.com/joachim-n/drupalcon-europe-2020-lazy-builders).
However, rather than with a block or page render. I'd like to implement the lazy_builder into hook_tokens() and make the $replacements value dynamic so that it uses the lazy_builder.
We have a value saved to session that we use as the value of a token (so it back be used across the site).
$session = \Drupal::request()->getSession();
$session->get('my_value');

I've tried setting $bubbleable_metadata with both addCacheContexts and addCacheableDependency
$bubbleable_metadata->addCacheContexts(['session']);

&
$session = \Drupal::request()->getSession();
$bubbleable_metadata->addCacheableDependency($session);

However both these options make the page UNCACHABLE.
I'd like to keep the page a cache HIT, but load in the token value via lazy_builder.
My question is, is there anyway to leverage lazy_builder, in the token replacement?
/**
 * Implements hook_tokens().
 */
function mymodule_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  $replacements = array();
  if ($type == 'my_token') {
    foreach ($tokens as $name => $original) {
      // Find the desired token by name
      switch ($name) {
        case 'my_token':
          $session = \Drupal::request()->getSession();
          //make the below use lazy_builder
          $replacements[$original] = $session->get('tracking');
          break;
      }
    }
  }
  // Return the replacements.
  return $replacements;
}

This answer might be helpful. In your case you could try to bubble up the attachment from the token itself:
$replacements[$original] = '<my-placeholder>';

$bubbleable_metadata->addAttachments([
  'placeholders' => [
    '<my-placeholder>' => [
      '#lazy_builder' => ['\Drupal\mytheme\MythemeLazyBuilders::replaceUid', []],
    ],
  ],
]);

You not really need the Drupal token system, you can attach placeholders almost everywhere in the rendering process, but for some cases this could be a convenient way to make a lazy builder available.


Change register button label when certain field is selected I use a custom module to change the text of my register form submit button:

<?php
function registration_button_override_form_alter(&$form, &$form_state, $form_id)
{
  //check to see if user is logged in so that this is only displayed to anon users that are registering
     global $user;
     if ($user->uid == 0) {
     if ($form_id == 'user_register_form') {

     // Change register button text.
     $form['actions']['submit']['#value'] = t('Jetzt registrieren');

     }
  }
}
?>

This works fine. Now, I try to adjust this code that the button label text changes if a certain field on the registration form has a certain value selected.

I added this line:

if (isset($row->field_data_field_registrierung_als[0]['value']) == 1)

This doesn't work. When thinking about it the form probably should load again in order to change the text, right? Does somebody know how this could be done?

EDIT:

My HTML:

<select id="edit-field-registrierung-als-und" name="field_registrierung_als[und]" class="form-select required">
<option value="_none">- Wert wählen -</option>
<option value="1">A</option>
<option value="2">B</option>
</select>

<input id="edit-submit--2" name="op" value="Neues Benutzerkonto erstellen" class="form-submit" type="submit">

My jQuery:

(function ($) {
$("#edit-field-registrierung-als").change(function() {
if $( this.value == "2")
$("#edit-submit--2").val("Registrieren");
}
}) (jQuery);

First of all you don't need to check if isset is equals 1.

Then I think you must use the form_state or do this with jQuery, like this:

if(document.getElementById('checkbox-is').checked) {
  $("#submit-id").text("Jetzt registrieren");
}

UPDATE: I have edited your code to look like this:

(function ($) {
  $("#edit-field-registrierung-als").change(function() {
    if ($(this).value == "2") {
      $("#edit-submit--2").val("Registrieren");
    }
  }
}) (jQuery);


Print out custom field and footer in newsletter 1. I have two fields in my newsletter content, the normal 'Body' and another called 'The List' (.field-field-thelist). I am trying to print this out in the newsletter but I cannot seem to get it working.

htmlmail-simplenews.tpl.php:

// this doesn't work
<?php print $node->field_field_list[0]['view'] ?>

I don't think I am doing this correctly, but I am basing it from this walkthrough.

2. For some reason when I call the newsletter to print $body (simplenews-newsletter-body.tpl.php), it also prints the $footer (simplenews-newsletter-footer.tpl.php) content ($footer doesn't actually print anything alone).

htmlmail-simplenews.tpl.php:

//Prints body AND footer for some reason, I want to separate these as two variables
<?php echo $body; ?>

The reason #2 confuses me is because there is very clearly 2 variables for each a body and footer in the simplnews.module file. Is there another way I can call these separately?

Note: I am not using Views for this newsletter

$node is available within the simplenews templates. htmlmail-simplenews.tpl.php is a generic template that is not simplenews specific.

$body in this context is the mail body, which has been created by combining the simplenews body and footer. Again, within Simplenews, those are separated, but are then simply concatenated together before passed to the htmlmail template.

To get to the node object in there, look at the example templated provided by HTML Mail, which uses $params['context']['node'] and $params['simplenews_source']->getNode() in Drupal 7.


Form API multiple select drop downs in a paragraph I am trying to recreate the following paragraph in a custom Drupal form.

How do you create multiple selects in a single paragraph?

You can try a combination of wrapping the whole form in a div, so:

form['#prefix]='
';
  $form['markup1'] = array(
    '#type' => 'markup',
    '#markup' => 'Hello this is a pulldown '
  );
  $form['pulldown1'] = array(
    '#type' => 'select',
    '#required' => TRUE,
    '#options' => array('option1', 'option2', 'option3'),
  );
  $form['markup2'] = array(
    '#type' => 'markup',
    '#markup' => ' and this is another pulldown '
  );
  $form['pulldown2'] = array(
    '#type' => 'select',
    '#required' => TRUE,
    '#options' => array('option4', 'option5', 'option6')
  );
form['#suffix]='
';

then use theme_form_element to remove the field wrapper divs that Drupal injects automatically around each field, see this post. Once these individual divs around each pulldown are removed then the pulldowns will render inline with the markup.


Content Type Custom Submit Handler I am very new to Drupal and is still learning. Please excuse if I have done my coding wrong.

Problem:
I wanted to add two buttons to my Content type.

1st button for Save Form - save the form and not publish it.
2nd button to Submit Form - save the form and submit it.

My Save Form button works right and it uses the default submit handler.

My Submit Form button is calling a custom submit handler and here is the code:

  function submit_Form(array $form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  $node = entity_create('node',$values);
  $node->save();

  drupal_set_message('Your form has been submitted. It will be reviewed by the team.');
  $redirect_path = "/user";
  $url = url::fromUserInput($redirect_path);
  $form_state->setRedirectUrl($url);

}

I am getting this error:

  Drupal\Core\Entity\EntityStorageException: Missing bundle for entity type node in Drupal\Core\Entity\ContentEntityStorageBase->doCreate() (line 83 of /var/www/clients/client1/web2/web/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php).

Thank you for looking at this.

When you create an entity node a value type for the content type is required. If your form doesn't provide one, you can add it to the values before creating the node:

  $values = $form_state->getValues();
  $values[] = ['type' => 'article'];
  $node = \Drupal\node\Entity\Node::create($values);


Missing "operation links" from all content list page I am currently missing the links that appear next to a piece of content on admin/content, the ones that say "edit / delete" etc.
I have all permissions enabled for the user I am logged in as, and I can still edit a piece of content if I go to view it first, just not on the list page.

Any ideas of what could be causing this?

Thanks

The solution was to re-install the latest version of Drupal.


Drupal Commons Completely private posts How can I give users the opportunity to make few posts completely private (i.e. visible only to themselves)? I'd like to do this with a make this post private - only for me checkbox.

Content Access

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.

Or you can do by allow permission to allow specific viewer/role


How to programmatically render a webform to display specific Elements I have tried this way but not able to hide "confirmation_id" element.

public function buildForm(array $form, FormStateInterface $form_state, $sid = NULL) {

$my_webform_machinename = 'request_form';
$my_form = \Drupal\webform\Entity\Webform::load($my_webform_machinename);
$my_form['elements']['flexbox_layout']['confirmation_id']['#access'] = FALSE;

return [
    'form' => [
    '#type' => 'webform',
    '#webform' => $my_form,
    '#sid' => $sid,
    ],

];

}

To hide custom field in webfrom you need to use the hook_form_FORM_ID_alter.

function CUSTOM_MODULE_form_webform_submission_request_form_add_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $elements = &Drupal\webform\Utility\WebformFormHelper::flattenElements($form['elements']);

  $elements['flexbox_layout']['confirmation_id']['#access'] = FALSE;
}

To get specific form elements you can use getSubmissionForm() method:

public function buildForm(array $form, FormStateInterface $form_state, $sid = NULL) {
  $my_webform_machinename = 'request_form';
  $my_form = \Drupal\webform\Entity\Webform::load($my_webform_machinename);

  $webform = $my_form->getSubmissionForm();

  $form['my_field'] = $webform['elements']['flexbox_layout']['confirmation_id'];

  return parent::buildForm($form, $form_state);
}


Views exposed date filters Can anyone tell me how I can use 2 Views exposed filters to filter nodes published between the two selected dates?

Use the Date Views module that comes shipped with Date. Add a filter to your view using the Date: Date option.

Now you can use the "In Between" option to either select between two specific dates, or relative dates (within the past 30 days of right now). Make sure to check "Expose this filter to views".


Export Content Type to a Form Like Structure? So, I'm just getting really lazy. I have to make new custom forms for users to input data. The form matches the Content Type exactly(except for somethings being generated server-side). Is there a way to just export a Content Type form into an form function?

If not it seems like something I might have fun developing.

Thanks,
Nate

I would recommend looking into Webform Template. All you have to do is make the Webform the one time, then you can copy the configurations for new forms.


How to style my custom Fivestar field? After having solved How to calculate the average Fivestar rating correctly?, I have a computed field Average score that displays the average score of a node. I sometimes want to display this field in a View as a rating (e.g. 4.2/5) and add some more markup to it. For the moment, I have different templates of the form views-view-field--MY-VIEW--field-average-score.tpl.php with the same code:

<?php $rating = round(($output/100) * 5, 1); ?>

  <?php print $rating . '/5'; ?>

Having all these duplicate templates seems silly to me. Is there a way to only have one and somehow point out which Average score fields should be styled accordingly? Simply using views-view-field--field-average-score.tpl.php is not what I want, since I don't always want to style Average score like this.

Then you can do it like this:

Use view-field--field-average-score.tpl.php which will affect all views that have this field, but we can add an if statement to target the views you only want the special markup.

Ex: In here we check if it has view_name with block_1 OR view_name_2 with block_1

<?php if (($view->name == 'view_name' && $view->current_display == 'block_1') || ($view->name == 'view_name_2' && $view->current_display == 'block_1'): ?>
<?php $rating = round(($output/100) * 5, 1); ?>

  <?php print $rating . '/5'; ?>

<?php else: ?>
<?php print $output; ?>
<?php endif; ?>

In case you are wondering, current_display is the machine name

The $view->current_display check is optional. This is so it only affects a certain Display of block/page that is inside your view.

So for line 1, you could use this instead:

<?php if ($view->name == 'view_name' || $view->name == 'view_name_2'): ?>

If you want to affect all blocks/pages that are inside these 2 views.


How do I display an array of entities from a controller? I am new on Drupal 8 , so i have created a service class which return a list of data, 'articles' (node entities), and I call this  service class inside a controller, but no data showing up :
My getArticles() method inside my service:
  public function getArticles(){
    $storage = \Drupal::service('entity_type.manager')->getStorage('node');
    $my_entity_ids = $storage->getQuery()
      ->condition('type', 'article')
      ->condition('status', 1)
      ->execute();
    $my_entities = $storage->loadMultiple($my_entity_ids);
    return $my_entities;
  }

My controller:
public function myPage() {
    $data = \Drupal::service('mymodule.service');
    $dataService = $data->getArticles();
    return $dataService;
  }

My result is a blank white page when I view the path routed to my controller, but I see the following message in my error log:

Recoverable fatal error : Object of class Drupal\node\Entity\Node could not be converted to string dans Drupal\Component\Utility\Xss::filter()'' -----"Warning : strlen() expects parameter 1 to be string, array given dans Drupal\Component\Utility\Unicode::validateUtf8()

Can anyone tell me please why i can't get the articles?

Controllers need to return a render array. Let's imagine you process your articles for render in a new method renderMyPage() which you call from myPage() and pass your array of article objects.
If you're displaying multiple fields from the articles, you're best off building and configuring a view mode and then getting the view mode render array as described in this answer.
function renderMyPage($articleObjects) {
  $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');

  $articles = [];
  foreach ($articleObjects as $article) {
    $articles[] = $view_builder->view($article, 'my_view_mode_machine_name');
  }

  return $articles;
}

If you want to render a single field from your article, you can get the render array for a field as described in this answer.
function renderMyPage($articleObjects) {
  $articles = [];
  foreach ($articleObjects as $article) {
    // You can pass a view_mode machine name or
    // an array of field configurations to view().
    $articles[] = $article->title->view();
  }

  return $articles;
}

Alternatively you can build your own render array, say to render the title as an h2.
function renderMyPage($articleObjects) {
  $articles = [];
  foreach ($articleObjects as $article) {
    $articles[] = [
      '#type' => 'html_tag',
      '#html_tag' => 'h2',
      '#value' => $article->title->value,
      // The other methods add cache tags automatically, but we need to add
      // cache tags manually here since we're building the array from scratch.
      '#cache' => [
        'tags' => $article->getCacheTags(),
      ],
    ];
  }

  return $articles;
}

Each of these examples returns an $articles array of renderable contents suitable as a return value from your myPage() method.


Is there a module/solution for allowing users to block each other on an SNS site? Is there a module or solution that allows users to block each other on a social networking site?  For example, if a user blocks another they will no longer see that user's profile or any content posted by that user.

I imagine one could do something like this with the flag module, but it seems like it might get extraordinarily complicated...

Take a look at the Ignore User module.  From the project page:

  This module allows a user to "ignore" content from other users that
  they do not wish to view. Node and comment content from an ignored
  user is hidden from view on a page. A message is displayed above the
  hidden block of content with a link to the user's "ignore list" and a
  link to toggle display of the ignored user's block of content in that
  node or comment.

Not sure if it will handle blocking a profile view or not, but it should block content.


Getting a custom block image field URL in the block Twig template I have a custom block containing a text field and an image field. I would like to render the block so that the image's URL can be defined as a data attribute of the block's wrapper div so that it can be used by a javascript function to create a parallax background effect behind the text field.

If I make a template file block.parallax.html.twig, I am able to render the image HTML.

{{ content.field_parallax_image.0 }}

However If I try to get the actual image URL, nothing is returned

{{ content.field_parallax_image.0['#url'] }}

If I dump the #item keys

{{ dump(content.field_parallax_image.0['#item']|keys) }}

I am able to get target_id, alt, title, width and height values, but I can't find the URL defined anywhere.

I have also tried to see if I could find anything useful in the block preprocess function but the field_parallax_image #url field in the variables is also empty

function mytheme_preprocess_block(&$variables) {
    if( isset($variables['content']['body']['#bundle']) && $variables['content']['body']['#bundle'] == 'parallax'){
        $variables['img_url'] = $variables['elements']['content']['field_parallax_image'][0]['#url'];
    }
}

Is there a way I can get this URL?

#url at this stage is not processed yet. This happens later in the image templates.

To get the url in the block template you can access the uri field in the image file entity instead:

{{ file_url(content.field_parallax_image.0['#item'].entity.uri.value) }}

BTW you didn't find this property in the dump output, because it is a computed value to make it easier to handle entity references.


Contextual Filter not working wiht URL aliases I have this issue with contextual filter. I have set the filter so it would get an ID of an article and based on that ID, it would show the name of the author.
The problem is, it doesnt work with URL aliases.
For example, when I put the ID of the node like example.com/node/22, it finds the author. But when I try to put the URL alias like example.com/clanky/something-something-something, it doesnt show anything.
Any idea how can I solve this?
Thank you for any reply.

Use Content ID from URL instead of Raw value from URL


How might I display a field twice in a node using different field formatters? Question:

How can I show the field_showcase_headshot field both as a picture on screen and as a download link?

Set up:

From the load tab of Devel, I have a few fields on this node.

The field here is Showcase Headshot. It is currently set to display on the screen as follows

But we'd like to include a download link to the original image in the fashion shown here.

That is, we'd like to append something like the following to the text on the page.

Showcase Download:
headshot

There are 2 options available for this to do.

By linking the image to its image path from the site. This can be achieve using a module https://www.drupal.org/project/image_link_formatter.
By using download module and custom field theme formatter.
In this you need to enable the download file module https://www.drupal.org/project/download_file.
And than create customize the field view using the field template.


Add CSS-class to current node in module logic In a custom module, I add some logic to the node rendering. Based on this, I would also like to add some appropriate CSS-classes to the current node.
The below code expresses  what I would like to do, but don't know how to do.

$node->classes[] = $class;

Because I already have the appropriate logic in my module, it seems to me like the adding of classes should be handled in the same place. I could do this in a template instead, but that would require me to duplicate all the logic.

Would hook_preprocess_node help you for this?

Example:

function mymodule_preprocess_node(&$variables) {
  $variables['classes_array'][] = 'blah';
}

The variables array contains all information about the ndoe as well, so you can run logic to dictate which classes should be added to which node types/IDs etc.

If you run dpm (with the Devel module enabled) then you can print everything in that array that you can alter/add to.

I agree that $node->classes would be a really useful addition though.


Identifying tags with no content tagged For my job site, jobs are tagged from terms of Tags vocabulary where new ones can be added. Sooner jobs expire and new arrive.

That has resulted in bloated taxonomy vocabulary with 2400 terms (or 2400 pages). I guess many remain empty for long periods.

Many tag pages simply show no classified content available which has attracted Google's Panda penalty.

What I want is removing those tags not used for any node, and automatically deleted those that have not been used in the past 3 months or so get.

Is there any simple way for doing this?

I have a similar script that I use, but I run it as a drush scr.  You can adapt it for your needs, perhaps to do this in a hook_cron():

$tags = taxonomy_vocabulary_machine_name_load('tags');

$tids = db_query('
  SELECT DISTINCT t.tid
  FROM {taxonomy_term_data} t
  LEFT JOIN {taxonomy_index} i ON i.tid = t.tid
  WHERE t.vid = :vid
    AND i.tid IS NULL
', array(':vid' => $tags->vid))->fetchCol();

if (!empty($tids)) {
  foreach ($tids as $tid) {
    taxonomy_term_delete($tid);
  }

  watchdog('foo', 'deleted @count orphaned tags', array(
    '@count' => count($tids),
  ), WATCHDOG_NOTICE);
}

This exact version is untested and a hand-edit from a very specific use-case I have.  Take backups and use at your own risk!

The only problem is that {taxonomy_term_data} doesn't have a created column, so this will immediately delete orphaned terms.  It also doesn't take into term hierarchy, or tags being on entities other than nodes.


Recover a deleted field I have a content-type with 4 fields each of which is a term reference. There are 100 nodes each assigned 4 term references. I have accidentally deleted one of these fields from the admin>structure>content-types>mycontent-type...resulting in all 100 nodes losing the term reference this lost field contained.

After installing the Database Admin module I could see that the database for my deleted field was still present, it had been renamed to something like "field_deleted_field_74"

Using mysql I have been able to rename this database back to "field_data_field_originalname" - i.e. using the original machine name for the deleted field
Furthermore I have been able to switch the value of the deleted column inside this database from '1' to '0'.

I have done the above with the other 'ghost' database that I found that was called something like "field_revision_field_74" ...

My problem now is that my renamed field is not appearing as a pre-existing field on my content-type manage fields display nor at admin>reports>fields list.
When I run 'drush field-info fields' it is also missing.

How to I bring it back? I am assuming that there is another database that refers to it that I need to edit.

Thanks!

A good question, and surprising there's not an easier way to rollback a deleted field, given the data is still available.

Assuming you have:

Renamed the field_deleted_* tables back to field_data_field_myfield and field_revision_field_myfield (latter also important)
Updated the 'deleted' flag from 1 to 0 in the relevant data tables.

There is also

field_config

  The main field configuration

field_config_instance

  The field configuration on a particular entity bundle.

You may need to adjust the 'deleted' flag there also:

e.g:

UPDATE field_config SET deleted = 0 where field_name = 'field_my_deleted_field';
UPDATE field_config_instance SET deleted = 0 where field_name = 'field_my_deleted_field';
TRUNCATE TABLE cache_field;


Custom webform component for displaying a list of nodes I would like to have a content-type with Add to cart button that would allow a user to add current node to the cart. Then there would be a webform that would list all the items (nodes) that the user added to the cart.

Can anyone give me directions on how to achieve this? I think it has something to do with creating custom webform component.

To answer my own question. My solution was to add a 'Add to Cart' button on the node which stores that node to the session. I created a new webform component based on textarea that is readonly and lists all nodes that the user added.


Function to determine whether my Cart is empty? I want to set an access callback on a menu item (primary links) for the shopping cart so that it only displays when there is something in the cart.  However, I can't find an obvious function to to this, and I don't know where to start with my own code.

Any suggestion is appreciated.

Using the same technique as commerce_cart_block_view (thanks to Ryan Szrama for the assist!), you'll need to:

Get the order using commerce_cart_order_load, then check to see if there are no line items.
Apply the entity metadata wrapper to retrieve further wrappers for the entity properties
Count line items in the cart, filtering for products only

For the access callback itself, take a look at Do you have an example of hook_menu() access callback? for several examples and links to documentation.

Therefore, the callback should be something like:

function MODULE_access_check() {
  global $user;
  if ($order = commerce_cart_order_load($user->uid)) {
    $wrapper = entity_metadata_wrapper('commerce_order', $order);
    return commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types()) > 0;
  }
  return FALSE;
}


Why are my custom error pages returning HTTP status 200 headers? Drupal 6 on IIS 7.
We have webconfig.xml setup to "Execute" the error pages when an error occurs, but the problem is that this now send status code 200 to the client (it is successfully serving the custom error content), which now means that unpublished URLs get indexed by search engines and other crawlers.

I notice that a default Drupal install send the correct HTTP status codes (404, 500, 403, etc), so it must be something in our configuration.

The option to use the default Drupal error pages is likely not on the table with this client.

I believe you still have to return the proper status code from your custom error page. For instance, for a custom 404 page, you need:

<?php header("HTTP/1.0 404 Not Found"); ?>


Language switcher not visible when logged out (Drupal 7) I'm creating a multilingual website in Drupal 7. I'm using the internationalization and entity translation modules and language detection is set to URL. I use the language switcher (content) from the entity translation module to switch between languages.

Everything works fine as long as I'm logged in as administrator. When I log out, or when I'm just an authenticated user, I can't see the language switcher anymore although the html code is generated.
Does anyone what could be the reason for this?

Thank you.

You have to check the permissions on internationalization module; probably you have selected "administrator only".

By the way, read this: Drupal multilingual.


Migrating taxonomy terms when source is a separate table? I'm writing a migrator for a now-unsupported WordPress plugin that used a single "attachments" table to store data ranging from thumbnails to musical genres. It looks like this:

mysql> describe attachment;
+----------------------+--------------+------+-----+---------+----------------+
| Field                | Type         | Null | Key | Default | Extra          |
+----------------------+--------------+------+-----+---------+----------------+
| attachment_id        | mediumint(7) | NO   | PRI | NULL    | auto_increment |
| attachment_target    | varchar(32)  | YES  |     | NULL    |                |
| attachment_target_id | mediumint(7) | YES  |     | 0       |                |
| attachment_type      | varchar(32)  | YES  |     | NULL    |                |
| attachment_info      | text         | YES  |     | NULL    |                |
+----------------------+--------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)

attachment_id is just an ID, attachment_target_id will correspond to a NID from the "artist" content type I'm trying to import this into, attachment_type is either "genre" or "thumbnail" and attachment_info is the actual data contained in the row ("Disco", as an example for a genre.).

To import all the genres into a taxonomy field, it seems I would extend the class that imports all the artists from the other table, then using $this->systemOfRecord = Migration::DESTINATION, import each row into the existing nodes. Alas, given each row would be a new migration item, it seems this would overwrite the values.

I've also thought about adding a sub-query to my initial artist migration that returns a comma-separated list of genres; alas, I'm not sure how I'd do that with Drupal database abstraction layer.

Any help? Thanks!

The piece I was missing was GROUP_CONCAT for the attachment table. My query now looks like this:

$query = Database::getConnection('default', 'wp')
       ->select('artists', 'a');
$query->join('attachment', 'at', 'a.artist_id = at.attachment_target_id');
$query->fields('a',
          array(
              'artist_id',
              'artist_name',
              'artist_publish_date',
              'artist_bio',
              'artist_record_company',
              'artist_social_links',
          )
        );
//Pull in genres.
$query->addExpression('GROUP_CONCAT(DISTINCT at.attachment_info)', 'genres');
$query->condition('at.attachment_target', 'artist');
$query->condition('at.attachment_type', 'genre');
$query->groupBy('a.artist_id');


How do I get fields attached to a user to display to anonymous viewers? I've searched around and either I don't find any questions that address my issue per se, or the solutions offered don't pertain/affect my problem. So here goes:

A D7 site, current core, etc.

I have fields attached to user entities. I don't have any permissions applied to limit access to the fields. All users (including anon) have access to user pages (user/username).

However, attached fields do not appear through views for anonymous users. They do appear for logged in users, and anonymous users can see the Groups Audience (I use organic groups on the site), but no other affiliated data shows (full name, website, twitter, etc).

If my view is a list of fields, the fields do appear, but without content (the labels print if I turn them on, text I have set to display as no results behavior shows, etc). If my view returns a rendered entity all that prints for anonymous users is the user picture and Groups Audience.

I'm at a loss here. Initially I thought it was a views issues; now I'm not so sure. I've checked my permissions multiple times and I can't see what's blocking it. Anonymous users can access user pages. I don't have any field-level restrictions (and enabled the Field Permissions module just to make sure). I don't know what else it could be.

Any help is super appreciated.

After poking around on this for a while I discovered that it is definitely an organic groups permission issue. For the record, I have the 7.x-1.5 version of OG installed.

In OG global permissions (admin/config/group/permissions) the fields attached to the user (and nothing else) are all listed under Organic Groups Field Access along with fields attached to groups and fields attached to group content types. When I give access to non-members the fields appear for anonymous.

I suppose this functionality is designed so you can limit user access to people who are connected through a group. This isn't entirely senseless, but can be frustrating if you don't anticipate that control over some objects will be trumped by OG permissions.


Node specific template with custom html header From time to time I have pages within the Drupal architecture that I don't want to use the standard page.tpl.php.tpl and html.tpl.php.  I want to create a template for specific nodes that uses a unique one for each.  It cannot have any drupal code in it.  Is this possible?

This applies to Drupal 7...

page.tpl.php

Make a copy of page.tpl.php from your active theme's directory e.g

/sites/all/themes/your_theme/page.tpl.php

If the theme does not have page.tpl.php file then make a copy of Drupal's default version at

/modules/system/page.tpl.php

Rename your copied file in your theme folder with one of the following naming convention. Use this format for a node content type (example uses a custom content type called 'news'):

page--node--news.tpl.php

Or for a specific node use the ID number (example uses node ID of 12):

page--node--12.tpl.php

html.tpl.php

The same applies for html.tpl.php For a specific content type use:

html--node--news.tpl.php

For a specific node

html--node--12.tpl.php

These will take precedence over the generic html.tpl.php or page.tpl.php if the ID or content type matches.


When checking out, redirected to front page and not payment page I am creating a new order, and line item (without a product, since this is just a fee we're collecting from the customer).  The order is created, with line item, but when I go to /checkout/[order_id], I'm just redirected to the front page.

My code for the order creation is:

function mymod_form_submit($form, &$form_state) {
        global $user;
        $order = commerce_order_new($user->uid, 'checkout_checkout');
        commerce_order_save($order);
ddl($order);

        $line_item = commerce_line_item_new('app_fee_type', $order->order_id);
        $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);

        $line_item_wrapper->line_item_label = t('Application Fee');
        $line_item_wrapper->quantity = 1;
        $line_item_wrapper->commerce_unit_price->amount = 3500;
        $line_item_wrapper->commerce_unit_price->currency_code = 'USD';
        $line_item_wrapper->commerce_total->amount = 0;
        $line_item_wrapper->commerce_unit_price->data = commerce_price_component_add(
                $line_item_wrapper->commerce_unit_price->value(),
                'base_price',
                $line_item_wrapper->commerce_unit_price->value(),
                TRUE,
                FALSE
        );
        commerce_line_item_save($line_item);

ddl($line_item);

        $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
        $order_wrapper->commerce_line_items[] = $line_item;
        commerce_order_save($order);
ddl($order);
        commerce_order_status_update($order, 'checkout_payment');
        drupal_goto('checkout/' . $order->order_id);
}

The customer should just be taken to the checkout screen.  What am I missing?

It looks like the order ID isn't being saved for the session.  Add this:

$_SESSION['commerce_cart_orders'][] = $order->order_id;

Just make sure you do this before you save the final version of your order.


How do I postpone an already postponed deletion I made a site in which users can publish content and also postpone the deletion time. Now I want the users to be able to postpone a deletion that have been already been postponed. So I want to consider the remaining time do so.

How can reach this goal?

First an educated (wild) guess ... Since Drupal, out-of-the-box, does not come with some "postpone" facility, I'm going to assume that you implemented that by using the Rules Scheduler to schedule the execution of a Rules Component, which does nothing but delete some content (node).

Have a look at my answer to the question "How can I set a reminder for a specific user to be triggered on a specific date?". Obviously, that is not the same question as yours here. But the "specific date" there appears to correspond to your "postponed date".

With that, you could just trigger a rule each time that the content is edited, and then verify the relevant data of your content to decide if you need to do either of these:

no more need to postpone the deletion of content "later on", so just DELETE the scheduled execution of the Rule to delete content.
(re-)schedule the execution of the Rule to delete content.

PS: from revision 1 of your question, I understand it is about D7 ...


How to add comment form to a view of nodes in Drupal 9? I'm using views to display the fields of nodes. I prefer to use fields because it allows me to use relationships (bring in author profile picture etc.). Adding the Content: Comments field shows the list of comments as well as the comment form for each node. However, when hiding and rewriting the result/and or using the replacement pattern for Content: Comments, the comment form disappears and only the comment list remains.
What methods can I use to display the comment form for each node in a list of nodes view when using fields?

However, when hiding and rewriting the result/and or using the
replacement pattern for Content: Comments, the comment form disappears
and only the comment list remains.

It's due to a Views UI bug as I was able to replicate the issue on a fresh install.
A workaround you can do is to do the re-writing via template file rather than via UI.
In your theme's /templates folder add:
views-view-fields--view-name--machine-name.html.twig
and print the view fields there
{{ fields.title.content }} {# title field #}

{{ fields.comment.content }} {# comment field #}

{{ fields.field_name.content }} {# some other field #}

Flush all caches so template gets pickedup.


Is there any option to import my excel to Views? I am new for drupal 7.

I got exported excel from view using Views Data Export Module.

My question is,

Is there is any option to import my excel sheet to view.

Kindly help me to achieve this...

You can do by using PHP Excel module. This module is for handling the export or import of Excel files.


How do you create a block that contains fields from the User Profile? I tried using the method described in one of the answers here: How to put user profile in a block

I created a block and used the following PHP code as a test;
<?php render(user_view($account)); ?>

It didnt work. So the question remains, How can you create a block and call user profile fields into it using PHP?

render() only returns the string, it doesn't print it to the output. This code should work:

<?php print render(user_view($account)); ?>

Assuming of course that you have loaded the $account object. If not you probably want to use something like:

global $user;
$account = user_load($user->uid);

As an aside, using the PHP filter is considered bad practice (it uses eval() which is an inherent security risk).

The best way to get what you're looking for is to write a small custom module that implements hook_block_info() and hook_block_view():

function MYMODULE_block_info() {
  return array(
    'user_profile' => array(
      'info' => 'User Profile Block',
      'cache' => DRUPAL_NO_CACHE
    )
  );
}

function MYMODULE_block_view($delta = '') {
  $block = array();

  if ($delta == 'user_profile') {
    global $user;
    $account = user_load($user->uid);
    $block['subject'] = 'User Profile';
    $block['content'] = user_view($account);
  }

  return $block;
}

If your new to writing modules the best resource I know of is the Module developer's guide, and in particular the Creating Drupal 7.x modules sub-section; it will walk you through all of the steps necessary to get your module up and running.

UPDATE

Just to address your second comment...

I think the easiest way to get only certain fields to display would be to install the Entity View Modes module. Then you can create a custom view mode for the user entity (called block_profile or something), and in the "Manage Fields" admin page for users assign only the fields you want to be displayed to that new view mode.

Then you can pass the new view mode to the user_view() function:

$block['content'] = user_view($account, 'block_profile');

And voila, your block will contain only the fields that you've added to the new view mode through the admin UI.

If Entity View Modes is causing you issues you can just uninstall it, and add the new view mode yourself using hook_entity_info_alter() (again in your new custom module):

function MYMODULE_entity_info_alter(&$info) {
  $info['user']['view modes']['profile_block'] = array(
    'label' => t('Profile Block'),
    'custom settings' => TRUE
  );
}


Core Testing vs SimpleTest I have a query concerning the core Testing module and the SimpleTest module.

When I install a new site, the Testing module is available but disabled. When enabled, a list of tests are available for a whole range of resources such as nodes, users etc.

When I install SimpleTest these tests disappear along with the core Testing module. They are replaced by five example SimpleTests.

Could someone explain the differences between these two modules?

Also, is it possible to use these initial tests within SimpleTest?

The simpletest module has been integrated into Drupal 7 core. Since then the contrib simpletest module has not seen much development. See also this issue.

If you want to start writing tests for your own modules, enable the core simpletest module (called Testing in the UI) and do not install the contrib module. Also check out the examples module, it should give you an idea on how to add tests for custom code.


can i add multiple value in field ? (please see an image) I need to do the stock management website with 2 Content type Supplier and Product.
First I add contents in Supplier content type. Then I add node reference field in Product content type and call it supplier and make it multiple value. it's looks good, i can select suppliers and save it. but in my concept i need to check which supplier sale this product and how price. so i need to add suppliers and price in the same form like my image,

my concept image, create by photoshop, can i do like this ?

the propose of this form, user can check how price of each supplier for this product and they can choose the lowest price for purchase in the next process.

Guys, did you have the idea that i can do like this ?

Thanks for share :D

For simmilar needs, i am using this module, for me it is very good! There are some other alternatives too, but for me this module is proven as stable:

http://drupal.org/project/double_field


How to change programmatically the link of a field in a View I have a View, with a hidden field with a URL, and an image field which has the following property:

Output this field as a link and linked to the URL field: [field_url_slider] and _blank as Target.

I want to change dynamically the behaviour, so when the image is a given one, to rewrite programatically the URL and also the Target.

In hoo_views_pre_render don't see how to do it, because the complete link, i.e. a href="", etc. is not any data of view->result and I don't know if this can be achieved via $view->display (I only want to change a result). So, in a few words, I want to change the HTML output of the Views display for just a result.

I have finally solved using hook_views_pre_render and setting the display of one of the fields to "do not display", and adding as pure HTML around the field, replacing the content with the other field. In other words, by writing at low level the link of the field.

Surely there must be another way of doing this.


hook_menu_alter() doesn't work Possible Duplicate:
  hook_menu_alter() is not working

I have implemented a hook function hook_menu_alter in a module I have created. I have printed something inside that function call but nothing shows up. Though the function hook_init() is executed from the same module. The output of the hook_init shows up in the page but not from the hook_menu_alter even after clearing the cache. Do somebody has any idea regarding this issue?

function mymodule_init(){
print "here";
}

function mymodule_menu_alter(&$items) {
print "I am here";
return $items;
}

hook_menu and hook_menu_alter are only called when rebuilding the menu table, not on each table load.  So you won't see your print statements.

As a side note, I would use drupal_set_message() rather than print when debugging.


Grant/restrict access according to node's author & moderation state I'm trying to bypass some of the permissions set by Workbench Moderation, only under specific circumstances. For a specific content type, I need the users of a specific Role to be able to:
- View all Published nodes of that content type (this works fine as it is quite general)
- View Unpublished nodes only if the nodes 1. are related to them (through Entity Reference field) or 2. they have created themselves.
- Edit nodes only if they are related to them (through Entity Reference field) or nodes they have created themselves. This should be allowed only in a specific State.

I've tried implementing hook_node_access_records() & hook_node_grants() hooks in my module but this doesn't seem to work. In the following example, the conditionals are different than what's mentioned above but the logic is the same:

function mymodule_node_access_records($node){
    $grants = array();
    if ($node->nid == 1234 && $node->uid == 99) { //(example conditions)
        $grants[] = array(
            'realm' => 'mymodule',
            'gid' => 123,
            'grant_view' => 1,
            'grant_update' => 0,
            'grant_delete' => 0,
            'priority' => 0,
        );
    }
    return $grants;
}

function mymodule_node_grants($account, $op){
    $grants = array();
    if (($op == 'view' || $op == 'update') && $account->uid == 99) { //(example conditions)
        $grants['mymodule'] = array(
            123,
        );
    }
    return $grants;
}

This does add a line in node_access table where only grant_view has a value of 1. It should just allow related users to view the specific (unpublished) node but not edit it.

UPDATE: I installed Devel node access and here are my findings for the test case above (node 1234 is Unpublished, user 99 is author):

Test User can View the node - OK
Test User can Edit the unpublished node (non-Published draft) - NOT OK
Test User cannot Delete the node - OK
Test User can Moderate the Unpublished node (allowed transitions set by WM config.) - OK

Here is what Devel actually displays on that node's view page:

Create: YES: by node (permissions) - OK
View: YES: view own unpublished content - OK
Update: YES: by node (permissions) - This should be overridden by my access module
Delete: NO: no reason - OK

How can I override this edit permission with my module? I'd eventually like to expand the functionality of this module to cover other cases as well.

A helper module that I use for managing node access is ACL .

  The ACL module, short for Access Control Lists, is an API for other modules to create lists of users and give them access to nodes. It has no UI of its own and will not do anything by itself

What I suggest is that instead of handling the grants yourself, you outsource it to ACL. The module has a simple (YMMV) to use high-level API that let you grant individual users access (and revoke it).

The documentation is a little sparse, but on the ACL project page existing client projects are listed.  I learnt how to use it by reading the source code of those.

Alternatively, you can read the source code of ACL to see how to do low-level manipulation of permissions.

If you end up writing your own module, the introduction to this page gives a good introduction to how Drupal's node access system works.  In particular, you should be aware of:

  Node access modules always GRANT access and never restrict it. (It is a whitelisting rather than a blacklisting system.)

I understand you already use DNA (Devel Node Access), but if somebody else stumble across this: DNA (part of the Devel project) is absolutely essential if you are going to debug node access.


Print edit/create/delete node link with jQuery Been searching for a while so I came here to ask...

How can I print edit/create/delete node links with jQuery? I just want to show the links when I hover over the < li >'s. I already have the hover code... So I really just need to code to get the edit/create/delete node links.

Edit: So, not the current URL but fetch the ID/NID's. These are in a list. I want to show the edit/delete buttons of that specific article when hovering over an item.

Thanks in advance!

If I understand correctly you need the urls to the node creation/edit/deletion.
So, here it goes.

The link to add a node is:

node/add/your_content_type_name

to delete a node

node/node_id/delete

to edit a node

node/node_id/edit

You can fetch the node ID with jQuery from the url, But your kinda stuck with the content type name.


Jquery into Drupal 7 I'm trying to get this: http://jsfiddle.net/SgHJ5/
to work in Drupal 7.

For some reason, when I paste it into my front--page.tpl (footer) it doesnt work.

I've also tried including a JS file into my template.php.

jQuery in D7 is in noConflict mode. You need to use jQuery instead of $, or a closure.
See http://drupal.org/node/171213


How to create a block view that displays content one year ago from from the post date of the current node We have a surf report running on D6. One of the features that we'd like to add is a block on the node page of a surf report content-type that shows the surf report from one year ago.

I know how to create a filter that sets the date to one year from the current date/time, but I want to make this block display the report from one year from the post date of the current node (as opposed to current date/time).

Any ideas on this? I've racked my brain and can't think of any solutions.

Any help is appreciated!

Can Views Data Rnage be a useful module? There is another choice is Views Date Range Filter D6. You will have investigate both solution if they work for you.


Add conditional javascript from CDN (external library) I know it has been discussed here several times, but:

Is there a way to include conditional JS from CDN in the head section?

My goal is to somehow use drupal_add_js, external. That will stick in the head area, even if I move scripts to the bottom of the page. It is about html5shiv and respond.js

The classic way to add js was discussed here and here. So what I've managed so far is to bring

<?php
function THEMENAME_preprocess_html(&$variables) {
    drupal_add_js('https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.js', 'external');
    drupal_add_js('https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js', 'external');
}

The problem is conditional. One way to add conditional elements, with drupal_add_js. I know how to load local conditional js, using a variable I'm creaing in template.php, like so:

<?php
$html5shiv = array(
    '#tag' => 'script',
    '#attributes' => array(
        'src' => file_create_url(drupal_get_path('theme', 'THEMENAME') . '/js/html5shiv.js'),
    ),
    '#prefix' => '<!--[if lte IE 9]>',
    '#suffix' => '</script><![endif]-->'
);
drupal_add_html_head($html5shiv, 'html5shiv');

But this will only put the conditional JS even before the meta title element and I need this to be loaded at the end of my  section, JUST BEFORE my scripts loaded from theme.info (scripts[] = js/main.js). And of course, this will load local JS, not external.

Any ideas?

The Boilerplate theme does it for CSS by adding to template.php in the theme:

function boilerplate_preprocess_html(&$vars) {
  if (!module_exists('conditional_styles')) {
    boilerplate_add_conditional_styles();
  }
}

function boilerplate_add_conditional_styles() {
  // Make a list of base themes and the current theme.
  $themes = $GLOBALS['base_theme_info'];
  $themes[] = $GLOBALS['theme_info'];
  foreach (array_keys($themes) as $key) {
    $theme_path = dirname($themes[$key]->filename) . '/';
    if (isset($themes[$key]->info['stylesheets-conditional'])) {
      foreach (array_keys($themes[$key]->info['stylesheets-conditional']) as $condition) {
        foreach (array_keys($themes[$key]->info['stylesheets-conditional'][$condition]) as $media) {
          foreach ($themes[$key]->info['stylesheets-conditional'][$condition][$media] as $stylesheet) {
            // Add each conditional stylesheet.
            drupal_add_css(
              $theme_path . $stylesheet,
              array(
                'group' => CSS_THEME,
                'browsers' => array(
                  'IE' => $condition,
                  '!IE' => FALSE,
                ),
                'every_page' => TRUE,
              )
            );
          }
        }
      }
    }
  }
}

Then added to the .info file:

stylesheets-conditional[lte IE 8][all][]  = css/compiled/ie8.css
stylesheets-conditional[lte IE 7][all][]  = css/compiled/ie7.css
stylesheets-conditional[lte IE 6][all][]  = css/compiled/ie6.css

I'm sure this could be easily adjusted for JavaScript instead


Translate untranslated strings I downloaded and enabled translations for my Drupal core and modules using these Drush commands:

drush dl l10n_update && drush en -y $_
drush language-add lt && drush language-enable $_
drush l10n-update-refresh
drush l10n-update

I got almost everything translated, and in "Administration » Configuration » Regional and language" I see that I have almost 60% of translations to Lithuanian.

However, not everything is translated. For example, harmony forum module thread reply;

2 replies

Atsakyti

Reply as a new thread

      (0) Like&nbsp;

and user profile statistics

Thread count:

Post count:

How can I edit these strings to be translated?

Identify what template it is using with Themer. Override it and use t() function to wrap those strings needed to be translated.


how to stay on the same page on clicking a link I need to know how to stay on the same page when a link is clicked. If l(), what can be passed as the second argument for the link to be for the page currently visualized?

I need to override l() for menu slot titles inside the megamenus module so that they don't redirect to a different page. Is there any token in Drupal 7 which stores the URL of the current page being displayed?


Generating arbitrary internal URLs I'm generating the URL inside a controller in a custom module. The URL I generate is to pages on the same site, but not in the module. I want to append an arbitrary number of slugs to the end of the base URL. Some slugs depend on the return values from other API calls, so there's no way to predict how many there are, or what they will be.

I want to generate a $url variable of the form:

'www.base-path-of-website.com'/any/number/of/arbitrary/slugs

I have tried using:

Url::fromRoute()

But cannot figure out how to get the base route for the website from it. Or how to add arbitrary slugs.

This was trivial in Drupal 7 and earlier, but I cannot find how to do it in Drupal 8. In Drupal 8, how do you generate arbitrary internal URLs from a module?
What should I be doing?

From the Drupal API docs for Url::fromRoute()

  Creates a new Url object for a URL that has a Drupal route.

  This method is for URLs that have Drupal routes (that is, most pages
  generated by Drupal). For non-routed local URIs relative to the base
  path (like robots.txt) use Url::fromUri() with the base: scheme.

For this method, you need to provide the route name as defined in your module's .routing.yml file, along with an array of parameters in your route:

\Drupal\Core\Url::fromRoute('mymodule.my_route', array('route_param' => 'param_value'))->toString();

Alternatively, if you don't have a route to plug into you can use Url::fromUri() as the docs specified:

\Drupal\Core\Url::fromUri('base:/any/number/of/arbitrary/slugs',array('absolute' => TRUE))->toString();


How to implement RSVP Functionality? I have created event using Calendar in Drupal Commons. I need to implement RSVP for these events Details like FB event section.

Kindly guide me to create RSVP plugin in Drupal Commons. I just searched the web to get some reference link for RSVP Implementation in Drupal 7. In that link, user nicoz commented "Use the flag module ".

I just installed flag module and create that flag like Participant/Maybe/No, but I cannot achieve it, because a flag will only provide flagged content and unflagged content.

Kindly give me any idea for this type of flag creation or else give me alternative module for  RSVP functionality.

A flag that is created with the Flag module is indeed a boolean variable (it is "on" of "off"). In this specific case you should implement 3 possible values, i.e.:

Participant
Maybe
No

Here is how you can get that implement by using 3 flags:

Flag 1, with something like these "Link text" values:

(to Flag) = Yes I plan to participate.
(to Unflag) = Please ignore my "Yes I plan to participate" from before.

Flag 2, with something like these "Link text" values:

(to Flag) = I'm not sure yet if I'll participate.
(to Unflag) = Please ignore my "I'm not sure yet if I'll participate" from before.

Flag 3, with something like these "Link text" values:

(to Flag) = No I will not participate.
(to Unflag) = Please ignore my "No I will not participate" from before.

If it fits your requirement, you could "assume" that for somebody who did  NOT set Flag1 and did not set Flag 2, the default applies which is something like "user does not want to participate, or didn't bother to let us know about it". That will avoid you need Flag 3.

If you're not familiar enough with the Flag module yet, I strongly recommend watching the set of 8 video tutorials about this module.

For more details, you may also want to refer to my answer to the question about Display unique text and button in nodes in a view in drupal 7. It contains the details about using the Entity Reference module for this, in combination with the Flag module, and possibly also the Rules module.


dynamic link to view page So i have set up a page view which has the path about/% with % representing the argument used in that view. I now want to link to this page on the main navigation bar.

I created a menu item  about/%dest but that didnt work as i guess the route is already registered by the view? so i altered it to look like this:

$items['%dest/about']= array(
  'page callback' => '_bps_path_redirect',
  'page_arguments' => 'about',
  'title' => 'about',
  'title callback' => 'get_title',
  'access arguments' => array('access content'),
  'type' => MENU_NORMAL_ITEM,
  'menu_name' => 'main-menu',
);

function dest_to_arg() {
  $arg = arg(1);
  return $arg;
}

function _bps_path_redirect($arg) {
  drupal_goto($arg.'/'.arg(1));
}

But to no success, the redirect doesn't work. So am i missing something? Is there a simple way to link a view which has a wildcard in its path?

Solved. I modified the page views to use a static path and then set up a contextual argument to grab the parameter of the url to use as an argument.


Add body class to both Node add and Node Edit Page I want to add a Body class to my Node Add pages and my Node Edit Pages.

How can I do this?

I know that I need use the following in template.php to add a class to Node Edit:

function MYTHEME_preprocess_html(&$variables) {
     if (arg(0)=='node' && arg(2)=='edit') {
      $variables['classes_array'][] = 'node-edit-page';
    }
}

But how can I modify the code to work with node add?

Note: Node Add is when you create a node (e.g. yousite.com/node/add/page).

Node Edit is when you edit an existing page  (e.g. yousite.com/node/1/edit)

Did you try :

function MYTHEME_preprocess_html(&$variables) {
  if ((arg(0)=='node' && arg(2)=='edit') || (arg(0) == 'node') && (arg(1) == 'add')) {
    $variables['classes_array'][] = 'node-edit-page';
  }
}


Upload images in Blocks in drupal admin Is there any way through which we can upload images from blocks in admin ? I have imce to upload pictures but if it was there in blocks it would be have been better , i saw many work arounds for this like creating a cck feild of image type then save it as view, instead is there any straight forward approach like upload module for nodes ?

You could use webfm module upload images and then display them using img tag in the blocks.


When to use Bundles vs Entity Types I have a design question:

I have several models that lend themselves to inheritance very well.

I have an animal object that has attributes that are shared between the dog, cat, and hamster objects very nicely.  However, the source of the dog, cat, and hamster are all from different APIs.

So what I started doing was to build my module around each of the APIs, with the necessary 'fields' effectively hardcoded in the module animal.  I knew that this horrifically violates the DRY principle; but am from the D6 (barely D7 era and hadn't really been introduced to entity types).  This was using custom tables, and custom 'models'.  This also means that I have to create the views, and all the other stuff associated with it myself.

So then I realized that I could actually use entity types for this.  The core animal module exposes only what it needs to (a small set of fields).  And the dog, cat, and hamster modules all extend the animal entity type thus giving me access to all the shared data without having to repeat myself and the added bonus of having views, handlers and the other stuff for almost free (a bit of boilerplate that is copy and paste...).

My questions are thus:

Is this thinking right, that content entity types are the way to go?
I know what I gain, but what do I lose by doing this?
Is this a good approach, i.e. is it fair to extend a base entity type?
Is it better to create bundles for each of the dog, cat, hamster or just use the extending of the animal content type?
When do you use a bundle vs extending a content type?

Yes, using content entity types for this seems like a good idea.

In regards to entity types vs. bundles, which one is better for you depends on your exact requirement (I only noticed after already writing most of this that you already mentioned and specifically asked about entity types vs. bundles, so might be too much explanation, but too lazy to rewrite now :)).

Entity types

You create separate content entity types. Whether you use inheritance for sharing the base field definitions or for example a trait is up to you. The inheritance only exists in code, the data itself knows no hierarchy, it is stored in separate tables.

But yes, sharing code there is perfectly valid. Drupal 8.4 for example adds a base class for publishable entity types: EditorialContentEntityBase, see https://www.drupal.org/node/2870643.

The advantage of this is that you can build each entity type with exactly the base fields that you need, which results in an optimized storage (1-4 base field tables, depending on whether you need revisions and/or translation support and separate tables for multi-value fields). However, the main drawback is that there is no API, neither views nor entity query that allows you to list different types of animals in a list. If that's a requirement, then this might be a no-go.

Bundles

You create a single animal entity type and different bundles for the different types of animals. This is like the node entity type and bundles. They share the same base fields and storage, additional type-specific fields can be added as configurable fields or maybe also per-bundle base fields (I honestly have no idea how well that actually work - and I'm supposed to be one of the maintainers of the entity system). This is the opposite of the above, it's easy to create lists with different animals but you might end up with a considerable amount of per-field tables if you have a lot of fields on your dogs/cats etc.

In regards to downsides, content entities are pretty heavy, they have a complex structure based on typed data and are therefore slower than plain custom objects. Their storage, while extensible, is also limited in various ways, you can only load full entities and there is no support for bulk update for example (but you can implement some things in a custom storage handler). But you get a ton of features for that, the mentioned views integration, widgets/formatters, cache handling/invalidation, revision and translation support and so on.


How to include "File upload" field in the webform composite element? I have created a custom composite element, I want to include "File upload" field...The field is visible to the user and the file is uploaded. But it is nowhere saved.

Depends on the destination folder. This webform FAQ might help you.

Edit: Webform Composite Elements do not support File elements yet. Reference on drupal here

Follow these issues (active as of 6/20/2017) to find release updates-
https://www.drupal.org/node/2883734
, https://www.drupal.org/node/2884624


render($page['content']) in the wrong place! Ok I'm having this really weird problem with my Drupal 7 site. I have edited my page.tpl.php file. Following is the html where this oddity occurs

<?php echo $title; ?>

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

Bestselling

                           <?php print render($page['right']['views_bestsellers-block']); ?>

Poll

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

So far everything looks fine. But when opened in the browser print render($page['content']); prints outside the table before it! I have checked this through firebug.

I have also edited a node.tpl.php file and everything is fine inside it.

Can anyone suggest what is going on?

The content in my node.tpl.php was wrapped in a tr tag. Don't know how it got there. When I removed it everything was fine.


Module Webform won't send email to certain address For some reason the normal contact form won't work. It doesn't send any mail to any address I request.
Therefore, I used the module Webform for Drupal 7.

The problem I have is almost the same described in this thread.

However, for me the problem is even when the domain name is the same.  Like user1@domain.com works, but info@domain.com doesn't.

When I do send to a gmail account, there also is no problem.
Basically, the info@domain.com doesn't seem to be 'supported'.
All the other email addresses do work.

The domain-email is hosted by Gmail. (A Google Business account)

What am I missing?

I was having this same issue. I contacted my host (Hostmonster) and found that there is a setting in your Zone Editor that can fix this issue.

Under MX (Mail Exchanger) I selected Remote Mail Exchanger and under the section that says "Points to" I put exchange.domain.com (replace domain with your domain name). I did this because we are running all of our email through an exchange server.

Try calling your host and explaining the problem.

I hope this helps!


Why can the Views Gantt module not find the DHTMLX Gantt JS library? I am trying to use the Views Gantt module and getting nowhere fast.

The Status Report is complaining that it cannot find the dhtmlxgantt JS library in the libraries directory - despite my having checked its presence over and over.

Has anyone any ideas what I might be doing wrong?

Are you sure the dhtmlxgantt JS library is located in: sites/all/libraries/dhtmlxgantt ?

Within that folder you should have extracted the original library which should have:
sites/all/libraries/dhtmlxgantt/codebase and sites/all/libraries/dhtmlxgantt/samples.

Also make sure the "dhtmlxgantt" folder name is all lower case.


Advice Needed on Associating Articles by user with Nodes I am building a national site, with 30 locations. Each locations page is built from a single content type, "venue".

For each location, the manager is given their own login details so they can keep their venue page up to date.

They will also be able to create an Article whenever they have news. All Articles will display a teaser on the main national page, but It should also appear on that managers location page, but not all of the others.

I am after some advice on how to make this happen with views. Obviously I wouldn't want to create a separate view for every location page and only display results by author.

Ideally there would be one view that I could display in a block on every venue page. It would need to get the related author information (maybe from a CCK field), and then display the article results of the owner of that venue. But how do I connect a node to a user, that a view can read?

Hope that makes sense, I'll try and explain it better if you need me to!

This is rather straightforward in Views 3.x - you just want to create a relationship based on the field that you are using to associate the content. This could be something as simple as an author but for your case it sounds like you are going to have multiple types of content that relates back to a venue, ex. articles, etc.

So you would want to use a module like entity_reference and create a field of type entity reference, perhaps named "Related to Venue", that connects to your venue content type. Then add this field to whatever content types you have and when a user adds a new node (ex. an article) they could relate that back to the appropriate venue.

Now in your view block for the venue page, you just need to create a relationship using this field and then add a contextual filter that will find the appropriate node id from the venue page. This is a bit tricky but this is a very common task and this handbook page on d.o walks you through the basics.


Copy content of one node into different content type Does anybody know how to copy a content of one node from one content type into different content type?

Content type A -> Content type B

I would like to copy the contents from the fields of content type A similar to content type B and set it as default for content type B, but I would let users to edit the field. I can't do node clone because content type B has more fields than content type A and also each content has a different URL aliases.

I tried entity reference prepopulate but it doesn't meet my needs. Also tried cross clone but I'm loosing my brain because I can't get it to work by rules, no instruction.

Are there any available module I can use? if you have any other suggestions please be nice to a beginner. :)

Thank you very much!!

You may be interested in Node Convert module:

  Node Convert adds a menu tab "Convert" on the node view page, i.e. node/1/convert, which gives the ability to convert the node from its current node type to another node type. The module provides the means to transfer all the field values of the current node type into fields on the destination node type, or discard them.

Of course this does not clone, but you can use node clone to create a clone of the A content type, and then convert said clone to content type B.


Overriding Field Collection output I have a content type named: lectures

In this content type I have a field collection field named: field_course_video_slide_sync

This field collection consists of 3 fields: field_start_slide_sec, field_slide_title and field_slide_number

What I'm trying to achieve is to rewrite them into this:

field_slide_title

I've tried tpl.php, preprocess_node, field_get_items and views but nothing seems to work. I can't figure out what I'm missing.

Please override field-collection-item.tpl.php file present in the Field Collection module directory. You can put your code in that. Just simply copy it to your theme folder, and place the code inside it.


MegaDrupal MD.Foto: Module dependency displaying incompatibility status I've downloaded the MegaDrupal MD.Foto theme. The feature module for MD.Foto has a few dependencies. One of the dependancies is on Chaos Tools, which I loaded. After doing so, I noticed that the Panels module began displaying the incompatibility message:

Requires: Panels (disabled), Chaos tools (>=1.4) (incompatible with version 7.x-1.2)

What do I need to do to correct this?

If you think Ctools 7.x-1.4 is the one you installed in your system and that Drupal wrongly detect it starts by clearing the cache. Then searh ctools.info file in your web root, if you find more than one, then you have duplicate installation of the Ctools module. Likely one of then is too old but is the one picked by Drupal. Remove it. If not, check the version in this file.


loading nodes with Ajax/jQuery Assume that we have a list of titles on the left and a div on the right side of the page that displays posts. when I click one of the titles it first removes content of that div and then loads node content. how can I do this? is there any module or function to do that?

You could look at the Quick Tabs and Vertical Tabs modules.  Otherwise you could write your own custom module if you had super specific needs and are proficient with drupal menu callbacks and php and of course jQuery.


Deny Access (instead of 404) for non-existant user accounts For a particular project I'm working on, I'd like to return access denied instead of a 404 for non-existant user accounts. I've tried setting a custom 404 page callback and access callback in hook_menu(), and then returning FALSE when paths like user/ are visited, but that doesn't help. I've also tried calling drupal_access_denied() directly in the callback, but that just results in a server error.

I've also tried overriding the user/%user menu item in hook_menu_alter(), but that has no effect on 404 not found pages.

Is there any way to get paths like user/239841239 (any non-existent user ID) to show an access denied page instead of a 404?

[Update: I simply moved the code I was using in the custom 404 page access callback (see below) to the page callback, and now the access denied page is being served correctly.]

// If visiting a non-existent user page, redirect to access denied.
if (strpos(request_path(), 'user/') !== FALSE) {
  drupal_access_denied();
  drupal_exit();
}

I would try setting up a conditional redirect from your 404 page to your custom users-specific error page, that only fires if the path of the referrer is user/*.

I would try to do this using Rules.


Other (related) nodes with the same taxonomy block grouping problem Quick view: I want to create a views block that lists all other nodes that have the same taxonomy term(s) and I want to group the related nodes by term.

I have trouble while doing this:

The content type has some taxonomy terms fields and one of them is my_taxonomy_field. I can enter multiple values to this field.

What I basically want is to show all other nodes tagged with the term(s) on this node and group them by terms. I could do this by contextual filters (content: has taxonomy term ID + ) as explained here or here.

Let me explain:

This is my node list:

NODE 1 taxonomy term field: term 1, term 2, term 3
NODE 2 taxonomy term field: term 3, term 4
NODE 3 taxonomy term field: term 5, term 6, term 7
NODE 4 taxonomy term field: term 6, term 7
NODE 5 taxonomy term field: term 1, term 3
NODE 6 taxonomy term field: term 1
NODE 7 taxonomy term field: term 8
NODE 8 taxonomy term field: term 2, term 9

Let's look at NODE 1, it has these terms: term 1, term 2, term 3

And the terms are tagged on that nodes:

term 1: node 1, node 5, node 6

term 2: node 1, node 8

term 3: node 1, node 2, node 5

This is the related nodes block based on the taxonomy term field:

node 1 (excluded)
node 2
node 5
node 6
node 8

I want to group them by terms as that (note that current node (node 1) excluded):

BLOCK

TERM 1

node 5
node 6

TERM 2

node 8

TERM 3

node 2
node 5

I tried to this with that way: views -> style -> settings (grouping field) and I selected the taxonomy term field. It does what I want, not what I want actually, more than what I want because it creates a views block as that:

BLOCK

TERM 1

node 5
node 6

TERM 2

node 8

TERM 3

node 2
node 5

TERM 4

node 2

TERM 9

node 8

This views doesn't add any (irrelevant) nodes to the list, the nodes are the same with the un-grouped one but because node 2 and node 8 are tagged with other terms, other terms listed here.

How I could list related nodes as grouped but without this 'unwanted' terms, with only the terms in the current node?

(Note: I'm working on both two ways mentioned above, these are the screenshots of them):

Method 1:

Method 2

I've used tags as the term field, so adjust for that.

Create the block view as follows:

A view of content (nodes).

Relationships:

Content: Tags (field_tags), require relationship  // you will use your term field here
Taxonomy term: Content using Tags (Relate each Content with a Tags set to the term.) and set the relationship to the first relationship added, and tick require this relationship // yours will be named differently

Contextual filters:

Content: Nid (node id). Set the relationship to the second relationship added. Provide a default value of Content ID from URL for WHEN THE FILTER VALUE IS NOT AVAILABLE. Specify a validation criteria of Content -> your content type -> Node ID -> Hide view
Content: Nid (node ID). DO NOT USE A RELATIONSHIP. Provide a default value of Content ID from URL for WHEN THE FILTER VALUE IS NOT AVAILABLE. Specify a validation criteria of Content -> your content type -> Node ID -> Hide view. Click on more and tick Exclude.

Fields:

Content Title (NO relationship)
Taxonomy term: Name, use relationship 1, and hide from display

Sort Criteria

Taxonomy term: Name, use relationship 1, ascending
Content Title, ascending

Filter Criteria

Add a filter of Content (node) type to filter on your content type.

Format:

Unformatted list, with settings: Grouping field Nr.1 set to the term field (field 2)


How to show specific views for certain combinations of taxonomy terms? I have searched and not been able to find anything related to this specific situation.

I would like to show specific views for certain combinations of taxonomy terms in Drupal 7.

I have three different taxonomies each with different terms (I have changed the terms here to make them easier to understand):

Fruit
  - Apples
  - Oranges
  - Bananas

Numbers
  - 1
  - 2
  - 3

Letters
  - a
  - b
  - c

Using these terms I already have a view that shows all items tagged with specific terms based on url such as:

/fruit/apples/1/a
/fruit/apples/2/c
/fruit/bananas/3/b

I achieved this with a view which uses a url in the form of /fruit/%/%/% and multiple contextual filters of type 'Has taxonomy term ID'.

So far so good.

What I would like to do is have different view displays that show for specific urls/combinations of terms:

/fruit/apples/1/a  - display 1
/fruit/apples/1/b  - display 2
/fruit/bananas     - display 3
/fruit/oranges/1/a - display 1
/fruit/oranges/1/b - display 2

Does anyone know how I can achieve this or have any alternate solutions/ideas?

In a custom module you could implement the hook hook_views_pre_view()

e.g.

function my_module_views_pre_view(&$view, &$display_id, &$args) {

    if ($view->name == 'the_view') {
        // if url matches certain pattern
        $view->set_display('your display');
    }

}


Multistep CCK module I was working with the Multistep module.

While working with this module I found that it creates a node of the corresponding CCK after the first step itself and then keeps editing the node. Is there any setting or any other method by which this can be stopped?

I want my CCK node to be created only after the last step of the multistep is finished. Is there any other way to acheive the required without using the module?

On a recent drupal project I used multistep and ran into similar issues.

To work around this I used with drupal "workflow" states, to keep the incomplete forms as draft, and have users explicitly set the form to complete by changing the state on the last page.

We then rewrote all the drupal views that we used for reports, so that they filtered out any draft nodes or nodes with state not set.

You might also be able to change the state automatically, by hooking into node save and writing some code to check whether the user is on final page, and doing any extra checks to confirm that the node is completed and should be moved to a different state.

 $step = _multistep_get_current_step($type);

Do watch out that the multistep current_step may be return 0 if the user or admin user viewing all steps on one page. Also watch out for loopholes where users can skip past steps onto final page without completing everything.

I realise for some applications that a lot of partially completed nodes is just untidy, but
advantage for us was that our users could come back to partially completed forms and continue later, and that it also gave us an insight into how many people gave up part way through, all of this could be managed using normal drupal views to produce lists of items in draft state.


no-indexing a views page Im using D7 and views 3 and I cant seem to find a solid answer on how to do this or if its possible but I created a page in views and I wanted to no-index the page, I dont see any options in views to do it so im wondering if this is possible and if so how can I go about doing this.

Any help is appreciated it.

EDIT**

Here is a function I managed to come up with however it something is making it not work. Does anyone have any suggestions?

function noindex_taxonomy(&$head_elements) {
  if (arg(0) == 'taxonomy' && arg(2) == 104 || arg(0) == 'taxonomy' && arg(2) == 103 || arg(0) == 'taxonomy' && arg(2) == 108) {
    $head_elements['noindex'] = array(
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'robots',
        'content' => 'noindex',
      ),
    );
  }
}

There is not any option in views module to add metatags. but you can add metatags to any url of your site by other drupal metatag modules.
See How to define Meta tags on Views?.


Which hook can I use before or after submitting a webform form? I created a webform form with drupal 8.

I would like to populate a database table with information from my form before or after submitting.

I guess there must be a hook like hook_webform_pressave () or hook_webform_insert () but I have not found the solution.

Thank you for your help

Take a look at the answer to Add a custom submission handler to a form. This will tell you how to add a submit handler to a form. You can use the same approach to add a custom submit handler to the webform and then perform the operations you want from the submit handler.


Get the first instance of a field where it's not null from rows I've got a view page, which is pulling together quite a few content types. All of these content types have a field called field_image, however some are not required and/or are missing.

I basically need to grab the first (latest - sorting by author date in my view settings) row, check if there's a field_image, if there is, we can just return that field, if not, repeat.

I thought about a few different ways of doing this, and I thought that I'd make it a Twig command for ease. My issue is that I can't seem to get the single field I'm looking for.

My Twig function is currently:

public function get_first_instance($field, $rows) {
  foreach($rows[0]['#rows'] as $row) {
    dump($row['#row']);
    exit;
  }
}

I'm running the Twig command from my views-view--my-content-type--page.html.twig template, passing a string, and rows.

I can see that the field_image is located in _entity > #fields > field_image, I'm just not sure how to reference this, or what function to use to load the entity?

Thanks for any help in advance.

Solved it, makes sense now!

public function get_first_instance($field, $rows) {

  foreach($rows[0]['#rows'] as $row) {
    $entity = $row['#row']->_entity;

    if($entity->hasField($field)) {
      $value = $entity->get($field)->getValue();

      if(! empty($value)) {
        return $value;
      }
    }
  }

  return dump('Field not found: '.$field);
}


General Content Search of Content type Exposed form Is there a method of giving a user the ability to search any term within all content of a particular node through an exposed form. For example you have the content type of, say - Business, with the fields of - CEO and Base of Operations. Could you give them a simple search that looks for a match in both those fields?

This is certainly possible and there can be many approaches to this, but it would require some effort in any case.

Taxonomy terms are not indexed by core search, therefore you would need to rely on a third party module. Such popular modules are Search API and Apache Solr.

My preferred method, in short, is to use the Search API in combination with Views:

Install the modules Search API, Search API DB, Views, Ctools.
Create server and index, add the taxonomy fields in the index.
Create a view for the search page based on the index
Filter by eg. "Search: Fulltext search", exposed
Add any fields to view, such as "Rendered entity" (for teasers etc.)
Sort by any field, such as "Search: Relevance".


FacebookforDrupal Publish to stream isnt working? I am trying to publish a node onto facebook. Below is my code. In hook_nodeapi(), I have placed a dpm("test") but it isnt showing. I am assuming that this function is not called at all?

function fb_stream_ext_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  dpm("test");
  if ($op == 'insert' || $op == 'update') {
    if (isset($node->stream_publish) && $node->stream_publish) {
      $attachment = array(
        'name' => $node->title,
        'href' => url('node/' . $node->nid, array('absolute' => TRUE)),
        'description' => filter_xss($node->teaser, array()),
      );

      /*
        if ($picture = $GLOBALS['user']->picture) {
        $url = url($picture, array('absolute' => TRUE));
        $attachment['media'][] = array(
        'type' => 'image',
        'src' => $url,
        'href' => $url,
        );
        }
      */
      if ($logo_path = theme_get_setting('logo_path')) {
        $url = url($logo_path, array('absolute' => TRUE));
        //dpm($logo_path, "logo_path is $logo_path and url is $url");
        $attachment['media'][] = array(
          'type' => 'image',
          'src' => $url,
          'href' => $url,
        );
      }

      $user_message = t('Check out my latest post on !site...',
                        array('!site' => variable_get('site_name', t('my Drupal for Facebook powered site'))));
      $actions = array();
      $actions[] = array(
        'text' => t('Read More'),
        'href' => url('node/' . $node->nid, array('absolute' => TRUE)),
      );
      fb_stream_publish_dialog(array('message' => $user_message,
                                     'attachment' => $attachment,
                                     'action_links' => $actions,
                               ));
    }
  }

  // Another way to add like button, as part of a node.
  if ($op == 'view' && variable_get('fb_stream_ext_nodeapi_add_like', FALSE)) {
    $url = fb_scrub_urls(url('node/' . $node->nid, array('absolute' => TRUE)));
    $node->content['dff_like'] = array(
      '#value' => "<fb:like href={$url}></fb:like>",
      '#type' => 'markup',
      '#prefix' => '
',
      '#suffix' => '
',
    );
  }
}

Any known solution for this?

Sorry, there is no hook_nodeapi() for D7. In D7, there are seperate hooks for create, update, view and delete operations. You could use this Link as a reference.
You could insert your dpm("test"); inside hook_view() to test it.


condition inside template.php (if logged_in/logged_out and else) Is it possible to perform condition inside template.php (if logged_in, do these...else do that/ do nothing)?

I am a front-end developer, and as a front-end developer, i like my code clean. So i'm cleaning up my drupal html source code output.

I found some modules out there, that help a lot, and one of then is HTML5 Tools and Metatag (thank you for the team developers). But even with those great tools, i still having the "Drupal.settings" in my html output.

Ocasionally, i found that i can remove the "Drupal.settings" from the html with the hook_js_alter :

  function MYTHEME_js_alter (&$js) {   unset($js['settings']); }

But the problem is: my logged in users still needing this "Drupal.settings" because some modules use it. So that's why i'm asking if there is a way to perform condition inside template.php to logged_in/logged_out users.

THank you in advance

This should help you out. Drupal user login - How to tell if a Drupal user is logged in (authenticated)

You can also use the utility variable $logged_in: Returns TRUE if the user is registered and signed in.

Updated answer.

In template.php, you can use global $user; to check and see if someone is logged in.

global $user;
if (isset($user->roles[1])) {
  //Put code here.
}

Checking against Devel, you can see that $user->roles[1] means it's an anonymous user.


Rules sometimes don't convert saved node to nid I have a strange problem with Rules. I try to set up 2-directional entity references. It works well with one content type, but fails with another. In the latter case, saved node is not converted into node when used as parameter in action like "Set data value" and Drupal tries to save it as array (which fails, of course).

So the questions is: Do you know about something (field, content type setting), which prevents Rules from properly converting saved object?

I'm using latest Rules dev from Drupal 7.

Rules export and error message can be found at https://gist.github.com/miloskroulik/898acaea40097724ff3e

So, the problem was in the entity reference field Rules were operating on (when adding value to it). The only solution I was able to come up with was to create a new field.


How to validate a file upload field added to a form using hook_form_alter? I am trying to add a file upload field to all story node forms. I tested the code and I am successfully getting the file upload field  on the form.

$form['my_file_upload'] = array(
    '#attributes' => array('enctype' => 'multipart/form-data'),
  '#type' => 'file',
  '#title' => t('Image'),
  '#description' => t('Image should be of minimum 50x50px width and should be of type png or jpg'),
  '#collapsible' => TRUE,
  '#collapsed' => TRUE,
  '#size' => 48,
  '#weight' => 4,
);

Now the question is How do I validate the file and also how do I retrieve the file after it has passed validation?

(Site runs on Drupal 6)

What you describe is what the Upload module does: In upload_form_alter() (an implementation of hook_form_alter()), it adds the form element to the node edit forms, and in the form submission handler it adds to the form (upload_node_form_submit()), it handles the uploaded files. With _upload_file_limits(), it checks the user didn't reach the assigned quota; with file_save_upload(), it checks the file passes the validators, and saves the file.

The Upload module, once enabled, allows you to enable the file upload for the content types. For example, for the Page content type, you can enable it at admin/content/node-type/page.

In the node edit form, the form element the Upload module adds appears as in the following screenshot.

If the Upload module is already enabled, and you need a upload form element more, than you should use the CCK module.


REST: 403 forbidden for file entities Ok, so this is a weird one...

I have a HEADless Drupal that I'm using to serve webform submissions. The webform module stores all files as private files.

The issues I'm having is if I view the submission in the angular app as the user that submitted the webform (owner) all the files come back fine. If I try to view the submission as a different user the files come back 403 forbidden. All of the other REST data comes back fine.

Then if I go back and view the submission as the owner again the files are now 403 forbidden for the owner as well. The only way I can get the owner to get a 200 response and see the files again is to flush the cache.

Other users viewing those files seem to lock the files down for the owner as well.

Viewing the webform submission in the actual Drupal has no issues.

Well, found my issue. I didn't enable the File entity module under Media which exposes the permission I needed to set for viewing private files.