Metatags not showing despite calling render in template My custom page.tpl.php is not outputting metatags. I've tried all of these:

 render($page['content'])
 print render($page['content'])
 render($page['content']['metatags'])
 print render($page['content']['metatags'])

I know that the metatags module is passing in the metatag info, because doing this

watchdog('foo', print_r($page['content']['metatags'], true));

results in an array like this:

 Array (
  [node:feed] => Array (
    [abstract] => Array (
      [#attached] => Array (
        [drupal_add_html_head] => Array (
          [0] => Array (
            [0] => Array (
             [#theme] => metatag
             [#tag] => meta
             [#id] => metatag_abstract
             [#name] => abstract
             [#value] => This is an abstract
            )
            [1] => metatag_abstract
          )
        )
      )
    )
    [keywords] => Array (
    [#attached] => Array (
    [drupal_add_html_head] => Array (
    [0] => Array (
      [0] => Array (
        [#theme] => metatag
        [#tag] => meta
        [#id] => metatag_keywords
        [#name] => keywords
        [#value] => keyword1 keyword2
      )
      [1] => metatag_keywords
    )
  )
 )

 ... etc ...

What might be stopping it from rendering the metatags on the page?

I've also noticed that the metatags element in the default devel tab is an empty array, BUT in the tokens tab within devel, the node:metatag tokens are all present and correct.

Further investigation shows that drupal_add_html_head() is being called and the metatag information is being passed in.

Turned out someone had overridden html.tpl.php and had removed the reference to $head. Adding echo $head between <head> and </head> in html.tpl.php fixed the problem.


drupal_mail() in HTML I want the outgoing mail that is sent by my custom module to be in HTML, but I dont know how.

This is my submit function:

//create an array from the companies in the db in a comma separated list
$companies = db_query("SELECT companies FROM {offer} WHERE id = $id")->fetchField();
$companies = explode(',', $companies);

// Set some variables
$from = 'noreply@danielholm.se';
$subject = 'Sent mail';
$module = 'mymodule';
$key = 'mykey';
$language = language_default();
$params = array();
$send = TRUE;

// the data
$question = db_query("SELECT message FROM {offer} WHERE id = $id")->fetchField();
$name = db_query("SELECT name FROM {offer} WHERE id = $id")->fetchField();
$mail = db_query("SELECT mail FROM {offer} WHERE id = $id")->fetchField();
$phone = db_query("SELECT phone FROM {offer} WHERE id = $id")->fetchField();
$compname = db_query("SELECT compname FROM {offer} WHERE id = $id")->fetchField();
$comptype = db_query("SELECT comptype FROM {offer} WHERE id = $id")->fetchField();

// Sort the companies
foreach($companies as $company) {
        $message = drupal_mail($module, $key, $company, $language, $params, $from, $send);
        // Create the mail content
        $message['subject'] = $subject;
        $message['body'] = array();
$message['body'][] = 'THe HTML MAIL HERE';

        // Retrieve the responsible implementation for this message.
        $system = drupal_mail_system($module, $key);

        // Format the message body.
        $message = $system->format($message);

        // Send e-mail.
        $message['result'] = $system->mail($message);

        // Update table where sent to 1
        $update = db_update('offer')
            ->fields(array(
            'sent' => '1',
            ))
            ->condition('id', $id, '=')
            ->execute();

        // Set message of performed action
        drupal_set_message('Done');
        $form_state['redirect'] = 'admin/content/offer';
        cache_clear_all();
}

You can try Mime Mail module.

  This is a Mime Mail component module (for use by other modules).

  It permits users to recieve HTML email and can be used by other modules. The mail functionality accepts an HTML message body, mime-endcodes it and sends it.
  If the HTML has embedded graphics, these graphics are MIME-encoded and included as a message attachment.
  Adopts your site's style by automatically including your theme's stylesheet files in a themeable HTML message format
  If the recipient's preference is available and they prefer plaintext, the HTML will be converted to plain text and sent as-is. Otherwise, the email will be sent in themeable HTML with a plaintext alternative.
  Allows you to theme messages with a specific mailkey.
  Converts CSS styles into inline style attributes.
  Provides simple system actions and Rules actions to send HTML email with embedded images and attachments.


Image crop for touch devices I am using imagecrop module for imagecrop field. but it is not working in touch deveices like ( ipad ). There is any best module for image crop in touch devices?. please help me.

I use the SimpleCrop module, hope it fits your needs.

SimpleCrop provides the simplest workflow for manual crop of images. Basically, you can crop image in three steps: upload image => select area => save content. Functionality of this module covers more than 90% needs of manual image crops.
One of the key feature of this module is that this crop can be used as-is for the end users. So you don't need to theme or to add a workarounds to show this image crop to someone else. It has minimalistic and usable UI.


Which hook can I use for a Drupal webform Post to a Google Spreadsheet? I have a webform with some options and fields. When user submit the form i receive an email.

I want to hook right before(or after) drupal send the email and populate my Google  Spreadsheet so i can review from my Google Drive account.(And send the email as normal)

I have make the connection with a custom php file. I don't know what hook i can use.

The hook you need is hook_webform_submission_presave($node, $submission) that, according to the documentation allows to modify a Webform submission, prior to saving it in the database.

So all values should be available there.


How to configure Secure Pages I'm using Drupal 6 on a website and trying to configure SSL for it.

I installed the Secure Pages module. However I can't figure out the following things:

How to give secure pages to all anonymous users and admin.
How to secure all pages of my site in the settings.

The documentation is not extensive.

Please help as I've spent half the day trying to fix this.

If I recall, SecurePages has an easy config to enforce HTTPS for everyone on all paths. Check the README.

You could also ditch SecurePages and force all traffic to HTTPS via .htaccess.


defining node multicolumn layout with twig template Sometimes I get lost in all the options I have on the drupal platform.

I am currently creating a site for a choir. I want them to be able to add new concerts. There has to be a page for every concert. I want to use a multicolumn layout for those concertpages. This layout I want to define using a twig template. Each concert would get a standard layout at creation.

I want to be able to override that template for each individual concert. Once the grafic design for promotion material is finished the page has to be inline with the grafic design. But it still has to be editable like a normal drupal-page.

I thought about doing that with a content type. But can I theme that in a multicolumn layout using twig? It seems like I only have a {{ content }} variable in twig.

Am I missing something? It seems like a custom entity would be a better solution since I can define a render array and add the fields in different variables wich I can then use in my twig file.

Maybe I got it all wrong, this is my second drupal project and I'm still learning to find the best way of getting things done.

Matt.

Make a copy of node.html.twig and rename the copy to node--[content-type-name].html.twig which goes inside your theme's template folder.

Then in node--[content-type-name].html.twig find and delete {{ content }} and instead in there you put

{{ content.title }}
{{ content.body }}
{{ content.field_name }}

This is how you can render your fields individually.

Then, you can wrap them inside an id or class divs. Ex:

{{ content.field_name }}

{{ content.field_name_other }}


when calling privatemsg_new in a block, how can I correctly set the internal $destination variable? I am calling privatemsg_new in php in a block so that the form to contact the node author is on the same page as the content. here is the code.

$node = menu_get_object();
if ($node->uid != 0) {
module_load_include('pages.inc','privatemsg');
$recipients = $node->uid;
print "
Contact " . $node->name ." about this post.
";
$subject = $node->title ." question.";
print drupal_render(drupal_get_form('privatemsg_new', $recipients, $subject));

Normally you access this form from the node page via a link that reads 'send this author a message' and that link loads a 'destination' parameter into the url query so that, when the message is finished, it redirects you back to the node page.

My code for the form in the block works fine except for the redirection back to the page after submission.  The variable that needs to be set is inside the scope of the privatemsg_new function:

http://drupalcontrib.org/api/drupal/contributions!privatemsg!privatemsg.pages.inc/function/privatemsg_new/7

How can I set that variable so that redirection works correctly?

EDIT 8/1/2012
Eugene's answer below was the correct direction and code for this particular problem, but I wanted to update my question with the exact code necessary to achieve a fully functioning 'Contact Author' block.  Simply copy and paste this in for Drupal 7 and it should work great, if you looking for the same solution.

$node = menu_get_object();
if ($node->uid != 0) {
module_load_include('pages.inc','privatemsg');
$recipients = $node->uid;
print "
Contact " . $node->name ." about this post.
";
$subject = $node->title ." question.";
$form = drupal_get_form('privatemsg_new', $recipients, $subject);
// Setup destination parameter to be equal to current page.
$form['#action'] = url('messages/new/'. $node->uid, array ('query' =>    drupal_get_destination()));
  print drupal_render($form);
drupal_set_title($node->title);
}

You have to set the drupal title manually. The reason being that the privatemsg_new function overrides this.

Try this code in block, if you don't want to implement any hook in custom module.

$node = menu_get_object();
if ($node->uid != 0) {
  module_load_include('pages.inc','privatemsg');
  $recipients = $node->uid;
  print "
Contact " . $node->name ." about this post.
";
  $subject = $node->title ." question.";
  $form = drupal_get_form('privatemsg_new', $recipients, $subject)
  // Setup destination parameter to be equal to current page.
  $form['#action'] = url('node/'. $node->uid, array ('query' => drupal_get_destination()));
  print drupal_render($form);
}


How can I add custom content to a Drupal 6 menu? 1) Currently I have drop down menus for primary & secondary links. They need to now be mega-menus, and need to include the item teaser as well as the link:

  Link 1

Teaser for this link

2) We also want to include webforms or any content in a menu list item. I am hearing that blocks are the way to go, but again, am a bit confused.

Can anyone help?

Try the megamenu module.  I haven't used it, but it appears to be designed to do exactly what you are looking to do.  Unfortunately, it appears that the capability to add blocks inside menu items only exists in the version for Drupal 7, but the D6 version supports most of the functionality you need.


How to use $query->add_where_expression in hook_views_query_alter I'm trying to use hook_views_query_alter() to select some nodes based on a calculation using two fields in that node.  I can't find much documentation or many examples that help me understand how this works.

I could use Views PHP, but this module is very buggy in Drupal 7.

I think I need to use $query->add_where_expression() but I can't work out how to use it.

My view is called "latlong", and as a test to see if I have the right approach, I've tried to select nodes based on the value of field_latitude. Copying other functions i've seen through googling, this is my best guess, but it's not working. I know one of my nodes has the value 53.9519 so if my syntax is right I should get a row back, but I don't:

function my_module_views_query_alter(&$view, &$query) {
  switch($view->name) {
    case 'latlong':
      $query->add_where_expression(0,'field_data_field_latitude.field_latitude_value = 53.9519');
      break;
  }
}

If I print_r($query->where[0]) I get:

Array (
  [conditions] =>
    Array (
      [0] =>
        Array (
         [field] => field_data_field_latitude.field_latitude_value = 53.9519
         [value] => Array ( )
         [operator] => formula ) )
         [args] => Array ( )
         [type] => AND )

What am I doing wrong?

If you look at the documentation for views_plugin_query_default::add_where_expression(), you will notice the following note. (The emphasys is mine.)

  The caller is reponsible for ensuring that all fields are fully qualified (TABLE.FIELD) and that the table already exists in the query. Internally the dbtng method "where" is used.

Looking at this Stack Overflow question, I would get your code should be the following one.

function mymodule_views_query_alter(&$view, &$query) {
  switch($view->name) {
    case 'latlong':
      $alias = $query->add_table('field_data_field_latitude');
      $query->add_where_expression(0, "$alias.field_latitude_value = :latitude", array(':latitude' => 53.9519);
      break;
  }
}

Since the latitude is a floating point, I would use a comparison that is different from $alias.field_latitude_value = :latitude, for example checking the latitude is inside the range [$latitude - $epsilon, $latitude + $epsilon].


How to add validation on 'next' button using fieldgroup module I am creating a multiple page registration form using the field group module and
I want to add validation on 'next' and 'previous' buttons.

If the first page's field is empty, the user can not go to next page they show some alert or message.
I am using jquery but not successful with it.

Create own module and add

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

  if ($form_id == "FORM_ID") {
        $path = drupal_get_path('module', 'MY_MODULE');
        drupal_add_js($path . '/validations.js');
    }
}

Create validations.js file to the MY_MODULE folder and put this there

(function ($) {
Drupal.multipageControl.prototype.nextPage = function() {

        // Group check here, otherwise every pages required fields invoke error.
        if (this.wrapper.hasClass('GROUP-NAME')) {
       $('input.required').each(function(index) {
        $(this).rules("add",
            { required:true, messages: { required: "field is required."} }
        );
    });

validated = 1;

$('input.required').each(function(index) {
                // You might want $("#YOUR-FORM-ID") here instead of just form.
    if (!$("form").validate().element(this))
        validated = 0;
});
}

if (validated == 1)
    this.wrapper.next().data('multipageControl').focus();
else
    $('html, body').animate({scrollTop:0}, 'slow');

}
})(jQuery);

This actually checks all fields in your form that are required.


How to restore uploaded backup in Drupal 7 (public files or entire website) correctly? When trying to restore public directory I see:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'temporary://cvetmagazin-2016-03-13T16-28-59.tar__0.gz' for key 'uri': INSERT INTO {file_managed} (uid, filename, uri, filemime, filesize, status, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => cvetmagazin-2016-03-13T16-28-59.tar_.gz [:db_insert_placeholder_2] => temporary://cvetmagazin-2016-03-13T16-28-59.tar__0.gz [:db_insert_placeholder_3] => application/octet-stream [:db_insert_placeholder_4] => 166375 [:db_insert_placeholder_5] => 0 [:db_insert_placeholder_6] => 1457901164 ) в функции drupal_write_record() (строка 7316 в файле /home/user/drupal_fish/apps/drupal/htdocs/includes/common.inc).

However, Drupal accepts database dump without errors. How to fix that? Thanks.

I think it's a concurrency issue when D7 makes a file object in db.
try to use this modules Upload QC
please let me know if it works with you.

also try to check the temp file name. and make sure tat the database is restored correctly.


Cannot upload file of type image I am experiencing a really strange behavior I have never seen before with Drupal. I am able to upload files of every type but not images. The files system is public. The problem appears on the local test server and on the live server.
Error message:
The image upload widget shows the standard error box logging:
**The file xyz.jpg could not be uploaded.

This value should not be null**

This issue appears on the whole site on every image of the file field widget within the backend.
Even the file upload for Drupal's "File Archive" does just work with every other file type than 'jpg', 'jpeg', 'gif', 'png' file types.
The issue appeared after updating to the "web/" file structure while also updating the core to 8.8. I tried to update to 8.9.12 including every module installed but the error when trying to upload a file stays.
I rechecked all the settings regarding "tmp folder" and also tested the folder access rights (chown, chmod). It is set to 777.
I updated the database (drush updb) and also rebuild the cache (drush cr).
No PHP error log is created (not in Drupals Watchdog or the apache log).
I am sure that it is not a configuration issue as I am able to upload files that are not image files without problems. Another interesting bit is that when uploading a file it is actually created in the final sites/default/files location. The file also has the correct owner and access rights.
I could not find a related issue when researching nor I am able to come up with another idea. I even tried to change the file system to private, created new entities with image or file fields and tried different image upload widgets - nothing seems to work.
Any help is greatly appreciated.

After spending good 20hours with investigating the issue I was able to fix it by repairing an entity error in the database via un and installing the file_entity module.


How to use service container correcly? I want to use service container inside my class so I have this this:

class SomeController extends ControllerBase {

  protected $entityTypeManager;
  protected $requestStack;

  public function __construct(EntityTypeManagerInterface $entityTypeManager,RequestStack $requestStack){
    $this->entityTypeManager = $entityTypeManager;
    $this->requestStack = $requestStack;
   }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('request_stack'),
    );
  }

  public function content() {
    $testEntityTypeManager = $this->entityTypeManager->getStorage('node')->getQuery();
    $testRequest = $requestStack->getCurrentRequest();
    //do something with these...
  }

}

What I wanted to do here is create a container for EntityTypeManager and RequestStack. Now phpStorm is giving me a warning regarding public static function create(ContainerInterface $container) and it says Method call uses 2 parameters, but method signature uses 1 parameters and I can't use it in my method content().

$testEntityTypeManager and $testRequest are just examples with which I would do something else but even now it doesn't work and phpStorm tells me getCurrentRequest().

Sure I can use them statically but that is not what I'm trying to achieve here. Any push in right direction is appreciated!

The error:

  Method call uses 2 parameters, but method signature uses 1

Your create() method is defined to only receive a single argument, $container. This must be a debugger in PHPStorm giving you this output, because what it is saying is that the code calling SomeController::create() is passing two arguments. So the second is getting lost. Your problem is likely stemming from that, and probably means one of two things:

The code calling the create() function is mistakenly passing a second value, or
Your create() function needs to be re-defined to catch the second argument, and do something with it.

ControllerBase::create only expects a single argument, $container, and since your function defines that, I'd guess the more likely culprit is the calling function passing an unnecessary argument (#1 above). However, if the passed variable is necessary for some reason, SomeController::create() can be redefined to catch an optional argument:

public function create(ContainerInteface $container, $additional_param1 = NULL) {
  if (is_null($additional_param1)) {
    throw new \Exception('$additional_param_1 is required');
  }

  // Continue as normal.

}


How to add e-mails in 2 different databases in drupal 7 I used drupal 7.10 to built my website and i used 2 modules, the first is the webform to build the membership form, and the simplenews to write and send newsletter to users.

Anyone could subscribe in the newsletter even if it is not a member by enter her\his email in a newsletter subscribtion block in the home bage.

but what i wnat is that, when a user becomes a member he will join the newsletter service by adding his e-mail directly to a newsletter database, he don't need to enter his email in the newsletter subscribtion block agine.

How can i do this???

You have an option in Simplenews to subscribe the user on registration since 6-x.2.x : http://drupal.org/node/658242.


What is an entity URI? What are entity URIs? What are they used for?

Every answer I see is like Just define in your hook_entity_info() a URI callback. Why, if we are able to define entities and make them work without a custom URI? What is the benefit of the custom URI? Does it bring additional custom, cool functionality to our table that we can exploit?

Some examples of things out there on the web that mention Entity URIs, but don't leave me the wiser: Do entities need to have URIs?, Developing a custom Drupal entity, path(), uri(), defaultUri(), entity_class_uri, what to use?

In a nutshell: Why go through the hassle of defining an entity URI callback in your hook_entity_info(), if you can live without it?

Why go through the hassle of defining an entity URI callback?

To allow other modules to override the entity URI and / or provide a default one.

For instance, I have a student entity defined by the student module. The entity URI is student/%student and is defined from the following hook.

/**
 * Implements hook_entity_info().
 */
function student_entity_info() {
  $return = array(
    'student' => array(
      'label' => t('Student'),
      ...
      'uri callback' => 'student_uri',
      ...
    ),
  );
  return $return;
}

/**
 * Entity uri callback: gives modules a chance to specify a path for a student.
 */
function student_uri($student) {
  return array(
    'path' => 'student/' . $student->student_id,
  );
}

Now, let's say I have another module, student_special, which provides a different URI depending on a property in the student object. I can override the URI by implementing hook_entity_info_alter().

/**
 * Implements hook_entity_info_alter().
 */
function student_special_entity_info_alter(&$entity_info) {
  // Add a URI callback to the student entity.
  $entity_info['student']['uri callback'] = 'student_special_uri';
}

/**
 * Entity uri callback: points to a unique URI if the given student is awesome.
 */
function student_special_uri($student) {
  // First look for a return value in the default entity uri callback.
  $default_uri = student_uri($student);

  if ($student->is_awesome) {
    return array(
      'path' => 'awesome-student/' . $student->student_id,
    );
  }
  return $default_uri;
}

We can then use the student URI for a variety of things like creating links or redirecting users to the student entity's view page. For example, if we want to redirect the user to the newly created student after submitting a form.

/**
 * Submit handler for the student create/edit form.
 */
function student_form_submit($form, &$form_state) {

  ...

  // Save the student entity.
  student_save($student);

  // Redirect the user to the student URI.
  $student_uri = entity_uri('student', $student);
  $form_state['redirect'] = $student_uri['path'];
  drupal_set_message(t('Student %title saved.', array('%title' => entity_label('student', $student))));
}

This ensures that we get the correct URI, especially if there are modules that overrides the default URI.

  Does it bring additional custom, cool functionality to our table that we can exploit?

Alas, there are no lucky charms at the end of the rainbow. Like @googletorp mentions, you still need to define a menu callback for the URI to work, otherwise the URI is just a string that does not map to an existing Drupal menu callback.

There are two ways that you can go about mapping custom Entity URIs to menu callback items: via a standard implementation of hook_menu(), or by overriding the hook_menu() method in your controller, in case you're using Entity API with custom admin ui controllers.


Accessing a Entity Refererenced field of the current node I have to render a field of a node that is inside a content type in Drupal 8.

I have a content type called summary that has a field, called field_content that is an Entity reference field for unlimited items of a specific content type (article)

I'm able to get the current node and handle the field_content, but I cant access each of referenced items  inside  of this type.

Also I have tried to debug the field_content with  kint but the browser crashes (I suppose that it happens becasue the data dump is very big) and I can't access the inner properties (I have to get a field called field_desc_text inside each article).

I need the node or the nid to load it  of each of this inner items.

This is what i've tried:

       $currentNode = \Drupal::routeMatch()->getParameter('node');
    foreach ($currentNode->get('field_content') as $nodeRef)
    {
      kint($nodeRef); //*This debugs the entire referenced node, but there is no sight of my desired fields
      die;
     // kint($nodeRef[0]); *Cannot use object of type Drupal\\Core\\Field\\Plugin\\Field\\FieldType\\EntityReferenceItem as array
     // kint($nodeRef->get('title')); *Uncaught PHP Exception InvalidArgumentException: "Property title is unknown."

     die;

    }

And this is the output of the kint($currentNode):

https://mega.nz/#!Fogx0LpC!CYvc6YSRs1ZcgOAc4RCfDo5iVqjBLYckvuFEUgqRGx8

Thanks in advance!

I believe you need $currentNode->get('field_content')->referencedEntities() -this should return each of the referenced entity objects.


Create path alias to a custom link I have a taxonomy term that has its own template, inside that template, there is custom links that just add a new argument to the URL
for example the current path is /taxonomy/term/%, one of the custom links will send the user to /taxonomy/term/%/%

with pathauto the url alias changes only when I visit /taxonomy/term/% (vocab_name/term_name), but it won't changed when I vist /taxonomy/term/%/%. I want it like that : vocab_name/term_name/%.

Is that possible ?
thanks in advance.

Check path_alias_xt and subpathauto, I have used subpathauto to achieve this for nodes and path_alias_xt documentation says it does for taxonomy terms too.


How to avoid "An illegal choice has been detected" when updating select list values via ajax? I have four entity reference fields to user entity in a form. Host form is node edit form.
Three of them are select lists, last is Inline Entity Form.

After adding a user entity via IEF I'm trying to update select lists values:

function ebep_users_feature_users_list_ajax($form, $form_state) {

  $ief = array_shift($form_state['inline_entity_form']);
  $options = array('_node' => t('- None -'));
  $commands = array();

  foreach($ief['entities'] as $data) {
    $options[$data['entity']->uid] = $data['entity']->name;
  }

  foreach(_ebep_users_feature_getUserListFieldNames() as $fieldName) {
    $form[$fieldName]['und']['#options'] = $options;
    $commands[] = ajax_command_replace('#'.$fieldName.'_wrapper', drupal_render($form[$fieldName]));
  }

  return array('#type' => 'ajax', '#commands' => $commands);
}

It works, but when I try to add another user via IEF I am getting:

  An illegal choice has been detected. Please contact the site
  administrator.

--- Original answer. Is wrong, check update below.

Just set

$bla['#validated'] = TRUE

On the select that will be updated with AJAX.

Checkout "Illegal Choice has been detected"

--- Update 17 Dec 2019 ---

Actually that was not good advice, that was a long time ago, now I know better.

Ajax callback function is supposed to only return the piece of form that has changed or some ajax commands.

In this case form modification must be made on the form function or a form alter hook. Form building and validation functions are run each time an ajax callback is called. Just check $form_state on your form build or alter function and adjust values accordingly.

See Resolve the error "An illegal choice has been detected..."


Get total revenue for special product I want to get total revenue from a productId on Drupal commerce. How can I do that? I found in drupal commerce's table but didn't see any relationship to get that info.

After some research here is the result. I think it work fine

$totalRevenueQuery = db_select('commerce_payment_transaction', 'cpt')
    ->fields('cpt', array('currency_code'));
  $totalRevenueQuery->addExpression('SUM(amount)', 'amount');
    $totalRevenueQuery->leftJoin('commerce_order', 'commerce_order', 'cpt.order_id = commerce_order.order_id');
    $totalRevenueQuery->leftJoin('field_data_commerce_line_items', 'field_data_commerce_line_items', 'cpt.order_id = field_data_commerce_line_items.entity_id');
    $totalRevenueQuery->innerJoin('commerce_line_item', 'commerce_line_item_field_data_commerce_line_items', 'field_data_commerce_line_items.commerce_line_items_line_item_id = commerce_line_item_field_data_commerce_line_items.line_item_id');
    $totalRevenueQuery->leftJoin('field_data_commerce_product', 'commerce_line_item_field_data_commerce_line_items__field_data_commerce_product', 'commerce_line_item_field_data_commerce_line_items.line_item_id = commerce_line_item_field_data_commerce_line_items__field_data_commerce_product.entity_id');
    $totalRevenueQuery->innerJoin('commerce_product', 'commerce_product_field_data_commerce_product', 'commerce_line_item_field_data_commerce_line_items__field_data_commerce_product.commerce_product_product_id = commerce_product_field_data_commerce_product.product_id');
    $totalRevenueQuery->condition('commerce_product_field_data_commerce_product.product_id', $product_id);
    $totalRevenueQuery->condition('field_data_commerce_line_items.entity_type', 'commerce_order');
    $totalRevenueQuery->condition('field_data_commerce_line_items.deleted', 0);
    $totalRevenueQuery->condition('commerce_line_item_field_data_commerce_line_items__field_data_commerce_product.entity_type', 'commerce_line_item');
    $totalRevenueQuery->condition('commerce_line_item_field_data_commerce_line_items__field_data_commerce_product.deleted', 0);
    $totalRevenueQuery->condition('commerce_order.type', 'commerce_order');
  $totalRevenue = $totalRevenueQuery->execute();


How to show validate error of a node listing page i am trying to save form state in database and want to view in a listing page with its error validation.

i.e, i want to validate a previously saved form state from my database.

this is a node type form .

i had already tried node_validate its not working because i fetch the data before submitting the node . so there is no nid and for that it is not working

and also tried  drupal_validate_form but it is showing

[form_token] => The form has become outdated. Copy any unsaved work in the form below and then reload this page

Any help is most Appreciable.

EDIT :

Can any one just say How To save my form and retrieve it from database and load all result in a page .

This may not quite answer your question, but I think it might help with whatever you're trying to do.

You can alter the node creation form to have extra validation and display it on the screen using the devel module, along with a custom module that calls hook_form_alter

function mymodule_form_alter(&$form, &$form_state){
    //add a function in #validate to read form_state and show it on screen
    $form[#validate][] = mymodule_read_values($form_state);
    //or if you want to make it happen before any of the other form validation, uncomment the next line and comment the one above
    //array_unshift($form[#validate], mymodule_read_values($form_state));
}

function mymodule_read_values(&$form_state){
    // make sure you have devel module installed or this will cause WSOD
    dpm($form_state);
    // if you want to prevent form submission you can uncomment the next line
    // throw new Exception('Cancelling form submit - see mymodule');
}

Remember of course, to replace any instance of 'mymodule' with the name of your module, particularly the first one, or the hook won't work.

Doing this will show the structure of the form_state on the screen when you try to save the node.

If you want to target a specific form you can change the first line to

function mymodule_form_FORMID_GOES_HERE_alter(&$form, &$form_state){


Programmatically fill the "Publish On" date field value provided by the Scheduler Module I'm using the Scheduler Module to schedule the publishing date of the content in my Drupal 8 site. I would like to programmatically fill the value of the Publish On date field provided by the scheduler module.

In Drupal 7, I used the following code

function hook_form_alter (&$form, $form_state) {
     $date_format = (_scheduler_use_date_popup()) ? SCHEDULER_DATE_FORMAT : variable_get('scheduler_date_format', SCHEDULER_DATE_FORMAT);

      $form['scheduler_settings']['publish_on']['#default_value'] = format_date($querydate, 'custom', $date_format);
}

This code doesn't work in Drupal 8, since the _scheduler_use_date_popup() function and the SCHEDULER_DATE_FORMAT constant are not available.

I'm using the following code in Drupal 8 which doesn't work:

function hook_form_id_alter(&$form, FormStateInterface $form_state) {
    $form['scheduler_settings']['publish_on']['#default_value'] = \Drupal::service('date.formatter')->format($contest_start_date, 'custom', 'Y-m-d H:i:s');
}

You should be able to provide a default value using a hook_field_widget_form_alter() to modify the #value_callback of the TimestampDatetimeNoDefaultWidget that scheduler uses to a custom one, and this is how you can pass custom logic for a default value. Here's some sample code that could go in your custom module, you could add/modify conditions and logic as needed, but this should at least get things moving in the right direction:

<?php

/**
 * @file
 * Publish On Default module file.
 *
 * This module provides a default value for the "Publish On" value
 * for nodes.
 */

use Drupal\Core\Datetime\Element\Datetime;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\scheduler\Plugin\Field\FieldWidget\TimestampDatetimeNoDefaultWidget;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_datetime_timestamp_no_default_form_alter(&$element, FormStateInterface $form_state, $context) {
  // Only alter the callback for the "Publish On" instance of the `datetime_timestamp_no_default` widget.
  if (isset($element['#title'])) {
    if ($element['#title']->__toString() == "Publish on") {
      $element['value']['#value_callback'] = 'mymodule_publish_on_default_value_callback';
    }
  }
}

/**
 * Callback function to add default time to the publish on widget.
 */
function mymodule_publish_on_default_value_callback(&$element, $input, $form_state) {
  // If no default value, set the default to the current date/time.
  if (empty($element['#default_value'])) {
    $date_format = $element['#date_date_format'];
    $time_format = $element['#date_time_format'];
    $timezone = !empty($element['#date_timezone']) ? $element['#date_timezone'] : NULL;
    $date_time_format = trim($date_format . ' ' . $time_format);
    $date_time_input = date('Y-m-d H:i:s');
    $date = DrupalDateTime::createFromFormat($date_time_format, $date_time_input, $timezone);
    $element['#default_value'] = $date;
    $input = FALSE;
    return Datetime::valueCallback($element, $input, $form_state);
  }
  // Fallback to the original valueCallback() method.
  else {
    return TimestampDatetimeNoDefaultWidget::valueCallback($element, $input, $form_state);
  }
}


How can I pass $title a node variable to html.tpl.php? I'm looking to use the variable $title in my html.tpl.php file. How can I do this?

I would like to just write a bit of php like so:

<?php print $title ?>

So is a preprocess function needed? TPLNAME_preprocess_html() { ??? something like that?

I would like to reference this question here which got me thinking, what is the proper way?

Helpful Question That I Saw

// template.php
function THEMENAME_preprocess_html(&$vars) {
  $vars['title'] = 'my title';
}

// html.tpl.php
echo $title;

http://drupal.org/node/223430


Exposed filter as dependent dropdown? Is it possible to create a view with exposed filter similar to the image given, where location field is a taxonomy term and rest of it are content types with location field as term reference.

Views Dependent Filter Module integrates this functionality with views

  Allows the presence of exposed filters on a view to be controlled by
  values in another exposed filter. Dependent filters are hidden when
  not relevant, and their values are not considered when the exposed
  form is submitted.


Is it possible to use a path like that : user/%user/word with MENU_NORMAL_ITEM instead of MENU_LOCAL_TASK i hope you understood the title of my topic because i have difficulties to express this problem in english.

I would like to change the menu item which is a tab (saved searches) and put it on my menu block.

So i went to the files of the module and found this:

search_api_saved_searches.module

$items['user/%user/saved-searches'] = array(
'title' => 'Saved searches',
'description' => 'View and edit your saved searches.',
'page callback' => 'search_api_saved_searches_user_listing',
'page arguments' => array(1),
'access callback' => 'search_api_saved_search_edit_access',
'access arguments' => array(1),
'weight' => 5,
'type' => MENU_LOCAL_TASK,
'file' => 'search_api_saved_searches.pages.inc',
);

I know that MENU_LOCAL_TASK is a generally a tab, so i tried MENU_NORMAL_ITEM but it didn't work.

I tried some other thing and removed %user $items['user/saved-searches'] but after that i had many error, i tried to debug them but after many hours i stopped, it was clearly not a good solution to change code directly on a module.

So my question is: Is there a easy way to move a menu item from a tab to a menu block when the path has a wildcard components ? If it's not possible, do you think there is, maybe, a workaround to accomplish what i want to do?

Thanks,

i used views to achieve what i wanted to do but it was not easy because :

Fields was not the same and didn't have the good format
There was no filter "current user"
So i create a custom template using views-view-table.tpl.php.

I don't know if what i did is very good:

I call global $user in my template, maybe it's a mistake, i don't know if we can do that
Thxs to criticguy, i improved the following code by removing current user test

 <?php foreach ($rows as $row_count => $row): ?>
    <tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?>>
    <?php foreach ($row as $field => $content): ?>
     <td <?php if ($field_classes[$field][$row_count]) { print 'class="'. $field_classes[$field][$row_count] . '" '; } ?><?php print drupal_attributes($field_attributes[$field][$row_count]); ?>>
     <?php if($field == 'last_execute') : ?>
       <?php $last_execute = t('@time ago', array('@time' => format_interval(REQUEST_TIME - $content))); ?>
         <?php print $last_execute; ?>
       <?php elseif($field == 'created'): ?>
         <?php $created = format_date($content, 'short'); ?>
         <?php print $created; ?>
       <?php elseif($field == 'notify_interval'): ?>
         <?php $interval = format_interval($content, 1); ?>
          <?php print $interval; ?>
       <?php elseif($field == 'results'): ?>
          <?php $tab = explode(',', $content); ?>
          <?php $x = 1 ?>

          <?php foreach($tab as $value): ?>

            <?php print 'Resultat '.$x.''; ?>

            <?php $x++ ?>
          <?php endforeach ?>

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

<?php endforeach; ?>

Final result:

I'm always interested by my question about MENU_NORMAL_ITEM and MENU_LOCAL_TASK.


Title link doesn't change after the content type has been changed The title link for a view block doesn't change after the content type has been changed.
Title "Video" links to http://example.com/video.

After changing the title to "Entertainment" and the content type to "Entertainment", the "video" title has changed to "Entertainment" but the link still link to http://example.com/video.

For title, try putting Entertainment

  Thanks @No Sssweat.


Migrate: What's the difference between prepare() and prepareRow()? Using the Migrate module: I understand that prepareRow() runs a filter on the row and should return TRUE or FALSE based on some conditions, which allows a row to be migrated or not, but could someone clarify:

when to use prepare()
when to use prepareRow()
why you wouldn't add a filter in the initial sql query to filter row results that you might remove/include in either of the above

Thanks!

This is all covered in-depth in the Migrations classes documentation provided by the project. Specifically in the Commononly Implemented Migration methods page which says the following and includes further simple example function implementations. From the docs ...

function prepare_row($row)

  The prepareRow() method is called by the source class next() method,
  after loading the data row. The argument $row is a stdClass object
  containing the raw data as provided by the source. There are two
  primary reasons to implement prepareRow():

  To modify the data row before it passes through any further methods
  and handlers: for example, fetching related data, splitting out source
  fields, combining or creating new source fields based on some logic.
  To conditionally skip a row (by returning FALSE).

function prepare($entity, stdClass $row)

  The Migration class prepare() method is called by the destination
  class prepare() method, after it has called all field-level prepare()
  methods and immediately before the destination object is saved. The
  $entity argument is the destination object as populated by the initial
  field mappings and manipulated by the field-level methods; the $row
  argument is an object containing the data after prepareRow() and any
  callbacks have been applied. The prepare() method is the last chance
  to manipulate the destination object before it is saved to the Drupal
  database. It is important to remember that, since it is called after
  the field handlers, fields will be in their fully-expanded forms
  (i.e., in Drupal 7 a text field value will be at
  $entity->field_textual_data['und'][0]['value'] rather than simply
  $entity->field_textual_data).

The Migrate module is a framework which allows you to encapsulate a migration process from a source piece of data to a destination location and configuration. A migration consists of:

define where the data is
define where the data should go
fetch a piece of data (row)
sanitize the data
begin to move the data (say into an Entity)
actually move the data
after moving the data perform additional action(s)

The API provides hooks to affect the data being moved in this life cycle of a migration. By excluding data from the migration via your initial query you're limiting how much control you have over the total data you could move. For sub-migrations you may find this useful. But in a general content migration you would want your migration to be as all-encompassing as possible.


Trigger a JS function only if the view has no more results. or is empty? Hi this might be a stupid question but i can't seem to work it out.

I'm using 'views ajax get', 'views load more (with waypoints)' and what i'm trying to achieve is to only display the footer when the last page of the view has been loaded and appended to the page. and if the view returns no results (using exposed filters)

I've attempted to use jquery's .ajaxSuccess() but i cant work out how to count the results or even to locate the variable with results. Do i have to search the responseJSON for results

What is the best way to do this? is there some Drupal specific structure i need to know about?

Thank in advance :D

All you have to do is check if the "load more" div does not exist. (check if the load more button is no longer there).

(function ($) {
    $(document).ajaxComplete(function() {
               if ($(".loadmore").length = 0){
                   // do something here
               }
    });

})(jQuery);

Check the actual name of the load more div, I just made it up for this example


Add PayPal WPS payment payload information to Commerce admin e-mail I'm using Commerce with the Commerce E-mail module to customize the e-mail sent to admins whenever there is an order (a payment is received) at the store.  Payment is handled using PayPal WPS through the Commerce PayPal module.

On my site, buyers must input their e-mail addresses before moving on to PayPal, but these e-mail addresses (on my site) sometimes differ from the e-mail addresses registered on buyers' PayPal accounts.

For this reason, I want the admin e-mail (sent when an order is paid for) to include both the e-mail address that the buyer input on my Drupal site as well as their PayPal e-mail address.

Commerce E-mail provides a [commerce-email:order-items] token, but there is no token for the PayPal WPS information.  This information is stored within Drupal; in the Order Admin UI, if you click on the payment details of the transaction, under Payload there is a printout of an Array that includes [payer_email] => thepayeremail@example.com.

Payload array:

Array (
    [13775355555-ipn] => Array
        (
            [mc_gross] => 17.00
            [invoice] => 555-1377531555
            [protection_eligibility] => Eligible
            [payer_email] => thepayeremail@example.com

How can I add the buyer's PayPal registered e-mail address ([payer_email]) into the admin e-mail sent by Commerce?  It would be great if the solution would also allow use of other information in the payload array, such as the buyer's physical address.

You can extract those array and add them data object. After adding them to the token replace function you can use that to create custom tokens which will help you to get the tokens.
That custom tokens can now be used to get the buyer's email address

// Write a code for porting data to token_replace()
$data = new val();
$data->mc_gross = variable_get('mc_gross', '');
$data->invoice = variable_get('invoice', '');
$data->protection_eligibility = variable_get('protection_eligibility', '');
$data->invoice = variable_get('payer_email', '');
token_replace(['payload']', (array) $data);

--------write this in  module_name.tokens.inc file------------------------------------------

 function hook_token_info() {
      $info = array();

      // Add any new tokens.
      $info['tokens']['payload']['mc_gross'] = t('Gross');
      $info['tokens']['payload']['invoice'] = t('Invoice');
      $info['tokens']['payload']['protection_eligibility'] = t('Protection Eligibility');
      $info['tokens']['payload']['payer_email'] = t('Email');
      // Return them.
      return $info;
    }

    function hook_tokens($type, $tokens, array $data = array(), array $options = array()) {
     $replacements = array();

    if ($type == 'payload') {
    foreach ($tokens as $name => $original) {
          switch ($name) {
            case 'mc_gross':
              $replacements[$original] = $data['mc_gross'] ;
              break;
            case 'invoice':
              $replacements[$original] = $data['invoice'];
              break;
            case 'protection_eligibility':
              $replacements[$original] =  $data['protection_eligibility'];
              break;
            case 'payer_email':
              $replacements[$original] = $data['payer_email'];
              break;
          }
        }
      }

      return $replacements;
    }


Set entity reference field to 'autocreate' directly in the entity field definitions I'm having trouble with the two ways of defining forms for entities in Drupal (the first one being in the entity field definitions and the second one being by defining a custom form class).

Now, in a classic form, all I have to do is add an element with the  entity_autocomplete type and set #autocreate to array('bundle' => 'foo'). I tried replicating this in various ways in my entity, none of which worked out (I tried via BaseFieldDefinition's setSetting or in the display options for the form).

What I don't understand is why the two ways of defining forms are so different? Why can't it just be the same syntax in both places?

I'm aware of the Inline Entity Form module, but there doesn't seem to be a proper port for Drupal 8 yet, and what I'm trying to do works perfectly fine when I define the form manually as explained. I just want to be able to define all this in my entity directly to avoid unnecessary code.

I finally found a way to get it to work after digging through the code for the EntityReferenceAutocompleteWidget. To enable automatic creation, I needed to edit the handler settings. Here's my code:

$fields['client'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Client'))
  ->setSettings(array(
    'target_type'      => 'client',
    'handler'          => 'default',
    'handler_settings' => array(            // Added
      'auto_create'    => TRUE              // Added
    )
  ))
  ->setDisplayOptions('form', array(
    'type'     => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size'           => 60,
      'placeholder'    => ''
    ),
    'weight'   => 0
  ))
  ->setRequired(TRUE);


Date Repeat: Display only the first and last instances of a series? I have been going crazy trying to find a way to display only the first and last dates of a series using Date Repeat, either in a view or the node itself, of repeating events.  For example, there is a course that starts on January 16, and repeats every Monday until March 5.  I would like to be able to display something like "Every Monday from January 16 until March 5" or something to that effect.  Does anyone have any advice, can anyone point me in the right direction?

Thanks in advance!!

This is an old question, but I thought I'd put in my two cents.

The only way I can think to accomplish this is with custom PHP and a call to the database. You could collect all of the dates for an event an then just show the first and last. The name of the repeat rule is saved in the field_date_rrule column and could be parsed from there.


Drupal 8 - url to image I can't find how to get image url. I have images in /themes/custom/mytheme/img directory. I think there must be some way to get path to current theme or somethink like that.

You can use {{ directory }} for the path to your theme. Then you just need to add /img/yourimage.jpg.


Delete files on rollback in Migrate? I have a migration that pulls in a PDF with it and populates a content type. When I rollback the migration, it does not delete the PDFs with it.

How can I tell a migration on rollback to clean up after itself? Is there something I can put in the YAML? Is there an event I can hook into?

I wound up doing this to solve this case:

<?php

namespace Drupal\mymodule\Plugin\migrate\destination;

use Drupal\migrate\Plugin\migrate\destination\EntityContentBase;
use Drupal\migrate\Plugin\MigrationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\node\NodeInterface;

/**
 * We need rollback support for deleting files.
 *
 * @MigrateDestination(
 *   id = "myplugin"
 * )
 */
class MyPlugin extends EntityContentBase {

  /** @var string $entityType */
  public static $entityType = 'node';

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
    return parent::create($container, $configuration, 'entity:' . static::$entityType, $plugin_definition, $migration);
  }

  /**
   * {@inheritdoc}
   */
  public function rollback(array $destination_identifier) {
    $entity = $this->storage->load(reset($destination_identifier));

    // Delete attached files on Working Papers.
    if ($entity && $entity instanceof NodeInterface) {
      if ($entity->bundle() === 'working_paper') {
        $fid = $entity->get('field_paper_working_paper')->target_id;

        if ($fid) {
          $storage_handler = \Drupal::entityTypeManager()->getStorage('file');
          $entities = $storage_handler->load($fid);
          $storage_handler->delete([$entities]);
        }
      }
    }

    // Execute the normal rollback from here.
    parent::rollback($destination_identifier);
  }

}

In the migration yaml definition, point destination at this instead of entity:node:

destination:
  plugin: myplugin
  bundle: working_paper

The $entityType member and create method seemed to be required as well, otherwise Migrate did not seem to know how to parse this into a node of a particular type, despite extending from EntityContentBase.

The reason for wanting to do this is that its cumbersome especially while developing that files are not removed along with their entity on rollback. In my case, I have strictest confidence in that the rollback of this entity does not affect anything else because this is the only place this file will ever appear.

Is this the best way to add this type of behavior?


Is it possible to include a forward slash in a route dynamic property? Is it possible to include forward slashes in routing parameters?

// routing.yml
mymodule.route
    path: '/mymodule/{param}'
    defaults:
        path: ''
    requirements
        path: '[A-Za-z0-9\-\/]+'

/mymodule/this/is/a/single/param would then result in

$param = 'this/is/a/single/param';

being passed into the controller method.

I tested this out, and it doesn't work in Drupal 8, unfortunately.

mymodule.test:
  path: '/mymodule/{testparam}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\TestController::build'
    _title: 'Variable Parameter'
  requirements:
    _permission: 'access content'
    testparam: .+

It picks up the route with "/mymodule/hello", but not "/mymodule/hello/world".

There's some more discussion of this here:
Slashes in single route parameter or other ways to handle a menu tail with dynamic number of params

It looks like there's a solution, but it's pretty heavy handed.


Reverse Translation Function? As you know t() function in Drupal is translation function.

t('base value') returns translated expression for current language.

I want to know, is there any function in Drupal that takes translated expression as a parameter and returns base value ?

$translated = t('base');
$base_value = reverse_translation ($translated)

I am searching for reverse_translation function

according to t() documentation you can get translate the string it in any langcode,it is mean you can have reverse translation

my suggestion is

t($string,  array(), array('langcode'=>'en'));

and as example
stack dont let me use persian character(I write in Fenglish but you read it persian :) )

t('Chetori mehrdad',  array(), array('langcode'=>'en'));

return equal of string ('Chetori mehrdad') in english  if you translate it before form English to persian (How are you mehrdad), this mean 'Chetori mehrdad`(persian) => 'How are you Mehrdad'(english) :)

I hope this is useful at this time ,sometimes the answers is after you need :(


How do I enable clean URLs with Nginx? I'm using Drupal 7.x. I have achieved to make it work without clean URLs.

Investigating, I have understood that I should create a vhost for each drupal site and enable clean URLs with the following code.

if (-e $ REQUEST_FILENAME) {
     rewrite ^ / (. *) $ / index.php? q = $ 1 last;
}

Alternatively, I could use this code.

location / {
         [... ]
         error_page 404 = @ drupal;
         [... ]
}

location @ drupal {
         rewrite ^ (. *) $ / index.php? q = $ 1 last;
}

However, I've also seen that without creating a vhost can enable clean URLs (like Apache).
I tried on both lines in my setup but I do not get a result.
When I enable clean URLs it always displays the word Nginx (The localhost).

What is the right way to enable clean URLs?

This is my configuration in /etc/nginx/sites-available/default.

server {
        listen   80; ## listen for ipv4; this line is default and implied
        listen   [::]:80 default ipv6only=on; ## listen for ipv6

        root /usr/share/nginx/www;
        index index.php index.html index.htm;

        # Make site accessible from http://localhost/
        server_name localhost;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to index.html
                try_files $uri $uri/ /index.html;
                # Uncomment to enable naxsi on this location
                # include /etc/nginx/naxsi.rules
        }

        location /doc/ {
                alias /usr/share/doc/;
                autoindex on;
                allow 127.0.0.1;
                deny all;
        }

        location /images {
                root /usr/share;
                autoindex off;
        }
        # Only for nginx-naxsi : process denied requests
        #location /RequestDenied {
                # For example, return an error code
                #return 418;
        #}

        #error_page 404 /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
                root /usr/share/nginx/www;
        }

        #Pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
                try_files $uri =404;
                #fastcgi_split_path_info ^(.+\.php)(/.+)$;
        # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

                # With php5-cgi alone:
                #fastcgi_pass 127.0.0.1:9000;
                # With php5-fpm:
                fastcgi_pass unix:/tmp/php5-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        location ~ /\.ht {
                deny all;
        }
}

I have not created any vhost on my server; neither do I know how.

I have next that work successfully:

  location / {
    index index.php;
    # This is cool because no php is touched for static content
    try_files $uri $uri/ @rewrite;
    expires max;
  }

  location @rewrite {
    # Some modules enforce no slash (/) at the end of the URL
    # Else this rewrite block wouldn&#39;t be needed (GlobalRedirect)
    rewrite ^/(.*)$ /index.php?q=$1;
  }

  location ~ \.php$ {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name;
    fastcgi_intercept_errors on;
    fastcgi_pass unix:/var/run/php-fpm.sock; # fastcgi_pass unix:/tmp/php5-fpm.sock;
 }


How to add view to view mode? We have a view, custom_view, that was created to be displayed on a page that is of the basic page content type. The basic page content type is using the Default View mode and has a taxonomy term, custom_tag.

Initially we thought about adding the block to the theme block layout, but that does not provide what we need. The custom_view should only be visible on the basic page content type for the Default View and not others.

How do you add Views to a View Mode?

The view has a contextual filter so it takes in the current language and it takes in the value of the custom_tag since it is present on the basic page content type.

How do you add Views to a View Mode?
If you want to add a view to a content type's view mode there is a few ways to do this and depending on your exact requirement one might be better than the others
views field formatter
Use https://www.drupal.org/project/views_field_formatter will allow you to choose a formatter for a field and it will pass automatically the value of the field to the view
viewfield
https://www.drupal.org/project/viewfield will allow you to add a field and to choose what views can be chosen and allows you to also include an argument on the node edit form
EVA: Entity Views Attachment
https://www.drupal.org/project/eva will allow you to create a specific EVA views display and configure it to appear for specific bundles (content types).  After saving the view it will appear as a field in the display mode of that content types so it can be positioned appropriatelly
All the above module can take advantage of arguments and contextual filters so you can do very complex things with them


Can't send managed file as mail attachment I'm working on a form submit in a Drupal 7 project, the form has and upload file field, in my form submit handler I can get the file id, what I want to do is to send and mail which has as attachment the uploaded file.

my form submit function:

function my_form_submit($form, &$form_state) {
  $fid = $form_state['values']['document'];
  $file = file_load($fid);
  $params = array(
    'attachment' => $file,
  );
  global $language;
    drupal_mail('my_module', 'key_1', 'my_own_mail@gmail.com', $language, $params);

}

hook_mail implementation:

function my_module_mail($key, &$message, $params){
  switch ($key) {
    case 'key_1':
      $message['subject'] = t('my mail subject');
      $message['body'][] = t('Hello this is a test content');
      $message['params']['attachments'][] = $params['attachment'];
  }
}

When submitting the form the mail has not been sent and this error is shown:

Error : Cannot use object of type stdClass as array in my_module_mail()

Anybody has an idea why it doesn't accept object and or how to deal with this in this case.
Thanks.

file_load return file object:

  Loads a single file object from the database.

But $message['params']['attachments'][] should be an array.
So just change $file = file_load($fid); to $file = (array)file_load($fid); in your submit function my_form_submit will be like:

function my_form_submit($form, &$form_state) {
  $fid = $form_state['values']['document'];
  //file object as an array.
  $file = (array)file_load($fid);
  $params = array(
    'attachment' => $file,
  );
  global $language;
    drupal_mail('my_module', 'key_1', 'my_own_mail@gmail.com', $language, $params);

}

Update:

to send attachement you need just the filePath try with:

$params = array(
    'attachments' => array(
      0 => array(
        'filepath' => $file->uri,
      ),
    ),
  );


How do I interact with $title, $breadcrumbs, and $action_links within a process or preprocess function? I'm using a Bootstrap subtheme, with a custom page.tpl.php override.  Within the template file, I see there are variables for $title, $breadcrumbs, and $action_links.

If I wanted to access these inside of a preprocess or process function, let's say to modify the title based on whether or not there is content in a given region, how would I do that?

They don't seem to be passed along in $variables like the rest of the page content.  $variables['title'] is not present.  Would I use API functions such as drupal_set_title()?

This is how I manipulate breadcrumbs in page preprocess function. You can actually do this somewhere else, where you think it fits according to your needs.

/**
 * Implements hook_preprocess_page().
 */
function extremes_preprocess_page(&$variables) {
  // You can use preprocess hooks to modify the variables before they are passed
  // to the theme function or template file.

  //define breadcrumbs array
  $breadcrumb = array();
  $breadcrumb[] = l('SS','<front>');//add homepage first
  //if we are on one of my dynamic pages, we do this
  if (arg(0) == 'node' && is_numeric(arg(1)) && !empty($variables['node']) && _is_dynamic_type($variables['node']->type)) {
    if (!empty($variables['node']->field_term_reference)) {//we are gonna depend on a term ref field
      //get all parent terms
      $parents = array_reverse(taxonomy_get_parents_all($variables['node']->field_term_reference[LANGUAGE_NONE][0]['target_id']));
      //and add them to breadcrumb array
      foreach ($parents as $parent) {
        $breadcrumb[] = l($parent->name, 'taxonomy/term/' . $parent->tid);
      }
    }
    //set the breadcrumb
    drupal_set_breadcrumb($breadcrumb);
  }
  //if we are on a term listing page
  else if (arg(0) == 'taxonomy' && is_numeric(arg(2))) {//you can also check here, which vocabulary you want
    //easier this time
    $parents = array_reverse(taxonomy_get_parents_all(arg(2)));
    foreach ($parents as $parent) {
      $breadcrumb[] = l($parent->name, 'taxonomy/term/' . $parent->tid);
    }
    if (arg(3) && $type = taxonomy_term_machine_name_load(arg(3), 'vocab_name')) {
      $breadcrumb[] = l($type->name, request_path());
    }
    drupal_set_breadcrumb($breadcrumb);
  }

}

This sample uses taxonomy_machine_name.module which uses the same system with pathauto and is very useful for loading taxonomy terms from url if you set up correctly.

For title, you can go with drupal_set_title() and for action links hook_menu_local_tasks_alter().


Display blocks on taxonomy and content type pages I have a taxonomy menu block. I need to show this block on some taxonomy term pages for a particular vocabulary and on some content type node pages in second sidebar region (bartik theme).

How can we achieve this? Is there any module available? Or can we do it programmatically using a custom module or in the theme's template.php file?

I think Pathauto module could be your friend here. This module allows to define automatic url patterns for different entities, notably vocabularies, using tokens (Token module needed).
By default, you will have [term:vocabulary]/[term:name] for any taxonomy term page. Then you just have to configure your taxonomy menu block : Pages > Show block on specific pages : your-vocabulary/* (of course replace "your-vocabulary" by the name of the vocabulary you created).
The process is the same for any content type page.

Example:
Vocabulary : Fruits
Terms : Apple, Orange, Strawberry
The Apple page url would be : your-site/fruits/apple
You configure your block with : Show block on specific pages : fruits/*
And then your block will only appear on taxonomy term pages related to the vocabulary Fruits.


Multisite: Other link color (css) When using the same theme on multisites, what would be the easiest sollution to give each domain another link color?

I would suggest you try Domain CSS module if you are already using Domain Access module. ( https://drupal.org/project/domain_css )

This will give you ability to add additional css per domain so you can keep everything clean and organized.

Another alternative is to write a custom module and get $_SERVER['HTTP_HOST']; which you can run into switch statment to load css.

Similar question: Load domain-specific CSS file on a multisite


Drush Segmentation fault when upgrading from Drupal 6 to Drupal 7 I am running drush -vd updb --yes || exit 1 to upgrade D6 to D7 then I got this error several times atleast.

Bootstrap to phase 0. [0.01 sec, 4.79 MB]                            [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drush() [0.01 sec, 5.08 MB] [bootstrap]
Cache HIT cid: 5.0-commandfiles-0-eae08ebb5299072299ae95f485024c57 [0.02 sec, 5.09 MB]                                                                                [debug]
Bootstrap to phase 0. [0.06 sec, 11.02 MB]                                                                                [bootstrap]
Bootstrap to phase 2. [0.08 sec, 11.03 MB]                                                                                [bootstrap]
Drush bootstrap phase : _drush_bootstrap_drupal_root() [0.09 sec, 11.03 MB]                                                                                [bootstrap]
Initialized Drupal 7.14 root directory at /var/www/vhosts/git/html [0.12 sec, 15.06 MB]                                                                                [notice]
Drush bootstrap phase : _drush_bootstrap_drupal_site() [0.12 sec, 15.07 MB]                                                                                [bootstrap]
Initialized Drupal site default at sites/default [0.12 sec, 15.07 MB]                                                                                [notice]
Cache MISS cid: 5.0-commandfiles-2-d0694fde84f442a7d33c2119cff575f2 [0.13 sec, 15.07 MB]                                                                                [debug]
Cache SET cid: 5.0-commandfiles-2-d0694fde84f442a7d33c2119cff575f2 [0.27 sec, 15.09 MB]                                                                                [debug]
Found command: updatedb (commandfile=core) [0.28 sec, 16.05 MB]                                                                                [bootstrap]
Segmentation fault

Any idea what is segmentation fault is?

Drupal is very sensitive to the order you do things when doing a major system upgrade.  You must follow the instructions in UPGRADE.txt exactly; in particular, if you run updatedb just once, after upgrading your core and all of your contrib code, then the upgrade is sure to go wrong.  The symptoms can vary; I would expect that this is probably what is causing your segmentation fault.

If you look at the UPGRADE.txt instructions closely, you will see that you need to run updatedb on core only, with no contrib modules enabled; after that, you must upgrade your contrib modules one at a time, upgrading their code and then running updatedb for each one.  If a module that has a schema in the database has update hooks that need to run, then updatedb will run them, even if the module is not enabled, so you must be extremely exacting in your code management, or the upgrade will fail.  It is also critical that you upgrade your modules in the right order, because a module will clearly need to have its dependencies available in order to successfully complete its updatedb processes.  If you have a lot of modules, this process can be extremely tedious.

The Drush Site Upgrade command can be used to automate this process to a large degree.  There are still some things that you need to do manually, but it will walk you through the UPGRADE.txt instructions one step at a time, offering to do most of the steps for you automatically.  It will even give you advice about replacement modules for some contrib projects not available in D7, and will run the content migrate code to insure that you CCK content gets upgraded too.

If you go through all of the steps faithfully, and you are still getting a segmentation fault, it could be that your system is running out of memory.  Adjust your settings in php.ini to adjust.  If this still doesn't work, you could be encountering a bug in a contrib module.  When this happens, you can try asking for support in the issue queue of the particular module that is causing you problems.  If this does not get you anywhere, your final resort is to build a new Drupal 7 site from scratch using similar modules, and migrate your data using Drupal to Drupal migration.  In the futue, Drush Site Upgrade will also support the d2d upgrade path, but for now you'll need to do it manually.

Postscript: Understanding what a segmentation fault is is not really important to solving your problem, but there is a good definition on Wikipedia here: http://en.wikipedia.org/wiki/Segmentation_fault.


Get information about a menu item In Drupal 8, you can use system blocks to show menus starting from different levels. For example:

Menu item 1 (level1)
--- Menu Item 2 (level2)
--- Menu Item 3 (level2)

Menu item 4 (level1)
--- Menu Item 5 (level2)
--- Menu Item 6 (level2)

When user is on a page linked by menu item 2 I want to have a block showing the following:

Menu item 1
    --- Menu Item 2
    --- Menu Item 3

What the main system block offers is the following result:

    --- Menu Item 2
    --- Menu Item 3

You see? I need the parent menu item of these menu items as well.

What I did so far is to define a custom block in my module:

class MainMenuBlockSecondLevel extends BlockBase {

  public function build() {
    $menu_name = 'main';
    $menu_tree = \Drupal::menuTree();
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $parameters->setMinDepth(2);

    $tree = $menu_tree->load($menu_name, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $tree = $menu_tree->transform($tree, $manipulators);

    $parents = $parameters->expandedParents;  // menu_link_content:dd7b39a6-c4c8-48dd-a1cf-92a755087c29

    $build['parent']['#markup'] = '
Parent
';
    $build['menu'] = $menu_tree->build($tree);
    return $build;
  }
}

With the $parents variable I get an array like that:

Array
(
    [0] =>
    [1] => menu_link_content:dd7b39a6-c4c8-48dd-a1cf-92a755087c29
)

Here it stops for me now. What is menu_link_content:dd7b39a6-c4c8-48dd-a1cf-92a755087c29 and how can I get the needed information like menu item title and path out of it?

MenuTreeParameters::$expandedParents are a list of menu tree ids (a composite key of the menu bundle and the menu content UUID). You can see its data in the menu_tree, menu_link_content, menu_link_content_data, database tables.

If you need to programmatically invoke the menu item for reference, you can load it via Drupal's entity manager:

// Load each menu content item per UUID
foreach ($parents as $menu_uuid) {
  $menu_content = current(\Drupal::entityManager()->getStorage('menu_link_content')->loadByProperties(array('uuid' => $menu_uuid)));
  // @TODO: Reference menu content properties for data
  // (e.g. $menu_content->get('title')->value / $menu_content->get('link')
}


How to remove the global library from specific page?? How to remove the global library from specific page ?

I want to rearrange java script files.

You need to implement hook_page_attachments_alter().


How to show only child terms of a taxonomy on a table I want to display only child terms of a taxonomy on a tableselect ?
Example :

Term A has : terms {B,C,D}
term E has : term {F}

I want to display only {B,C,D,F} on a table (in order to make some stuff with checkbox etc)

Solved by joining two tables : taxonomy_term_data and taxonomy_term_hierarchy, the second one contains the field : parent ( 0 for parents, tid of the parent if it's a child term)


Perform Row Functions in a View Trying to get a calculation at the end of an Aggregated Table or even Pivot Table in Views, but as it seems to be a bit of a two step process, I can't figure it out for the life of me...

I have the following table of user skills, pulled together using aggregation (for a number of reasons the way the data has to be gathered). I can also use a pivot to the same result.

I want to then be able to evaluate overall skill of each user by counting the Lows, Mediums and Highs for each user, multiplying them by 1, 2 and 3 respectively, and then add them together to a Total Skill value, per below:

Any ideas on how to do this, or an appropriate module that would give me this result?

Why don't you use THEME_preprocess_views_view_fields(&$var) function? In this function you may get every field of the view, and do any processing you want just before loading the view. just install devel module, and use kpr to see what variables are available.


How to apply drupal_add_css by block_id in Drupal? I am trying to apply css by block_id or block title.

if($template_name=="BOhhjI" && $block_name=="block1" ){
  drupal_add_css(drupal_get_path('module', 'MyModule') . '/css/grid.css', array('group' => CSS_DEFAULT, 'every_page' => FALSE));
 }
  else if($template_name=="calender" && $block_name =="block2"){
  drupal_add_css(drupal_get_path('module', 'MyModule') . '/css/carousal.css', array('group' => CSS_DEFAULT, 'every_page' => FALSE));
 }
 else{
  drupal_add_css(drupal_get_path('module', 'MyModule') . '/css/MyModule.css', array('group' => CSS_DEFAULT, 'every_page' => FALSE));
 }

But, drupal_add_css apply css to whole page. I have a single template and multiple css.I need to switch css on a given condition. Any way to achieve this?

Edited: Following solution from comments

function Module_Name_block_view($delta = '') {
    $blocks = array();
    $query = db_select('Table Name', 'n')
            ->fields('n')
            ->execute();
    $block_data = $query->fetchAll();
  foreach ($block_data as $block_query) {
  $macname = $block_query->title;
  if($block_query->options == 'BOI'&& $delta == $macname){

    $blocks['subject'] = t($block_query->title);
    $blocks['content'] => array
      (
        '#markup' => block_content($block_query->selected_type_list),
        '#attached' => array
        (
          'css' => array('/css/grid.css'),
        ),
      );
}
  }
  return $blocks;

}

You can try this code. Paste this code in file template.php

function YOURTHEME_preprocess_block(&$vars) {
  // use dpm($vars) to see struct of variable $vars
  $delta = $vars['block']->delta;
  switch ($delta) {
    case 'abc':
      //add css here
      break;
  }
}

Block ID are

string 'block'
$variables['block']->module
$variables['block']->delta

You can check block delta to use drupal_add_css()


How to increase weight range avaliable when using Tabledrag? I have a tabledrag with more than 20 entries. Much more. Default weight range is from -10 to +10, so it can only order first 20 entries. Every additional one have weight of 10 and is ordered by secondary means like ID, name or whatever, and not the way user set it to. How can I expand that range? I can't see anything like that in drupal_add_tabledrag documentation.

My form definition is pretty much copy-paste from Examples for Developers.

If you are using a field of type "weight" like in the examples module you need to use the #delta attribute.


How to avoid script being injected into costum blocks? I have a custom block in which I put iframe and javascript ads. I noticed that recently they are being exploited so that attackers add some script to them (i.e on custom block table). I use Full html on the blocks to be able to insert iframe and script code of the ads. All these made me feel very insecure about Drupal so I appreciate your solution to secure my site.

So if your admin account had it's password changed, I would be willing to bet the hackers gained access to your admin account somehow.

Might want to think about beefing up your passwords, for both your admin account and the box.

You definitely should make sure your Drupal install is up to date. If "Drupal Core update status" isn't "up to date" at /admin/reports/status you should look to update core. If there is ever a security vulnerability found in core, it's normally fixed very quickly and rolled out in a new version, so you should keep your core up to date.

As for ways to make your blocks more secure, one thing you might want to try is to actually move the block from being controlled by the admin to being controlled by code.

You can write a little custom module that will create blocks. You'll want to be familiar with hook_block_info and hook_block_view. Another upside to moving blocks into code is that it will increase their portability.

Also, as another general security note, you might want to take a look at Security Review, which will help point out any security flaws you might have on your site.


Why did all my themes disappear when I upgraded to PHP 7? Today I had to do some support on a Drupal 6 website and when I tried to refresh a CSS file, all the themes disappeared. When going to the theme page, nothing in the list at all. Not even the core themes.

This is a Drupal 6.x website and I am running it on my current development system which runs PHP 7.x among other things.

Why would my theme disappear like that?

Note: I tried clearly all the cache tables and click on the "Clear all Caches" and the caching is turned off in the Performance screen (so that way I know it's not that creating problems.)

I don't know specifically why your themes disappeared, but the requirements page for Drupal (https://www.drupal.org/docs/7/system-requirements/overview) states:

  Drupal 6: PHP 5.x only (5.2.5 or higher recommended). Warning: support
  for PHP 4.x has been dropped. Drupal core should work with PHP 5.3.x,
  but PHP 5.3.x and higher may produce errors or unexpected behavior
  especially for contributed modules and themes.

PHP 7 is definitely not supported. You will likely find many more errors than this over time.


Request body to post a new comment using REST API I have a comment type and content type with field from type of that comment type.
I also using Rest and Rest UI modules. I want to insert new comment on specific node using rest API using POST request.

In the REST config page, I have this service enabled

What I want to do, what is the request body should be to insert new comment successfully through Postman.

I've solved it by these below

{
    "entity_id": [{
        "target_id": 612
    }],
    "entity_type": [{
        "value": "node"
    }],
    "comment_type": [{
        "target_id": "discussion"
    }],
    "field_name": [{
        "value": "discussion_comments"
    }],
    "subject": [{
        "value": "Goodbye World"
    }],
    "comment_body": [{
        "value": "comment which you want write"
    }]
}


Set default value with PHP on a node field. I'm using Drupal 7 and have created a content type called abc. In abc there is a field called seller. When a logged in user creates a new piece of abc content, the value of the seller field would be the name of the person who is logged in.

So what I want is a default value for the seller field for a small piece of PHP code. But I am not able to find the place to enter this PHP. In Drupal 6 there is text area for the php code to enter, how can this be done with Drupal 7.

I don't know if there is an UI for it, but fields allows either an array as allowed values or an callback.

This means that you most likely will need to create a function in a module instead of hardcoding the php which then would be saved in the database. IMO this is a good thing.

In your field config array you want something like this:

....
'settings' => array(
    'allowed_values' => array(),
    'allowed_values_function' => 'callback_function',
),
...

If you are new to this, take a look at field_create_field and field_update_field.


Display User Relationship request dialog on content profile page I need to create an 'add friend' link programatically.

       $content .= '
' . l('Add to your friends', 'relationship/' . $tid . '/request/1?destination=user/' . $tid, array('html' => true, 'attributes' => array('class' => 'add`-friend')));

It leads me to another page with confirmation form for the invitation.

Could anybody tell me how (if possible) I can display this confirmation form in dialog?

I've created Add as friend likes in a project once doing this:

l(t('Add as friend'), 'relationship/' . $account->uid . '/request');

It served me fine, but I'm not sure if you want something different.


Split a date field output into two spans I have a Date field on a content type. I'm trying to render it so that just the Month and Day are visible, but I need each in a separate .

I think the most appropriate place to do this is in the preprocess function for the node theme function. Within that function, here's the date field on the node object:

What is the appropriate way to convert this to something I can run a custom date formatter on, so I can get the month and the day separately?

This is my current approach:

$date_field = $node->field_event_date_time[$node->language][0];
$date_object = new DateObject($date_field['value'], new DateTimeZone($date_field['timezone_db']));

$variables['event_month'] = date_format_date($date_object, 'custom', 'M');
$variables['event_day'] = date_format_date($date_object, 'custom', 'j');

But it does seem a bit messy, and I've noticed is that the field won't always have the language array key, so that complicates it a bit further.

If your current approach works, consider sticking with it.  Use field_get_items() to get past the "field won't always have the language" problem.

To answer the original question, at admin/config/regional/date-time you'll find a tab to create a new format.  You can somewhat laboriously create a format based on something like:

<\s\p\a\n \c\l\a\s\s="\f\o\o">l F j</\s\p\a\n> - <\s\p\a\n \c\l\a\s\s="\b\a\r">g:i a</\s\p\a\n>

All the backslashes may not be necessary, but you have to backslash escape any character that is a special date code.

Then edit a type or make a new one that uses your format with the markup built in.


Add a meta content="noindex,nofollow" tag on a node created programmatically Is it possible to add a meta content="noindex,nofollow" tag to the head on the page of a node created programmatically (and onl this node)? I have created the node like this:

function MODULENAME_install() {
  $bodytext = 'Some Text';

  $node = new stdClass();
  $node->type = "page";
  $node->title = "New title";
  $node->language = LANGUAGE_NONE;
  node_object_prepare($node);
  $node->body[$node->language][0]['value'] = $bodytext;
  $node->body[$node->language][0]['summary'] = '';
  $node->body[$node->language][0]['format'] = 'full_html';
  $node->path = array('alias' => 'new-title');
  node_save($node);
}

You can use below code for adding no-follow and no-index meta for the node. Put this code in your themes template.php file.

function MYTHEME_html_head_alter(&$head_elements) {
  if (arg(0) == 'node' && arg(1) == 'YOUR NODE NID' && !arg(2)) {
    $head_elements['MYMODULE_meta_robots'] = array(
      '#tag' => 'meta',
      '#type' => 'html_tag',
      '#attributes' => array(
        'name' => 'robots',
        'content' => 'noindex'
      )
    );
  }
}


How can I schedule change of the default front page? I have a node being displayed on the front page, set at admin/config/system/site-information > Frontpage.

I need to change it to another node on specific date.

It would be ideal if I could do that using views display of /frontpage + Promote node to frontpage. But i have a referenced by nid view inserted into the nodes of this content type (using Views Field) which does not show anymore if I use this method.

Thanks

I would add a date field to the node and then filter the view to only show the node scheduled for today. Point your front page to that view.

You'll need the date module.


Handling custom parsing and importing with Feeds I've been wading through the Feeds module and documentation, and for whatever reason have been unable to figure the best way to do this, so I'm hoping someone will be able to point me in the right direction.

I need to get video node information from one D6 site to another.  I've set up a feed via Views on the source site, and I want to use Feeds to ingest the info into the target site. There are two custom things I need to do, and I can't figure the best way to do them.

There are two taxonomy vocabularies on the source site that I need to get to specific vocabularies on the target site. One is a tags vocabulary, and one is titled Channel (same on both sites). I've added the tid for the target Channel term to the feed as <channel-map> and I need to import that value into the assigned Channel term on the target node. The problem is that the core Taxonomy module dumps all taxonomy terms, regardless of vocabulary, into the source feed as <category>; the only way to differentiate between vocabs when importing the feed item is to look at the domain attribute, which is the URL for that term. There is a Tags target in the standard feed importer, but I need to filter out the Channel terms, as well as the terms for other vocabs that only exist on the source site.
The target site has a custom video formatter that plays the embedded video from the source site when you enter the source site URL into the Video field on the target node in the format http://mysourcesite.com/node/$nid. I've added the source nid to the feed as <source-nid>, so I just need to take that value and construct the URL the source site URL is already stored in a variable on the target site as part of the custom formatter settings), and then insert it into the Video field on the new target node.

So what I'm trying to figure out is the best way to handle these instances when importing the feed.  It looks like one option is to write a custom parser and/or importer plugin.  However, I don't need to rewrite the whole parsing and importing processes; I just need to handle the two cases above. There are already targets defined for the two fields I need to import into, so would it just be a matter of using the feeds_node_processor_targets_alter() hook and override the existing node processor? Or would I need to write my own custom plugins?

Thanks.

EDIT: I tried creating my own callback as a wrapper for content_taxonomy_feeds_set_target() using hook_feeds_node_processor_targets_alter(), but by that point in the process, all that is provided is the term name with no additional information to indicate the source vocabulary.

I finally got everything to work with some code voodoo and changing parsers. One thing that I didn't add to the original question above as an edit was the fact that using the common syndication parser, my custom items that I added to the source feed were never available. I then switched to using the SimplePie parser, and was able to extend that functionality to do what I need.

According to the Feeds module documentation for developers and this blog post, you can do some custom parsing by overriding the parseExtensions() method of FeedsSimplePieParser class. First, you have to declare the class with hook_feeds_plugins():

/**
 * Implementation of hook_feeds_plugins().
 */
function mymodule_feeds_plugins() {
  $info = array();

  $info['MyModuleFeedsParser'] = array(
    'name' => 'Custom Parser',
    'description' => 'Custom parser for my video import.',
    'handler' => array(
      'parent' => 'FeedsSimplePieParser',
      'class' => 'MyModuleFeedsParser',
      'file' => 'MyModuleFeedsParser.inc',
      'path' => drupal_get_path('module', 'mymodule') . '/plugins/feeds/',
    ),
  );
  return $info;
}

You also want to implement hook_enable to clear caches.

/**
 * Implementation of hook_enable.
 */
function mymodule_enable() {
  //clear the cache to display in Feeds as available plugin.
  cache_clear_all('plugins:feeds:plugins', 'cache');
}

Next you create the class.

/**
 * Custom Feeds parser class used to parse custom info from source site video feed.
 */

class MyModuleFeedsParser extends FeedsSimplePieParser {
  /**
   * Add the extra mapping sources provided by this parser.
   */
  public function getMappingSources() {
    return parent::getMappingSources() + array(
      'source-nid' => array(
        'name' => t('Video NID - SimplePie'),
        'description' => t('.'),
      ),
      'channel-map' => array(
        'name' => t('Channel Map - SimplePie'),
        'description' => t('Target Channel tid - SimplePie.'),
      ),
    );
  }

  /**
   * Parse the extra mapping sources provided by this parser.
   */
  protected function parseExtensions(&$item, $simplepie_item) {
    if ($value = $simplepie_item->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'source-nid')) {
      $item['source-nid'] = $value[0]['data'];
    }
    if ($value = $simplepie_item->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'channel-map')) {
      $item['channel-map'] = $value[0]['data'];
    }
    // Filter out non-Tags terms.
    $categories = $simplepie_item->get_categories();
    // Cycle through the categories and delete any items
    // in feed item that aren't tags. The array id values
    // are synchronized between $categories and $item['tags'].
    foreach($categories as $id => $category) {
      if (!strstr($category->scheme, '/tag/')) {
        unset($item['tags'][$id]);
      }
    }
  }
}

This code does a few things:

getMappingSources() creates a couple sources that are available for mapping. You set these in your importer settings for your processor.
Gets the source-nid value from the feed source and add it to the item.
Gets the channel-map value from the feed source and add it to the item.
Filters out the non-tags terms from the categories (aka taxonomy terms). The scheme value is the URL to the taxonomy term (e.g. mysite.com/tag/tag-term), so I use that to identify non-tag terms and unset them.

Finally, I have to create the values for the video field and the Channel vocabulary. This is done with some custom callbacks defined in hook_feeds_node_processor_targets_alter().

/**
 * Implements hook_feeds_node_processor_targets_alter().
 */
function mymodule_feeds_node_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
  $targets['field_source_url'] = array(
    'name' => 'Source Video URL',
    'description' => 'The URL of the source video',
    'callback' => 'mymodule_feeds_set_source_url',
  );

  $targets['channel'] = array(
    'name' => 'Target Channel',
    'description' => 'The target video channel',
    'callback' => 'mymodule_feeds_set_channel_target',
  );
}

And the callbacks themselves:

/**
 * Custom callback to set the video source URL in field_video.
 *
 * @param $node - The node object being built.
 * @param $target - The target field.
 * @param $value - The field value from the feed.
 */
function mymodule_feeds_set_source_url(&$node, $target, $value) {
  $source_url = variable_get('emvideo_source_domain', '') . '/node/' . $value;
  $node->field_video[0]['embed'] = $source_url;
}

/**
 * Custom callback to set the target vocabulary term.
 *
 * @param $node - The node object being built.
 * @param $target - The target field.
 * @param $value - The field value from the feed.
 */
function mymodule_feeds_set_channel_target(&$node, $target, $value) {
  $term = taxonomy_get_term($value);
  $node->taxonomy[(int)$value] = $term;
}

You then define these as targets in your Processor mapping (to coincide with the Source values above), and you're good to go.


Pass node field data into Views block I'm bad with words, so hopefully I can get this across clearly. I'm using Views and the dRealty module. I've tried using relationships, and it's a no go.

I made a Views block of an "Agent" content type that has an agent_id (field_agent_id) text field. The dRealty module creates listings by pulling data from a RETS server, and the agent id (field_listing_agent_id) comes through as a text field. I need to show the data of the agent with the id that matches the listing on the node. How can I pass the field from the node into the Views block?

I'm using Views PHP to filter and I'm referencing How to Filter view by comparing 2 fields, but no luck.

The way I've typically seen that type of thing done is using Contextual filters (formerly called "Arguments" in Drupal 6). The Drupal 7 Advanced Views Tip: Contextual Filters screencast or this tutorial on Using Views Contextual Filters should provide a starting point for using them. In short, contextual filters are like regular filters, except that they allow arguments to be passed in dynamically rather than the filter criteria having to be statically set ahead of time.


Why nodes aren't always deleted on cron? I have this code in my module_cron function (I need to delete old unpublished nodes).

include_once './modules/node/node.module';
$nids = db_query("SELECT nid FROM node where status = 0 AND UNIX_TIMESTAMP()-changed>172800 LIMIT 2000");
while ($result = db_fetch_object($nids)) {

  echo  "Deleting node ".$result->nid."<br>";
  node_delete($result->nid);
}

It always outputs node ids, but it rarely actually deletes nodes. In fact it seems to totally stop deleting them until I login to admin panel. What am I doing wrong? Is there any way to always delete nodes?

Check this "Running cron as an authenticated user" in http://drupal.org/node/23714
it might be useful for you.


How can I add a taxonomy-based view to a page? I created a taxonomy with a vocabulary called Series. The Series vocabulary contains a list of terms x, y, z.

I created a content type called Events, which has a field to tag the content with a term from the Series vocabulary.

I created a view to display the events on a page in ascending order beginning from today's date.

The view is set to display certain fields for each piece of Event content. One of the fields displayed is the Series term, which is set to be a link that goes to a page that contains a list of all events tagged with that term.

How can I make that resulting page into a view block that I can drop into a content panel?

Go edit the view that you created and hit add+ next to the view name and then block. By adding a block a new block will appear in the Structure-> Blocks Section and then you can place it anywhere you like.


check box with date module I need a solution for reservation, for example i have a swimming pool and i want to Reserve it, the visitor will choose the time he want, let me say i will select the start and end date (the reservation time) mmmm in our example from 8 am to 9am, what i need to display the available reservation time like this:

And the visitor can select one hour or more to reserve the swimming pool.
Is there a module can do this?and if not is there a reservation module can do what i nees by another way? thanks

As far as i know, there  is no module which will display exact User Interface as check-boxes that will integrate with date module.

What i would like to suggest is to create time field to display from and to time of timing slots using date module.

If you need exact User interface what you are asking then follow below steps.

Add checkboxes field with different timings.
Then create date from and to time fields.
Hide date from and to fields using css.
On click of check-boxes update the hidden date from & to fields using jquery or javascript, so that you can use Date module features.