Allows users to pass from flat to threaded view for forum comments We've migrated a site from Drupal 5 to Drupal 7, and we were unable to figure out how to allow user to change between flat and threaded view for the forum comments. This was possible in Drupal 5, but in Drupal 7 it's only possible to change the default display mode per content type (as an administrator option).

Is there a way to allow this for the users?

Unfortunately, on Drupal 7 that setting is not per user, but per content type. So you need to go to the content type's comment settings and choose either flat or threaded view.


How to get attributes of the form elements? I know that it should be easy, but currently it doesnt work.
In my function I want to get #title of each element in the form. My form is fieldset "add_company". For example, when I try to get #title:

$msg = '';
foreach ($form['values']['add_company'] as $item)
    $msg .= $item['#title'] . ' ';

But I receive nothing.

Second part of question is when i try smth like this:

$value = $form_state['values']['add_company']['offers']['#title'];

I receive "O", but not "Offers".

You can do it like this:

function my_form_validate(OR_SUBMIT)($form, &$form_state)
{
  $msg = '';
  foreach(element_children($form[FIELDSET_NAME]) as $key => $value) {
    $msg .= $form[FIELDSET_NAME][$value]['#title'] . ' ';
  }
}


Sending an email using phpmailer drupal 6 How do I use the phpmailer module. I have it installed and my test email sends. However the php mailer tutorials show examples for using the module outside of Drupal. I want to place some code within a node to quickly fire off an email to myself when x happens.

or is it better to use the durpal mail function, I am using drupal 6, however this is not part of a module but instead will be placed in a node.

You should consider using drupal_mail for sending email from Drupal. That will make sure Drupal can control your mails. For example say, you are using some module like Re-Route Email or maillog.

  $params = array(
    'subject' => t('Client Requests Quote'),
    'body' => t("Body of the email goes here"),
  );

  drupal_mail("samplemail", "samplemail_html_mail", "me@site.com", language_default(), $params, "admin@site.com");

/*setting up our mail format, etc in hook mail*/
function hook_mail($key, &$message, $params)
{
    case 'samplemail_html_mail':
          /*
           * Emails with this key will be HTML emails,
           * we therefore cannot use drupal default headers, but set our own headers
           */
          /*
           * $vars required even if not used to get $language in there since t takes in: t($string, $args = array(), $langcode = NULL) */
          $message['subject'] = t($params['subject'], $var, $language->language);
          /* the email body is here, inside the $message array */
          $body = "

HTML Email with Drupal

              {$params['body']}
              ";
          $message['body'][] = $body;
          $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
          break;
}

You would invoke this in your code somewhere. Or else you can use the rules module to send email as per some events or actions in the site.

If you still want to use PHP Mailer, you have module to do that here.

you can see a screencast on using rules to send email here.


500 error on one page in entire site only showing error "You are here" instead of administration content this error seems to only affect one page in on the website, and nowhere else.
Here is what it looks like:

The watchdog reports do not show the issue, and I believe it to be a permission error or caching error with Apache2, but unsure. I have tried:
clearing cache, searching for a relevant php file with unreadable permissions, and looking over .htaccess files for anything out of the ordinary.
I may have missed a few php files but I am looking for confirmation that I am heading in the right direction.

I will probably end up asking the web platform IT people for help if I can't find an answer, but anything at all will be greatly helpful.
Thank you.

If you have shell access to your server, you could check the actual php error logs on the server- which should indicate the exact culprit.

If you recently updated Drupal core or some contrib modules, you may want to make sure the update process completed successfully.

Also, if you were editing/adding a custom feature module, content types, field collections, paragraph bundles, or other entities referenced by the specific "People" content type, you may have accidentally removed a required field that could cause the page to break- in which case, restoring a backup database could fix the issue.


CKEditor displays entire site page when rich text is switched on The ckeditor is switched off by default. If there is no text present in the field while editing, the cck provides a wysiwyg interface with no text present when rich text is toggled on. However if any text is present and Rich Text editor is switched on then a particular page of the site gets rendered instead of the text. On switching off rich text the rendered page html gets displayed.  Please help.

CKEditor version is latest(7.x-1.13)

The issue was due to a php code used in the donate button of the same page which got rendered in all wysiwyg fields. There was error in the code which disallowed the search to function properly. I was able to identify the issue using elysia cron which displayed errors  when search cron was running. Checking the logs helped me resolve the issue.
Error in one page could cause the CKEditor to display the same page for all wysiwyg fields when switching on rich text is interesting. Thanks.


Convert a Drupal 5 site to Drupal 7 We have a site with the configuration of Drupal 5, and we need to convert content, content types, views, and everything into Drupal 7. We have already tried with the normal conversion process like D5 => D6 => D7, but we are facing many errors; content and views are not imported correctly.

Is there any solution?

From what I've read, going from D5 -> D6 -> D7 can be a pretty involved task.

These two pages suggest you may want to start with a clean install of D7, recreating your content types and  Views, then using Migrate module or a custom script to migrate the content/users. (The migration path from CCK to the Drupal 7 Fields is discussed here: http://drupal.org/node/1144136.)

http://drupal.org/upgrade
http://quicksketch.org/node/5739

I don't know how complex your setup is (how many Views, content types, and modules you have), but it's probably the case you are going to need a fair amount of work to bring your site into Drupal 7.

The related question is https://drupal.stackexchange.com/questions/1420/migration-from-drupal-5-to-7.


How to create inline node-add forms using a block with content type names The following page setup is needed:
A block (at the left, see image) with links to node-add forms, which open inline (the area at the right) in the current page.

The reason why the form needs to appear inline, is that this page is part of a group and the layout of the group and group menu and all must stay the same

I tried to create a Panel page variant for the node add form, but the minipanels that I use in node panels are not available there.

I thought about using an iframe, but that is not recommended generally, especially not for mobile use.

I can't find modules that are specifically suitable for this purpose, but I might have missed some.

What way could I accomplish this setup using javascript/jquery ?

Panels is definitely the way to go here.

Using Page Manager set up a URL with an argument, like mypath/%node-type
Set the argument to be Node add form: content type
In the content area you can rearrange the form how you like or just add the whole node creation form by using the elements under form in the add content screen
Make either a custom pane or a menu of links that point to the various node types:

mypath/article
mypath/event
mypath/document
mypath/video


Placing block inside a node (positioning block between specific elements in node's content) Basically I created a webform and enabled it as a block, now I want to put that block inside a specific node. I can do that by placing it in a 'content' region and defining the specific node BUT it displays at the end of the content. Now how can I move it between specific elements inside the content?

The node is using a page-type....tpl.php which is used by 5 other nodes as well so I cannot change the code.

To visualize it looks like:

[ content ]

-description text-

-list of videos-

[ end of content ]

and I need to put my webform between the text and the video list. Is there a way?

Give the Block reference module a try.

  Defines a field type Block reference which creates a relationship to a
  block and allows the block to be displayed as the content of the
  field.


How can I embed a view in a template when passing view name and parameters are passed as variables? Inside my paragraph template I have variables which contain category id and view machine name. So when I print them like this:

  {{ content.field_category }}
  {{ content.field_view }}

I get correct values.

Then I'm using twig tweak to embed view and if I embed it with hard-coded values, like this:

  {{ drupal_view('view_machine_name', 'embed_1', 33) }}

it also works. I hard-coded the same values my variables display from above.

Now I want to use my field values instead of hard-coded values:

{{ drupal_view(content.field_view, 'embed_1', content.field_category) }}

I get error like:

Warning: array_flip(): Can only flip STRING and INTEGER values! in Drupal\Core\Entity\EntityStorageBase->loadMultiple() (line 266 of core/lib/Drupal/Core/Entity/EntityStorageBase.php). Warning: Illegal offset type in isset or empty in Drupal\Core\Entity\EntityStorageBase->load() (line 251 of core/lib/Drupal/Core/Entity/EntityStorageBase.php).

when I try to replace view parameter and:

InvalidArgumentException: Placeholders must have a trailing [] if they are to be expanded with an array of values. in Drupal\Core\Database\Connection->expandArguments() (line 738 of core/lib/Drupal/Core/Database/Connection.php).

When I try to replace category parameter.

I guess that content.field_category is not an int value and content.field_view is not an string, as this twig filter expects but I have no idea how to convert them to those primitive types?

Tried intval - it's not working

Tried number_format - also not working

I guess I would have to somehow get view machine name and category id directly from those objects but I don't know how to achieve that.

Tried content.field_category.id() and content.field_view.id()

Nothing works.

Try to avoid using {{ content }} this way. The position you have found in the render array in your last comment can change anytime when reconfiguring the paragraph type or when installing/updating code. Render arrays are not APIs and they are only required to have valid renderable child elements at the lowest level, but not a fixed structure.

The Entity API on the other hand, which you would use to access {{ paragraph }} in a paragraph template, does not change, at least not without a transition period while you can still use a deprecated API.

Example:

// field value like string or number
{{ paragraph.field_example.value }}

// target id of a reference field
{{ paragraph.field_reference.target_id }}

See also https://drupal.stackexchange.com/a/263285/47547.


How to make autocomplete return nid and name? My question is about textfield autocomplete. I have this code:

function my_module_menu(){
  $items['my_module/textfield_autocomplete'] = array(
    'page callback' => 'my_module_textfield_autocomplete',
    'file' => '.\my_module\my_module.inc',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access example autocomplete'),
  );
  return $items;
}

In my_module.module:

$form['fieldset7-wrapper']['prop'][$i] = array(
          '#type' => 'textfield',
          '#title' => t('Nombre de propietario'),
          // The autocomplete path is provided in hook_menu in ajax_example.module.
          '#autocomplete_path' => 'my_module/textfield_autocomplete'
        );

In my_module.inc:

function inmoges_ofertas_propietario_autocomplete($string) {
  $matches = array();

  // Some fantasy DB table which holds clientes

  foreach ($return as $row) {
    $value = check_plain($row->name).' '.check_plain($row->surname1).' '.check_plain($row->surname2);
    //$value = $row->name.' '.$row->surname1.' '.$row->surname2;
    $matches[$value] = $value;
  }

  // return for JS
  drupal_json_output($matches);
}

This works perfect. But I want that json return callback {nid; name} instead of {name,name}, and also show the name in textfield, but I can save nid in my form.

If I change to this my function ajax

$matches[$row->nid] = $value;

The previous sentence returns {nid, name}, but if I choose one value of the list name, in the textfield is shown the nid value, not the name value.

Any suggestions?

Take a look at the examples module's ajax_example_autocomplete.inc file. You'll need to add a validation function that looks up the nid from the node->title:

  $result = preg_match('/\[([0-9]+)\]$/', $title, $matches);
  if ($result > 0) {
    // If $result is nonzero, we found a match and can use it as the index into
    // $matches.
    $nid = $matches[$result];
    // Verify that it's a valid nid.
    $node = node_load($nid);
    if (empty($node)) {
      form_error($form['node'], t('Sorry, no node with nid %nid can be found', array('%nid' => $nid)));
      return;
    }
  }
  // BUT: Not everybody will have javascript turned on, or they might hit ESC
  // and not use the autocomplete values offered. In that case, we can attempt
  // to come up with a useful value. This is not absolutely necessary, and we
  // *could* just emit a form_error() as below.
  else {
    $nid = db_select('node')
      ->fields('node', array('nid'))
      ->condition('title', db_like($title) . '%', 'LIKE')
      ->range(0, 1)
      ->execute()
      ->fetchField();
  }


Is there a module to include translatable variables in content? I'm building a bilingual site with a lot of content. We need to be able to edit and translate certain titles that affect many pages at once, like "Today's News" or "Sign up here." But I don't want to make them all fields on content types because there's too many of them.

Is there a module or plugin that allows you to places these variables inside the content? And allows you to edit/translate and show what pages they're on?

Can't you wrap them in t() when fetching them?

Note: The author wants to be able to translate values from the variables table. I suggest a way to translate values from the variables table. No point in using contrib modules if core can do it just fine. That is, unless there are restrictions not mentioned in the original post that would make using the t() function impossible.


Multiple content types in views in order one by one I have 3 content types (A, B, C).

I need to output all of them in views in order:

A1
B1
C1
A2
B2
C2
...

I need to get the last node with content type A, then the last node of content type B, then the last node with content type C, then the node of content type A created earlier etc.

So, is it possible to alternate content types in views?

Thanks a lot!

Yes that is possible. If A is the name of the content type and 1 is the ID of the content. Then you first sort on ID and then on Content Type.


how to get information about discounts on product? Short: I have commerce product and commerce discount that affects this product's price. I want to presents details of this discount to users in shop.

Long story: I use Drupal Commerce with Drupal Commerce Discount which is based on Rules. Discount module is used for configuring promotions on products. Some of promotion (configured discounts) are time-limited ie. they ends on 11.11.2015.
I would like to get information about discounts that affect product when displaying details. First of all I need to display information how much time is left before discount ends.

Is there any way to get information about active rules on product level?

On the line item, you have the field_unit_price field. Inside of that field's data attribute, you'll find information about the discounts that are applied to that product:

array(1) {
  ["components"]=>
  array(2) {
    ...
    [1]=>
    array(3) {
      ["name"]=>
      string(22) "discount|discount_test"
      ["price"]=>
      array(3) {
        ["amount"]=>
        float(-240)
        ["currency_code"]=>
        string(3) "USD"
        ["data"]=>
        array(2) {
          ["discount_name"]=>
          string(13) "discount_test"
          ["discount_component_title"]=>
          string(5) "Test"
        }
      }
      ["included"]=>
      bool(true)
    }
  }
}

Iterate over the components. If there is a discount applied to one of the items, you'll find one with a name that begins with discount|.  Then you can then load that discount and grab more information about it:

$discount = entity_load('commerce_discount', array('discount_test'));

From here, if you've added dates, the date fields will be accessible on the field commerce_discount_date.


How can I use pathauto to generate URLs for deeply nested vocabularies? I am generating breadcrumbs from URL arguments as described here.

I have a vocabulary that looks like this:

Arts-> Performing-> Dancing-> Ballet

I want my url to look like this:
arts/performing/dancing/ballet

Using the pathauto module, I can do this for taxonomy terms:

[term:parent]/[term:name]

Which, on the Ballet page, gives me the following; not what I want:

dancing/ballet

If I use parents instead of parent,
([term:parents]/[term:name]); this is close but not quite:

arts-performing-dancing/ballet

How can I get from arts-performing-dancing to arts/performing/dancing?

Try something like this as your vocabulary pattern:

[term:parent:parent:parent:name]/[term:parent:parent:name]/[term:parent:name]/[term:name]

And your last question should go away.

Just be sure to repeat the parent: part at least as many times as max term depth expected in your vocabulary. Pathauto will smartly skip overhead items.

I know it's not super-scalable, but it works for me.


How can I map multiple fields to one 'parent' field? What I want to do is best illustrated with an example.

Apartments have different price ranges for different units according to how many bedrooms/bathrooms those units have.

How could I set up a content type that will allow me to do something like this:

$500 -- 5br/4ba

$400 -- 4br/3ba

$350 -- 4br/2ba

In the above example each price range has a corresponding 'bedroom' and 'bathroom' value.
In order for this to work I need to map these price ranges to these values. Each apartment entity can have up to 10 of these mapping pairs.

I hope this makes sense. I can't figure out how to set up the content type.

Thanks for your patience and help.

See this example post on Select lists for content types:
How to have CCK "Select list" field on my content type?

you would just make the values for the list option as (value | display text):

500 | $500 - 5br/4ba
400 | $400 - 4br/3ba
350 | $350 - 4br/2ba
... 6 more options of whatever conditions ...
 25 | $25 - you sleep in the closet

This price field could allow up to 10 values if that's your limit.

Since the keys (values) of the prices are integers. You could SUM or Aggregate the values using Views if needed.


How to configure Node Export to mass node export? I'm trying out Node Export for mass node export, but it seems that I have to choose every node to export individually.

What if I want to export all nodes of a selected content type? Is there any way I can do this in Node Export, or I should find another module?

You can do it with drush:

$ drush help ne-export
Export nodes using Node export.

Arguments:
  nids : A list of space-separated node IDs to export.

Options:
  --file : The filename of the output file.  If supplied, the node code will be
exported to that file, otherwise it will export to stdout.
  --format : If supplied, node code will be output using a particular export
format, if available. (e.g. serialize)
  --status : Filter for 'status'; A boolean value (0 or 1) indicating whether
the node is published (visible to non-administrators).
  --promote : Filter for 'promote'; A boolean value (0 or 1) indicating whether
the node should be displayed on the front page.
  --sticky : Filter for 'sticky'; A boolean value (0 or 1) indicating whether
the node should be displayed at the top of lists in which it appears.
  --translate : Filter for 'translate'; A boolean value (0 or 1) indicating
whether the node translation needs to be updated.
  --language : Filter for 'language'; The language code (e.g. de or en-US) of
this node.
  --type : Filter for 'type'; The machine-readable name (e.g. story or page) of
the type of this node.
  --sql : Filter by SQL (EXPERIMENTAL); An SQL query string that returns nids
(e.g. "SELECT nid FROM nodes WHERE nid < 10").
  --code : Filter by PHP code (EXPERIMENTAL); PHP code that prints or returns,
an array or CSV string of nids (e.g. "custom_get_my_nids();"). Don't include PHP
tags.

For example,

drush ne-export --type=article --file=article.txt

will output all of the article nodes to article.txt in serialized format.  You can then use drush to import them:

$ drush help ne-import
Import nodes previously exported with Node export.

Arguments:

Options:
  --uid : User ID of user to save nodes as. If not given will use the user with
an ID of 1. You may specify 0 for the Anonymous user.
  --file : The filename of the input file.  If supplied, the node code will be
imported from that file, otherwise it will import to stdin.

For example:

drush ne-import --uid=1 --file=article.txt

*updated


Get information from a node that has just been saved to update a different node I have 2 different content types "factory" and "measurement" that are related with an entity reference field. I am using a computed field to store the latest measurement as a field of the factory content type. The problem is that in order for the computed field to be "re-computed", the factory node that the measurement refers to, needs to be updated.

My first thought was to batch update all the factory nodes in predefined intervals. This has a very important downside: the factory information (and specifically the latest measurement that I'm interested in) will not be updated until the batch update is executed.

My next thought was that I could use a hook whenever a new measurement is created and update the corresponding (=the one that the entity reference points to) factory. The problem is that hook_node_insert will not give me the information that I want (i.e. the entity reference field that points to the factory) since in the hook's description it states clearly that:

  You should not rely on data in the database at this time as it is not
  updated yet.

Is there any other way to execute a piece of code whenever a new node of specific type (i.e. measurement) is saved/created and have the node's fields available in my code? How do Rules do it?

P.S: I thought about using Rules but it seems like an overkill for such a simple thing to install a pretty heavy module.

In hook_node_insert($node) you cannot reliably read saved node's data from database, but you can read data from $node object provided to that hook.


Province/State list does not update when Country changes when set to "Dropdown" (Location Module) The Location module is exhibiting a weird bug. When setting a location (Country & Province/State), if I use autocomplete for the Province field, it will only suggest provinces in the selected country.

However, when I change it to a Dropdown, the Province/State field does not change, despite the AJAX refresh clearly working (the Province/State field fades in and out, so the AJAX callback is clearly working).

I've used the Webkit Inspector to check the page and there's no JS errors and there is an AJAX callback (however, since I don't have a base reference from a functional site, I'm not sure what data payload I should be expecting to see in the callback).

EDIT: I figured out a solution, but Drupal Answers won't let me answer my own question for another 6 hours. For the sake of anyone else who may be running into the same issue, I've uploaded the code + explanation in a pastie.

EDIT: Nevermind, that didn't entirely work... Will update once I find a working solution.

A friend of mine worked on that issue a while ago, this was the link to the issue. He is now using the Address Field module.
I'm personally using address field as well, the country - province/state selections work well in that module.


How to export nodes as XML? I need to export all polls of a D6 site in XML format so that they can be imported to Django. Node export module states that one can choose to export nodes in xml using drush. However I could not find any docs to describe how to do so. I tried:

drush node-export-export --type=poll --file=xpoll

It exports the polls but in array format. I also could not figure out how to do so using the module's GUI.

So appreciate your help to get the nodes XML, preferably using a drush command.

drush help node-export

You can pass --format to supply the format of the output. Try doing drush node-export-export --type=poll --file=xpoll --format=xml


Seperate admin page for each role I have on my website several roles and each of these roles have different levels of responsibility. How can I create a separate administration page for each role or access level?

There's a number of ways you can accomplish this, here's a few off the top of my head (in no particular order):

Create a normal page node and use Node Privacy by Role, a module which allows you fine-grain access control on a per-node basis using roles.
Use Views to create an admin page and limit the access using Views's "Access Restrictions."
Use Panels to create an admin panel and limit the access using Panel's "Access Restrictions" (very similar to Views).
Use Contexts, create an admin Context and display the content conditionally.

Basically, there is no best or worst way, it all depends on how your current site is set up.  For example if you are already using Panels, it might make sense to go that route, etc.

Personally, I would use a mixture of Contexts and Views!


I'm trying to retrieve a custom content type onto the user profile page I'm using D7.
I have a custom content type that I need to relate to the user. The user will set up and maintain this page themselves.
i.e. Each user has one page of content for this content type.

When a user profile is viewed though I need to show the relevant page that relates to the the user.

What's the best way of doing this in D7?
I'm guessing it's something to do with creating a block view and then using contextual filters. I've managed to get a block view that does this within the preview but I can't get any further than that in terms of linking it to a user profile.

There is the possibility of linking the user name to the content title. In fact if the two were intrinsically linked it would be better. Ideally I would have used the profile 2 module but I'm using location ( doesn't work with users in D7 ) and FiveStar ( doesn't work with users in D7 ).

Any suggestions on where to start looking to solve this would be appreciated.

Have a look at the Profile 2 module. It replaces the Content Profile module from Drupal 6 and the profile module that is build into Drupal Core.


How can add Contact-Us-form in custom place of page.html.twig file? I need to add contact-us form in the custom place of page.html.twig file in my themplate, I want to add some code like belove:

Contact Us

    <form action="#" method="post">
        <input type="text" name="email" placeholder="Email" />
        <textarea name="message" placeholder="Message"></textarea>
        <button>Send</button>
    </form>

You can do this in four steps:

Build a contact form.
Put this contact form in a block with Contact Block.
In block layout put the block in a region -> myregion.
Place the region in page.html.twig -> {{ page.myregion }}


need help with drupal arrays my array for $var gave me the following $var dump

stdClass Object

    (
        [vid] => 71
        [uid] => 1
        [title] => dr1
        [log] =>
        [status] => 1
        [comment] => 1
        [promote] => 1
        [sticky] => 0
        [nid] => 71
        [type] => doc_upload
        [language] => und
        [created] => 1378359025
        [changed] => 1378359025
        [tnid] => 0
        [translate] => 0
        [revision_timestamp] => 1378359025
        [revision_uid] => 1
        [body] => Array
            (
            )

        [field_upload] => Array
            (
                [und] => Array
                    (
                        [0] => Array
                            (
                                [fid] => 59
                                [display] => 1
                                [description] =>
                                [uid] => 1
                                [filename] => drupal-7.23.zip
                                [uri] => public://documents/drupal-7.23.zip
                                [filemime] => application/zip
                                [filesize] => 3646168
                                [status] => 1
                                [timestamp] => 1378359025
                            )

                    )

            )

i need to take the value of [uri]... (indicated above) in a variable. Plz help

$uri = $var->field_upload[und][0][uri];

For object you need to use the notation '->' for tracing the object and $var is the variable which gave you the array .


Protect drupal code injection from url Recently my drupal site is hacked. When i see website log from drupal admin panel someone trying to inject code from url. I searched my website(drupal) directory lots of code in page appended and new files are created.

My question is that

Is this possible to inject code from url
If use how to protect them in drupal

log image

The logged requests are clearly attacking the security vulnerability SA-CORE-2018-002. But this is not your main concern now when you've already been hacked, because most hackers close the vulnerability after they take over your site to not get hacked again by other hackers. You probably need to restore your site from a backup before SA-CORE-2018-002 (but then of course go online only after applying the security updates) or if you have no backup available setup the site from scratch, because it's nearly impossible to clean a hacked site from all malicious code and data.

See Drupal core - Highly critical - Remote Code Execution - SA-CORE-2018-002 and the FAQ.


How to add a flag link to a view that contains only fields with relationships Normally one would add a flag link as field in a view, in order to be able to flag an entity of a views row.

However, I cannot add a flag link to a view that only shows entities using a relationship, since the flag link already uses its own relationship and apparently cannot have another relationship on top of that.

So the question is, how can I add a flag link so that it will flag entities in views rows that use a relationship?

My case:
I have a view based on entities of bundle 'project'. I have added a contextual filter that selects only the currently viewed project entity.
I have added fields of project content that reference the current project, using the entity reference field 'field_project'.
The view shows all content referencing the currently viewed project.
However, the flag that I add to the view does not flag the project content, but the viewed project. Result is that if I press one flag link, all flags appear as flagged in the view.

Quote from your own comment:

  I removed the flag, and re-added it, and suddenly the relationship field is available in the flag. The funny thing is that the flag was already present when I changed the view to only contain related entities, and when I tried to edit the flag relation properties, it did not give a field to add a relationship. Removing and readding the flag did help.

So it seems that "removing and readding the flag" is the solution to answer your question.

Credits: Yuri and Niall Murphy.


extract views $row values i have created a views filtring contents. i want to use custom tpl and get values of $row variable. How can i extract these valuse?

for example:

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

<?php endforeach; ?>

i have tried

<?php print_r($row); ?>

but no solution.

I am facing same problem and get solution as below. Create a tpl as give in Style output under theme information.

$arr_rows = $view->style_plugin->rendered_fields;
<?php foreach($arr_rows as $key=>$arr_row) : ?>
<?php print $arr_row['field1']; ?>
<?php print $arr_row['field2']; ?>
<?php print $arr_row['field3']; ?>
<?php endforeach; ?>


Getting latest node to display as front page I have what seems like a simple question about something it seems like many Drupal users would want to do, yet I cannot seem to find a good answer. I want my latest node (preferably of a single content type) to show as the front page. If I add a node, I want it to automatically become the front page. I don't want the front page to list nodes, etc. I found the "Top Node" module, which offers a view called "Single Node", which seems to do exactly what I want, but it has some problems (notably that it breaks the <front> alias used in setting block displays). There must be some way to do something that seems to be so common without an additional module, right?

I am aware that I could create a view that pulls the content from my latest node and creates a new page for it, but that seems like overkill, since the node already exists. Also, some of my node is being created programatically, and I cannot get those parts of the full node using a view.

How can I do this? Is there no built-in way?

Your best bet is to use Views and attach a PAGE format. Then for display format: "full content". Its not overkill since your page would be cached anyways. But if your really not keen on using views, your best bet is to create a new tpl file for your theme and gear it towards the frontpage via: node--front.tpl.php (not sure if it was like that, but google it) Then return the latest node filtered by content type.


Unable to access Views fields in block Twig template How Drupal 8 uses Twig, how different data is transferred from general template to specific templates?

For view block I have created block template as per default template suggestions. In my new Twig template if I print {{ content }} everything (view result fields) are getting rendered as per Drupal default.

How can I access and apply my theme markup to all view fields in my block template. {{ dump(_context|keys) }} display below.

In block--views-block--page-fields-block-1.html.twig

You can access the view fields like this:

{% for row in content['#view'].result %}

  {{ content['#view'].field['field_name'].value(row) }}
  // change field_name to the actual field machine name.

{% endfor %}

Personally, I rather use views-view-fields--[view-name]--[machine-name].html.twig

In your case should be views-view-fields--page-fields--block-1.html.twig

Here you do not need to do a for loop and you can access the fields easily with:

{{ fields.field_name.content }}
// change field_name to the actual field machine name.


Drupal 7 contexual filter display block based on node reference I have been going around in circles with this for a few hours now... Time to ask for help!!

I have two Content Types:

1: Book

2: Reader

The Book Content Type has a node reference field which is a select list of readers create with the Reader Content Type.

This is all set up and working fine.

Now the issue with my views:

I have a view with is a block containing the Reader fields. What I want to do is have it when the Book node is loaded my block shows underneath with the referenced reader details. Also if no reader is referenced then no block shows up.

I have spent some time in Relationship and Contextual Filters but can't get it to work.

The book URL is formatted like this:

books/[book-title]

I tired using 'raw value from url' in Contextual Filters as setting it to the 2nd argument but that didn't work either.

If anyone can help me out here I would be very much appreciative.

Thanks
C

Create a simple content view of readers add fields and add a contextual filter of field_book or whatever is the name of reference field and choose option "When the filter value is NOT in the URL" -> "Provide default value" -> "Content ID from URL" and save.


How to automatically highlight syntax of code displayed on page? I'm developing a website to publish my codes from different programing languages. I want to highlight syntax of codes with different colors. But, doing it manually is time consuming.
Is there any module or method which could do this automatically? Strictly, it should be done in CSS way.

There are several options to highlight code.

From the modules available on d.o. -- GeSHi Filter and Syntax highlighter

A very recent module (yet to make it to Drupal.org) is Wiredcraft's highlight_js on GitHub. They provide a Drupal 7 only version, but (*shameless plug*) I've ported it to Drupal 6 -- https://github.com/ThinkFabrik/highlight_js/tree/6.x-1.0

Edit: depending on the module you may either have to create a new input filter or use Full HTML to get best results


Views contextually filtered by terms in paragraphs TL;DR, Below are the structure of content types, paragraph types and taxonomy in my site.

Taxonomy vocabulary - Category

Terms - Sports, Politics, Business

Paragraph type - Multi Article

Fields -

Category (term reference to Category vocabulary)

Content types - Landing page , Article

Landing page (fields) -

Multi category (Paragraph field referring to Multi Article paragraph type)[unlimited]

Article (fields) -

Category term (term reference field to Category vocabulary) [unlimited]

Sample content example -

Landingpage A paragraph field has Sports,Politics

Landingpage B paragraph field has Politics

Landingpage C paragraph field has Business,Sports

Article A is tagged with Business

Article B is tagged with Sports,Business

Article C is tagged with Politics,Sports

Desired output -

Landingpage A detail page should be showing something like -

Sports  [based on paragraph field]

Article B  [based on term reference]
Article C  [based on term reference]

Politics

Article C  [based on term reference]

Landingpage B detail page should be showing something like -

Politics  [based on paragraph field]

Article C  [based on term reference]

Landingpage C detail page should be showing something like -

Business . [based on paragraph field]

Article B  [based on term reference]

Sports  [based on paragraph field]

Article B  [based on term reference]
Article C  [based on term reference]

Can this be achieved with views and contextual filters ?

Question in detail -
Forgive me for a lengthy question.

I have a field in the content type - Landing Page, which refers to a Paragraph type.

The paragraph type intern has a term reference field.

When I edit/ create a Landing page content, the desired term names are selected and saved (it can be any number of terms and it doesn't mean that this landing page is tagged to these terms. This is done just to categorise the result while rendering).

I also have another content type - Article which are actually tagged to some terms (both the above paragraph term reference and Article term reference are of same vocabulary)

Now, when any of the landing page content is rendered, I would like to show the latest 5 (or any number) Article contents tagged with each term that was added to the paragraph field which was selected from the paragraph field earlier.

The idea is to make the view result dynamic based on the terms added in the paragraph field of the content. In other words, the view result should vary on every node detail page.

Is there a way to achieve this with the help of views ? My final hope if I don't find a solution is to programatically fetch the latest contents under each term and display them.
Would like to know if a better more elegant way is there with views.

Note - The reason why Paragraph is chosen is due to the flexibility it provides with rearranging the terms etc.

Would be great if any reference or examples are provided if my approach is right.
Thanks.

Although there are multiple ways of doing this, here is probably one of the better ways if editor/front-end control is what you are after. These days, paragraphs are pretty commonly used to give easier control to editors.

It will be setup a little differently however.

First, install and enable the block_field module. This will
create a new type of reference field. We will use this later on.
Create a new View, choose Block display. Choose the Article bundle
for your content. Add some fields from Article that you want to see.
Add a new basic filter criteria for the category term reference
field. Set its default value to Sports.
You should now have a view showing all articles where the category
contains sports. Now duplicate this sports block, make another block
for politics, and so on. Changing the filter criteria to match each
term.

Your view should have a few blocks in it now. One for each term. Now
go edit your Multi Article Paragraph type.
Delete your term reference field from the paragraph, and add a new
field. Under references you will see a Block (plugin) now. Choose
that. Name it whatever, set to unlimited.

On your new field, at the very bottom, drop down the Blocks
fieldset. By default every block will be checked, uncheck them.
Scroll down until you see your 3 view blocks you made. Check each of
them. Then save the field.

Now go create a new landing page as if you are an editor. Your Multi
Article paragraph will have a block reference. Choose add block, and
pick one of the view blocks. Add a paragraph item for each view
block    you want to display.

You can then make many landing pages, allowing the editor to choose which types of articles to display. Here is my landing page A.


How can i remove and edit comment item how to remove or edit comment item like fieldset-wrapper.
just i want the form-type-select show and or edit description in fieldset wrapper.
tnx for all

You will want to duplicate one of the files with extension .tpl.php in modules/comment directory and place the dup' in your theme. Then clear cache and edit the file you dup'd and placed in your theme.

The File you want is /modules/comment/comment.tpl.php


How to configure node variations? I have a content type with a lot of different fields. Now this content can have (but not always) variations, which have the same fields, but different content.

I don't know how it would be best to organize this on the admin side. I could use child nodes, but if I have children, I'll have an empty parent. Basically what I need is to have multiple sets of the same fields for a content item.

I don't know if this is understandable, you might think of the as product variations or subproducts, here's an example:

Macbook (this only has title + description)
 -- Macbook Air (title + one set of characteristics)
 -- Macbook Pro (title + 2nd set of characteristics)
Mac Mini (title, description, characteristics)
iMac (title, description, characteristics)

As @W.M. said, i will use Conditional Fields module Conditional Fields along with Field Collection Module.

Essentially you will first define collections of fields (this is a kind of grouping of fields that are related. ie retina screen details), and then you can make this fields collections to appear if another field value is set using Field Collection.


How to complement eMail notifications with a notification bar? I am building a Drupal 7 website, and I noticed that you can install a facebook-like chat. This made me wonder if it is possible to implement something related to notifications that works something like Facebook. I simply want the notification "bar" to tell me if a user is posting a comment on my website, or if a new user has signed up. At this moment I just get an email about users trying to sign up.

I looked at the Notifications module for D7, but I am not sure this is what I am looking for. Or maybe I just don't know how to use it.

You may be looking for Heartbeat module:

Heartbeat displays user activity on a website. This module is an API to log activity. The logged data contains message structures, attributes and variables. Once the activity messages exist in the database, they will be parsed and build into activity streams.
(...)
Heartbeat has global configuration for display, message template configuration and stream configuration.


user_authenticate() function not working I'm working with Drupal 7, the function **user_authenticate()** working fine with the default User module, but I have implemented a custom "user login" module, and I use this same function in that module, but somehow it is not working at all in this new module.

When we are using this function in default module, it's retrieving all the records based on the user parameters, but in my case it's retrieving nothing.

This is the code that I have put in my custom module file.

if (module_exists('user')) {
     $username = $form_state['values']['name'];
     $pass = trim($form_state['values']['pass']);
     $userRecord = user_authenticate($username, $pass);

     print_r($userRecord); // its resulting me BLANK!!
     exit;

   }

Can anybody help me out please? What would the problem be?

user_authenticate($name, $pass) (Drupal 7) will return the user ID on successful authentication, or FALSE on failure. In Drupal 6, it will return the user info array.


How to change date format to custom in Views? (drupal 6, views2) I have a view that includes a CCK date/time field. It automatically displays the date like this if I choose Long as the format:

Tuesday, April 17, 2012 - 13:30

I need it to display in 12-hour time, not 24-hour, but the view field config doesn't allow me to enter a custom format for my date (for the label, yes - the actual value, no). How can I override the date formatting for just this one view?

EDIT

Never mind; I found a way to do it here.

Answer found here. Basically, you create a new date format in admin that is then available sitewide in any date format dropdown.


How do I change the admin toolbar search input box to type=search? I'd like to change the attribute "type" to "search". The search icon goes over the top of the text making it hard to see what you are typing. The themes are a combination of Adminimal for admin and Bulma for the front end. The Bulma front end is the problem.

The source html is as follows.

<input id="admin-toolbar-search-input" aria-labelledby="toolbar-item-administration-search" type="text" size="60" maxlength="128" class="form-text input ui-autocomplete-input" autocomplete="off" tabindex="-1">

I want the type attribute to be search so that the icon is hidden when you enter text.

I've tried overriding the bulma template input--bulma.html.twig. Not ideal from a scope perspective and setting these attributes here doesn't work.

{{ attributes.setAttribute('type', 'search') }}

Ideally I would find a theme pre-process function. I can't see to find one that works. How do I go about it?

The following hook works. I found it by text searching the project

function mytheme_preprocess_input(&$variables, $hook) {
 if ($hook == "input" && $variables['attributes']['id'] == "admin-toolbar-search-input") {
   $variables['attributes']['type']  = "search";
 }
}

It does not solve the icon problem in this case. The icon is in a different DOM element.

The fix to the search icon being over the text was

#admin-toolbar-search-tab input:focus + .icon.is-left {
 display: none;
}


Apache Solr own grouping in autocomplete The apache solr autocomplete module don't work for me.
I try to achive a relative complex autocomplete,
my target is to achive this on the autocomplete:

Search for "searchword":
-Facet for type/bundle
-Facets based on the results
Show all results for "searchword"

As example:
Search for "test":
Download (176)
Systems (100)
News (20)
Services (5)
Systems
System 1
System n
Services
Service 1
Service n
Show all results for "test"

Any suggestions how I could get this?

Edit: I use apache solr search for this so no search api hook here
(miss some functions in the search api based)

You can try to write your own query according to results you want to get.
below link may help you in this.

https://www.drupal.org/node/2203775


Apply different css files according to user selection Use case: content managers would have permissions to change the color scheme of the site.

Solution: I would make a page from hook_menu and give option to select from different pre defined css files.

Is there a hook/function I can use to render css files accordingly as per selected by user.

like: user selects red option the red named css file should render on site and previous, default css should be overridden.

Thanks

I found the link bit helpful... It might help you too.
http://wearepropeople.com/blog/7-ways-to-add-custom-js-and-css-to-a-page-in-drupal


Why does my Pie Chart only show 1 out of multiple fields? I'm attempting to create a pie chart views block with Google Chart Tools. It has multiple fields with numeric values for each field. The column chart of it works great, as shown in this screenshot:

But for some reason the corresponding pie chart always displays only one of those fields (with 100%), as shown in this screenshot:

What am I doing wrong?

Try rearranging the fields in the views settings under "Fields" section. While you are there, you may also try use a different group field in Google Chart tools format settings under "format" section.


Get path to theme assets in Twig template I have a question about getting a path to an image in a Twig template. The image is not assigned to a field or something. Just a static image which is stored in "MYTHEME/image/icon/my-icon.png".

In Drupal 7 I get the path in my node.template with the following code:

<img src="<?php print base_path() . path_to_theme(); ?>/image/icons">/my-icon.png

How does it work with in Drupal 8? I tried to pass a variable in template_preprocess_node().

MYTHEME.theme:

$variables['images_path'] = \Drupal::theme()->getActiveTheme()->getPath() . '/image/';

Twig template:

It doesn't work. There is no PHP error, but the path is wrongly said to be http://localhost/node/themes/template/image/icons/my-icon.png.

you can use {{ base_path ~ directory }} which will fix the absolute problem, no need to do any preprocessing, both of these variables are included by core.

For example

<img src="{{ base_path ~ directory }}/images/logo.png" alt="My Logo" />

PS. the ~ helper in twig is concatenate.

Edit: at least in the page*.html.twig templates base_path variable is included, possibly you will need to do preprocessing for other templates, you can easily check with {{ dump() }} if the variables are present

// File: THEMENAME.theme in your theme's root directory
function THEMENAME_preprocess(&$variables, $hook)
{
    $variables['base_path'] = base_path();
}


Dependent Dropdown in Field Widget I want to implement a Dependent Dropdown for a custom field widget.

I have a custom field with 5 select boxes. Each subsequent dropdown should populate based on values from previous Dropdown. I have a 5 functions that takes arguments to get the values.

I have implemented that, but I need to Ajaxify it, so that I can populate without page refreshes. Any pointers on how to do that?

Basically, I am trying to implement the below thing (from examples module) with FieldWidget.

https://cgit.drupalcode.org/examples/tree/ajax_example/src/Form/DependentDropdown.php

You didn't deserve the downvote: this is a perfectly good question, one that has simply no answer anywhere on the web yet. All of them only speak about dependent dropdowns in forms, not custom fields where we have two extra problems: first, being out of real form context when setting up ourselves, second, potentially being multivalued.
It took me some time to figure it out but here it is. We're extending a FieldItemBase:
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $id = $this->fieldDefinition->getUniqueIdentifier();
  $wrapper_id = "XXX-$id-$delta-replace";

  $selected_value1 = $items[$delta]->value1 ?? 0;
  $element['value1'] = $element + [
    '#type' => 'select',
    '#options' => $value1_options,
    '#empty_option' => '---',
    '#default_value' => $selected_value1,
    '#weight' => 1,
    '#ajax' => [
      'event' => 'change',
      'method' => 'html',
      'callback' => [$this, 'getValues'],
      'wrapper' => $wrapper_id,
      'progress' => [
        'type' => 'throbber',
        'message' => NULL,
      ],
    ],
  ];

  $selected_value2 = $items[$delta]->value2 ?? 0;
  $element['value2'] = [
    '#type' => 'select',
    '#empty_option' => '---',
    '#default_value' => $selected_value2,
    '#options' => $this->loadOptions($selected_value1),
    '#prefix' => "
",
    '#suffix' => '
',
    '#validated' => TRUE,
    '#weight' => 2,
  ];

  $element += [
    '#type' => 'container',
    '#attributes' => ['class' => ['container-inline']],
  ];

  return $element;
}

Fill value1_options with the options of your first dropdown. Change wrapper_id as you please but we don't know the actual ID the select will receive, so we have to make sure we make it unique in some other way (note that there might be more than one of the same custom field type in the final form, so using the name and the delta only will not suffice).
Using '#validated' => TRUE is usually frowned upon but this is the only easy way to make sure the second select will not result in an "Illegal choice" validation error after we replace the options without the form being aware of the possible values. One standard advice is to pre-fill the second dropdown with the union of all possible values, making sure that later dependent lists always use a subset of that full list but this wasn't really feasible in my case (or any other really dynamic case). Dependent lists in custom forms can simply return the original form element, so this doesn't apply to them, but custom fields can't locate the actual corresponding $form[] element, so this is the best I could come up with. It works.
Next, the function that loads the options of the dependent dropdown, depending on the value selected in the master one:
private function loadOptions($id) {
  $options = [];
  if ($id) {
    // load whatever options belong to the value of $id
    $options = ...;
  }
  return $options;
}

And finally, the Ajax glue to hold it together:
public function getValues(array &$form, FormStateInterface $form_state) {
  $triggeringElement = $form_state->getTriggeringElement();
  $selected_value = $triggeringElement['#value'];
  $html = '';
  $options = $this->loadOptions($selected_value);
  foreach ($options as $key => $value) {
    $html .= "<option value='$key'>$value</option>";
  }

  $ajax_response = new AjaxResponse();
  $wrapper_id = $triggeringElement['#ajax']['wrapper'];
  $ajax_response->addCommand(new HtmlCommand("#{$wrapper_id} select", $html));
  return $ajax_response;
}

If you compare the whole lot to the custom form solution, it's mostly the same but there are small differences in how to identify the correct element and how to actually replace the options of the dependent list that make this work in the field case.


How to add one another library files with different name from the theme name? I try to define a separate library with different name from the theme name, according to this artcle:
Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme
For example a library with below details:

Theme name: MyThemeName
Library Name: Library A
Library File Name: libfile.info.yml

libfile.libraries.yml

LibraryA:
  version: 1.x
  css:
    theme:
      css/Style.css: {}

And then attach this library to all page in:

MyThemeName.info.yml

libraries:
  - MyThemeName/LibraryA

I would be happy to hear what the problem is, share your experiences and guide me to know what is the right way to add another library files with different name from the MyThemeName?
Thanks for any help.

Short answer: You cannot.

Looking answer:
The purpose to for the libraries file is too define all the libraries of a module / theme.

The file is recognized because it is has the name of the theme/module it is placed at.

If you want libraries with a different namespace then you will need to search for an alter hook, and define these libraries there (not recommended).


Any module or way to add line item in existing order? Is there any way so that admin or whoever permission can add the line item in existing order while editing the order?

Any module or custom code?

It's available out of the box from commerce module...

See screenshot below of Edit Order


How to condition output based on a URL query string In my node preprocess function I check the value of a query param...

$variables['exclude_urls'] = \Drupal::request()->get('exclude_urls');

And in my template, I have...

{% if not exclude_urls %}

{{ url }}

{% endif %}

However, this approach doesn't work because the node preprocess function does not fire if nothing in the URL changes besides the value for the 'exclude_urls' param.

I have tried various methods to disable caching for the page.  Adding this to the route doesn't work...

  options:
    no_cache: 'TRUE'

I also tried using the page_cache_kill_switch in my controller, but it doesn't work...

\Drupal::service("page_cache_kill_switch")->trigger();

Neither does adding the query parameter to cache contexts...

$element['#cache']['contexts'][] = 'url.query_args:exclude_urls';

Instead of using hook_preprocess_node, is there some other way I should be checking the value of $_GET['exclude_urls'] and passing that to the template?  Do I add code to the twig template itself to check the value of 'exclude_urls'?  Is there any sure way to force hook_preprocess_node to fire every time?  What is the usual approach to conditioning display of content based on a URL query param so that caching won't interfere?

Update:  To be clear, I have also tried the above approaches in combination, with no success.  For example, the end of my page function in my controller looks like this...

\Drupal::service("page_cache_kill_switch")->trigger();
$element['#cache']['contexts'][] = 'url.query_args:exclude_urls';
return $element;

Update 2: In my local dev site, I do not experience this problem, and I've found that this line in my local settings makes it so hook_preprocess_node fires every time...

$settings['cache']['bins']['render'] = 'cache.backend.null';

However, I'm not sure how to take advantage of this in my production site, since I don't want to disable the render cache generally.  I can do something like this in settings.php, but it's a hack:

$parts = explode('?', $_SERVER['REQUEST_URI'], 2);
if ('/disable/cache/at/this/path' == $parts[0]) {
  $settings['cache']['bins']['render'] = 'cache.backend.null';
}

There are three layers where rendered content can be cached:

The Page Cache, which stores complete pages based on the URL for anonymous users.
The Dynamic Page Cache, which stores pages with placeholders for dynamic content that is rendered on each request.
The Render Cache, which stores individual rendered elements.

Each has a corresponding cache bin that can be disabled during development in settings.php

To set an additional cache context in hook_preprocess, so that the Dynamic Page cache knows to re-render that fragment and the render cache stores variants as needed, update the #cache variable:

function hook_preprocess_HOOK(&$variables) {
  $variables['#cache']['contexts'][] = 'url.query_args:exclude_urls';
}


How to filter Search API index view by taxonomy parent I am using the default database server that comes with search api. I have the Hierarchy Index ticked and I also have the taxonomy field that I want selected.

Could someone give me instructions on how to configure the view to have it filtered by the taxonomy parent/show only the children of the selected parent term? I just want a drop down like you would have with a regular view.

(I got this to work in D7 a while ago but I think that was because the field still retained its taxonomy data type when indexed but now with D8 it has none of that.)

I can add a field that has a parent relationship but that does nothing.
I tried adding a field Vocabulary » Taxonomy term » Term Parents and tried to filter by that but nothing.

I just figured this out the answer was simpler than I thought.

I was trying to use contextual filters & relationships like other answers said but what worked was just simply adding the Taxonomy Field to Filter Criteria then selecting the desired parent. That's it. No need to add a relationship to it.

Edit:
There is still a problem: it doesn't work when using a grouped exposed filter it gives this error:

  A value is required if the label for this item is defined.

Log Message:

  PHP -  Warning: trim() expects parameter 1 to be string, array given in ...

I tried changing the filter to Combined field filter with the Taxonomy as a field so the input would be string but I still get another error.

  PHP - Error: Call to undefined method ...


Is there a REST endpoint for getting the logout token? So I know the logout_token is generated along with the csfr_token during the POST to /user/login?_format=json.

You can get a copy of the csfr_token for the session at any time by calling a GET on /session/token. Is there a way to get the logout token outside of the user logging in? So is there a path that once logged in will provide you with the logout_token? I'm looking for a way to clear a cookie that gets stored beyond the initial session.

It appears this does not currently exist. I just created a patch for core. Please review it and make suggestions if you have a chance. https://www.drupal.org/project/drupal/issues/3004421

I will edit this answer if any progress is made with the patch.


Rule for sending email when order exceeds a defined weight I set up some shipping tariffs (with module shipping weight tariff). But now i want to define a rule that sends an email to the shopowner in case the order total weight is over a certain weight. How should this rule be defined? The one i made is not working, it is not kicking in (for sake of simplicity in the below example I chose to show a message instead of sending an email):

    { "rules_shipping_weight_alert" : {
    "LABEL" : "Shipping Weight Alert",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "-8",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_physical", "commerce_shipping" ],
    "ON" : { "commerce_shipping_collect_rates" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "commerce-order" ], "type" : "commerce_order" } },
      { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "field_physical_weight" } },
      { "commerce_physical_rules_order_weight_comparison" : {
          "commerce_order" : [ "commerce-order" ],
          "operator" : "\u003E",
          "value" : "9",
          "unit" : "kg"
        }
      }
    ],
    "DO" : [ { "drupal_message" : { "message" : "Shipping weight alert!" } } ]
  }
}

Any help would be much appreciated!

After some fiddling I've found the solution myself:

    { "rules_notice_overweight" : {
    "LABEL" : "Overweight",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "commerce_physical", "rules", "commerce_shipping" ],
    "ON" : { "commerce_shipping_calculate_rate" : [] },
    "IF" : [
      { "commerce_physical_rules_order_weight_comparison" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "operator" : "\u003E",
          "value" : "10",
          "unit" : "kg"
        }
      }
    ],
    "DO" : [ { "drupal_message" : { "message" : "Total weight is over 10kg" } } ]
  }
}

The problem in my first code example was the trigger "commerce_shipping_collect_rates". It has to be "commerce_shipping_calculate_rate" instead. I hope someone can benefit from that.


How do I add image captions using a custom style? I am not a programmer.

However, I need to know how to use css to add a caption for an image field in a node.

One way would be to create your own theme_image() in your theme's template.php file.  It would be pretty straightforward, just grab drupal's default theme_image() from theme.inc and add a span to it:

If Drupal 6:

function YOURTHEMENAME_image($path, $alt = '', $title = '', $attributes = NULL, $getsize = TRUE) {
  if (!$getsize || (is_file($path) && (list($width, $height, $type, $image_attributes) = @getimagesize($path)))) {
    $attributes = drupal_attributes($attributes);
    $url = (url($path) == $path) ? $path : (base_path() . $path);
    return '' . check_plain($title) . '';
  }
}

If Drupal 7:

function YOURTHEMENAME_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '' . (isset($variables['title']) ? $variables['title'] : '') . '';
}

Clear caches/theme registry and now every image will have a span with class caption after it with the image's title in it (or blank if none obviously).  If you want to get fancier with wrappers and so forth, just put whatever html you want/need in the return's above.

Then CSS this however you want.


How to add css depending on a field value? I have a field attached to a node which contains an image or not.

If there is an image I should load a specific css(sass).

How can I do this?

Basically you need to drupal_add_css in your template_preprocess_node in your template.php after checking the condition that image exists in a manner similar to

$field = field_get_items('node', $node, 'field_image');
if ($field) {
   //Do something with the field
}
else{
   //There are no results
}


Prevent form rebuild on image upload I have content type Gellery with two fields.
Image (Multiple)
Game Name (Entity Reference)

I am setting Game Name in hook_form_alter. Lets say it is set to "Game 001".
When image is uploaded, it actually resets the form, so the changes made to field "Game Name" donot apply when submit the form.

How to prevent form to be rebuilt on uploading image.
I guess something do to with $form_state

if ($form_id == 'game_gallery_node_form') {
  $form['field_boardgame']['und'][0]['target_id']['#default_value'] = 'game (41)';
}

I've done some tests using an Entity Reference field, and setting its default value in a hook_form_alter implementation. Everything is working fine - when I upload a single or multiple image files, the default value that I set in the hook for the Entity Reference field is preserved, and is saved fine when I press Save.

Please notice the way I'm setting the default value in my implementation of hook_form_alter(). This is different from what you have:

$form['field_reference_to_page'][LANGUAGE_NONE]['#default_value'] = 'trip (189)';

(My field is called field_reference_to_page. In your case, you 'll need to replace with field_boardgame). Notice that the arrays are different from what you have. Basically there is no [0] or ['target_id']. The value 'trip (189) is the title of the node and the node ID that this field is referencing. I made sure that the node really existed, and the node ID was correct.

I put together a short video proving that it really works.

By the way, Image fields cause an AJAX call when an image is uploaded - the form is rebuilt but not reloaded. But as I said, the default_value is preserved if you implemented the form alter correctly.


After logging off, a user is able to see the pages by pressing back button of the browser I have a requirement in which the user should not be able to see the books in the site unless he is logged in. And the user is not able to see the content.

The problem is when a user logs in, views a book and its child pages, and logs out; he is still able to view the pages he opened before when he was logged in, by pressing the back button of the browser. He is not able to make any changes though.

This may create problems when users visit the site from a public computer, log off, and go away without closing the browser window.

Is there a module or any setting change I can use to solve this issue?

This is a result of the browser caching the page, there's not a lot you can do about it really.

Some browsers might respond to setting cache control headers like the following:

header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

which might force the browser to re-load the page regardless of it's local cache.

There are apparently some options available to control this in Safari specifically, but I haven't been able to find anything for other browsers. I imagine the same would work for Chrome (being Webkit based), but I can't comment on the the other major browsers.


Extending the User Registration Form To add fields to the User Registration one can directly use the admin/config/people/accounts page. However, I am required to some other fields to the User Registration like food choice which is to be selected from drop-down list of foods, Email and Confirm Email fields (which should check whether both are same and whether the email was used in db), country (If UK/US is selected, text field for state, postal code should appear). Now, I could add the fields to the user registration page, but how can I handle the validations for the fields and how do I show such dropdown list. Am I required to create my module that extends the User Registration form. If so, how do I do this? Thanks.

If your only need is to add new required fields to the user registration form, you do not need modify the form through a module; by marking any user entity field as a Required field in the field UI, it will be presented in the registration form as a required field for registration.

If you require custom validation that goes beyond "it must be non-empty" you might need to employ a custom validation handler in a custom module, another helper module (e.g. Field validation), or a custom field module that matches your use case (e.g. Address field module).


How I can intercept an image field upload and validate it? I have a content type with an image field. I need to validate this field because I need to check if user upload a real image or only a file with image's extension (like jpg, gif, png etc). I have tried and readed 100+ things but none resolve my problem.

I have tried via "#upload_validators" with this code:

foreach ($form['field_all_images'][$form['field_all_images']['#language']] as $k => $v) {
  if (!is_integer($k)) continue;

  $form['field_all_images'][$form['field_all_images']['#language']][$k]['#upload_validators']['check_image_correct'] = array();
}

where "check_image_correct()" is a my custom function that checks via imagegetinfo(). My problem, in this "try/case", is that the function works/is called only for the first image. I have tried to move this function from hook_form_alter() to an #after_build function, without result (only the first time it works).

It looks like there a couple of very small bugs in that code that would stop it working properly, try this:

$lang = $form['field_all_images']['#language'];
foreach (element_children($form['field_all_images'][$lang]) as $key) {
  $form['field_all_images'][$lang][$key]['#upload_validators'][] = 'check_image_correct';
}


How to add Clear button for views exposed filter? I created a content type and View with Filter Criteria for my project, when I click the Search it shows the appropriate results.

But there is no option to clear the Search Fields and redirected to previous page (View).

In my requirement I need to keep a [clear/cancel] button with [search] button.

How to add [clear/cancel] button with [search] button in View?

Go to you view and Exposed form style settings. (You can find it right side Advanced settings of the view)

and check the 'Include reset button' option . You can also change the Reset button label. Find below.


How do I fix this commerce_auction_node_presave error message? I am working on a reverse auction for our youth group.  I'm using D7 with the commerce_auction module.   I ran into the error below when setting up the content type for the auction:

Notice: Undefined offset: 0 in commerce_auction_node_presave() (line 260 of /public_html/catz/sites/all/modules/commerce_auction/commerce_auction.module).
EntityMalformedException: Missing bundle property on entity of type commerce_product. in entity_extract_ids() (line 7697 of /public_html/catz/includes/common.inc).

for the first notice, line 260 contains this: $product_reference = $product_reference[0];

Does anyone know how to fix this error?  There's not a lot of commenting as yet on this auction module, so I can't find a solution.

/**
 * Implements hook_node_presave().
 */

function commerce_auction_node_presave($node) {
  $types = variable_get('commerce_auction_display_types', array());
  if (in_array($node->type, $types) !== FALSE) {
    $product_reference = field_get_items('node', $node, 'field_product');
    $product_reference = $product_reference[0];
    $product = commerce_product_load($product_reference['product_id']);
    $price = field_get_items('commerce_product', $product, 'commerce_price');
    $node->auction_starting_price[LANGUAGE_NONE][0]['amount'] = $price[0]['amount'];
    $node->auction_starting_price[LANGUAGE_NONE][0]['currency_code'] = $price[0]['currency_code'];
  }
}

Change the code below :

 $node->auction_starting_price[LANGUAGE_NONE][0]['amount'] = $price[0]['amount'];
    $node->auction_starting_price[LANGUAGE_NONE][0]['currency_code'] = $price[0]['currency_code'];

with

 $node->auction_starting_price[LANGUAGE_NONE][0]['amount'] = $price['und'][0]['amount'];
        $node->auction_starting_price[LANGUAGE_NONE][0]['currency_code'] = $price['und'][0]['currency_code'];


Does anonymous can access current node? How to check it in my module? I need to do something witn current node by my module only if anonymous users can view this node. How to check it?

By default I use $node->status == 1, but some other modules can change anonymous access rights also for published nodes.

Also, for development especially, Devel module's Devel Node Access submodule provides a block that you can display that shows, on any given content page, all the user access permissions/grants provided, and even displays a few users and the access they would be given if they tried accessing the page, editing, deleting, etc.

Check it out: http://drupal.org/project/devel

Also, just a short bit ago, Larry Garfield posted an excellent overview of node access in Drupal 7 (applies almost without any adaptation to the Drupal 6 systems as well).


View filtered by a Date field's value being in "last month" shows July content on July 31 A View is filtered by a Date field's value.  The Date field's month must be last month in order to match the filter.

On every day except July 31 it would return results from last month.  It should have returned results matching June.  We have tried "-1 month" but that didn't work either.

Why on July 31 does it jump ahead a month?

Try to use 'last day of last month' or 'first day of last month'.


hook_tokens_alter() not applying to [user:one-time-login-url] Token I'm trying to alter the one time login token. I am implementing hook_tokens_alter to do this.

/**
 * Implements hook_tokens_alter
 * @param $replacements
 * @param $context
 */
function portalapi_tokens_alter(&$replacements,  $context){
  if(isset($context['data']['user'])){
    foreach($context['tokens'] as $name => $original){
      switch ($name) {
        case 'one-time-login-url':
          $timestamp = REQUEST_TIME;
          $token = user_pass_rehash($context['data']['user']->pass, $timestamp, $context['data']['user']->login, $context['data']['user']->uid);
          $resetpath = url(variable_get('portal_frontend_url').'/reset-password/'.$token.'-'.$timestamp);
          $replacements[$original] = $resetpath;
          break;
      }
    }
  }
}

Logging the $replacements array at the end of the function call shows the expected changes. However, the token output isn't altered when used (for example when sending password reset emails).

As a quick background here - We're implementing an entirely headless front end serviced by an API, we need to use a different domain in the one time login link and a different structure.

What am i missing?

You cannot alter it because that token is not returned from user_tokens(). You get that token only with code similar to the following one.

$text_with_tokens_replaced = token_replace($text, $variables, array('language' => $language, 'callback' => 'user_mail_tokens', 'sanitize' => FALSE, 'clear' => TRUE));

The problem is that first the implementations of hook_tokens_alter() are called, then the callback passed to token_replace() is called. The effect is that every value you set for that token is then changed from the callback.

This is the code used from token_replace().

  $replacements = array();
  foreach ($text_tokens as $type => $tokens) {
    $replacements += token_generate($type, $tokens, $data, $options);
    if (!empty($options['clear'])) {
      $replacements += array_fill_keys($tokens, '');
    }
  }

  // Optionally alter the list of replacement values.
  if (!empty($options['callback']) && function_exists($options['callback'])) {
    $function = $options['callback'];
    $function($replacements, $data, $options);
  }

token_generate() is the function invoking the token hooks (including the alter hooks).

  $replacements = module_invoke_all('tokens', $type, $tokens, $data, $options);

  // Allow other modules to alter the replacements.
  $context = array(
    'type' => $type,
    'tokens' => $tokens,
    'data' => $data,
    'options' => $options,
  );
  drupal_alter('tokens', $replacements, $context);


I get "You are not authorized to access this page" when I try to load a view with Ajax I am trying to load a view with Ajax, showing it in a specific
. I always get the Ajax message, "You are not authorized to access this page." My code is the following one:

/**
* Implementation of hook_menu().
*/
function custom_api_menu() {
  $items['ajaxgettip/nojs/%'] = array(
    'page callback' => 'custom_api_test_ajax',
    'type' => MENU_CALLBACK,
    'access callback'   => TRUE,

      );
  $items['ajaxgettip/ajax/%'] = array(
     'delivery callback' => 'ajax_deliver',
     'access callback'   => TRUE,
  );
  return $items;
}

function custom_api_test_ajax($nid) {

   $viewName = 'tip';
   $args = array($nid);
   $displayId = 'block_1';
   $view = views_embed_view($viewName, $displayId, $args);
   //return drupal_json(array('test'=>$res));
   ajax_deliver($view);
}

I am creating a link as follows:

<?php
    $link = array(
        '#type' => 'link',
        '#title' => t('something'),
        '#href' => 'ajaxgettip/ajax/114', #Hard coded nid at the end of path, just for testing
        '#ajax' => array(
            'wrapper' => 'ajax-response-goes-here',
            'method' => 'replace',
            'effect' => 'fade',
        ),
    );

$output = "
Some HTML and stuff
" . drupal_render($link);
print $output;
?>

I don't have an idea about what I did wrong, and I have read a whole lot of documentation. Who can help me?

Try with page arguments in hook_menu:

function custom_api_menu() {
  $items['ajaxgettip/nojs/%'] = array(
      'page callback' => 'custom_api_test_ajax',
      'page arguments' => array(2),
      'type' => MENU_CALLBACK,
      'access callback' => TRUE,
  );
  $items['ajaxgettip/ajax/%'] = array(
      'delivery callback' => 'ajax_deliver',
      'page arguments' => array(2),
      'access callback' => TRUE,
  );
  return $items;
}


Is there a way to insert "0000-00-00 00:00:00" in a datetime database field? Is there a way to insert "0000-00-00 00:00:00" datetime database field?
Should I change the database field's default value to "0000-00-00 00:00:00"?

I got replies on Stack Overflow, and it works with plain PHP, but it gives an error with Drupal.

In Drupal 7 DB API, support for the datetime type was removed. This means that you must use use mysql_type or pgsql_type if you want this functionality.  Below is an example of of to declare this schema provided your database is MySQL.  By setting not null to FALSE, you can store an empty value (''), which is equivelent to '0000-00-00 00:00:00':

'mydate_date' => array(
  'description' => t('My date field.'),
  'type' => 'varchar',
  'mysql_type' => 'datetime',
  'not null' => FALSE,
),

Note that to make the schema portable, you should provide a fallback type (varchar) for the case that the database is not mySQL.


How do I alter the default node URL rendered in a view? I have a view that shows a list of node titles, where the node title is linked to the node detail page. I want to alter the node URL with a custom one.

How can I alter the node URL?

Usually when you set a URL alias when you creating/updating a node this new url will be used for your nodes links. If you didn't set a URL alias for your nodes, clear the caches after set. In my dev site working fine just doing this.


dpm() in hook_init shows twice on the page In my custom module, I use a hook_init() with a dpm-function.

function mymodule_init() {
    dpm('check');
}

but for some reason, my page shows 2 times 'check' on the page... Is this default Drupal behavior? And if so, what are the reason for this behavior?

hook_init runs once per-page request, for non-cached pages.

See _drupal_bootstrap_full

module_invoke_all('init');

I guess what's perhaps happening in your case is an additional ajax request is bootstrapping Drupal and triggering an additional hook_init call.


Print out NID of entity reference I have a custom field that is an entity reference, when using

  print render($content['field_call_to_action_1']);

in a content type template it prints out the title Call to Action 1, and the Title of the content that the entity reference is linked too.

How can I just get it to print out the NID instead?

Thanks for your time!

$content is to be rendered and obeys what you have set in node(other other entity) type's Display Settings (Administer > Structure >Content Types).

What you should use is, $node object.

<pre>
<?php
print_r($node);
?>
</pre>

Now you will see a nicely formatted information of $node object which also has the NID you want.

You will be able to access it with this:

$node->field_call_to_action_1['und'][0]['target_id']

Quick hint:If you are trying to build a URL link from this value, have a look at url() and l() functions!


How to configure URL paths using the pathauto module for multilingual sites? I am working on multilingual drupal website.To generate content path(i.e url) I am using pathauto module. I have not configured this module.

When I add content from basic page it sets content/[node:title] as url path seetings. It is fine for english language. But for other language content I want to set url same as english content.

What path pattern I have to set so that url path for nepali content is same as english content ?

Any help is welcome!

Consider using the Pathauto i18n module for this. Excerpt from its project page:

  ... by default Pathauto creates alias only for one language or for all languages one alias. This module provides functionality to create aliases for each language. Also this module will be helpful, if you use field translation and you want show node on all language with paths, different from node/nid.

This module contains 3 submodules which can be used to enable separate functionality for each entity:

pathauto_i18n_node (for nodes).
pathauto_i18n_user (for users).
pathauto_i18n_taxonomy (for taxonomy).

Example (also from project page):

When you create node without pathauto_i18n:

English alias: en/articles/first_article
Italiano alias: not exist
Deutsche alias: not exist

When you create node with pathauto_i18n:

English alias: en/articles/first_article
Italiano alias: it/articolo/first_article
Deutsche alias: de/artikel/first_article


The return property of exclamation in front of array I am learning the drupal 7 by the example module.
In the render_example, I don't understand the usage of the exclamation mark (!) in front of the !array and !alter.

I am sure that it is not related to the "boolean" nor "negation".
Please kindly advise how can I find the detail of the usage.

function render_example_info() {
  return t('The render example provides a

demonstration of of render array usage

using hook_page_alter() to make various changes on a page.

', array('!arrays' => url('examples/render_example/arrays'), '!alter' => url('examples/render_example/altering')));

}

When I edit the "!array" to "$array",

function render_example_info() {
return t('The render example provides a

demonstration of of render array usage

using hook_page_alter() to make various changes on a page.

', array('$arrays' => url('examples/render_example/arrays'), '!alter' => url('examples/render_example/altering')));

}

the message was changed
from:
demonstration of of render array usage
(with hyper link "http://www.example.com/drupal/?q=examples/render_example/arrays"
to:
/drupal/?q=examples/render_example/arrays">demonstration of of render array usage
(with hyper link "http://www.example.com/drupal/&5cem&nbspclass=" )

t() uses format_string(), which uses strtr(). For this reason, your second example snippet works. Since format_str() is using the following code, any token that starts with a character different from !, %, or @ is treated as if the token started with %.

  foreach ($args as $key => $value) {
    switch ($key[0]) {
      case '@':
        // Escaped only.
        $args[$key] = check_plain($value);
        break;

      case '%':
      default:
        // Escaped and placeholder.
        $args[$key] = drupal_placeholder($value);
        break;

      case '!':
        // Pass-through.
    }
  }

drupa_placeholder() is the responsible for escaping some characters, since it calls check_plain().

function drupal_placeholder($text) {
  return '' . check_plain($text) . '';
}

As side note, since $arrays is inside a single-quote string, PHP doesn't replace it with the value of the $arrays string. If you wanted to put the content of a string into the string passed to t(), you should use a t()-placeholder, which starts with !, %, or @.


Is it possible to display Entityform Types using Page Manager and Panels in D7? Currently, I have a D7 site and my main Content region is displayed using Page Manager and Panels variants. I've created an Entityform Type that allows users to request an appointment, and I'd like this specific entityform type to have a different layout than what the default page.tpl.php provides.

I'd love to provide a default panels layout for all Entityform types, but I can't seem to find a way to do this (even using the Entityform Panels module.) I've come close by using the "Page manager existing pages", but submission pages display in the default page.tpl.php.

Is there a way to do this?

What we have done so far, is to reference an Entity-Form in an node type with entityreference.
This works so far.
The Form will be displayed in the panelized theme and the preview will show up too in the correct context.
But!

The Preview will not show the labels of empty fields
The submission Page will not show in the correct layout and is still loosing context (even with pm-existing-pages)
List fields are broken, if core Patch https://www.drupal.org/node/1677598 is applied they don't break the form submit, but are empty in the preview and not saved.
Date fields with time are somehow broken too. Time is not safed, Date only when using the PopUp Calender

We decided to use the redirect option instead of the submission page to workaround the layout problem with the submission.
The Preview is still broken and we are trying to get it fixed.

Conclusion: Entityforms and Panels do not play well together. If we would have know this before we would have built a custom module or used Webform 4.x instead (we are still using webform 3.x in this site but there you don't have the option to use views to manipulate submitted data without loading another bunch of buggy modules!)

Hopfully Drupal 8 and YAML-Forms do a better Job in the future.


How can I view the IP addresses of visitors who view the home page of my site? I need to gather the IP addresses of visitors who view the home page of the site. There are bots that bounce off of the home page thousands of times a day. The Statistics module makes the site too slow. I also tried the Visitors module which worked pretty well, but there was no way to reduce the results only for the home page. Is there an another way to exclusively view IP addresses that visit the home page?

Edit: A way that doesn't slow the site down with a lot of database writing.

If you are using Apache, all page requests are recorded in the log directory. On a Ubuntu machine the location of this directory will be /var/log/apache2.

To block spam traffic, I recommend the mod_spamhaus module. This link contains information on how to setup mod_spamhaus on a Ubuntu machine. The module checks for blacklisted IPs listed on the Spamhaus project and subsequently refuses the connection if a positive match is found.


How to specify English path alias for Chinese? I created a node of type Post in English, and translated it using Entity Translation to Chinese, Traditional. I then set the path alias for the content type to be [node:menu-link:parents:join-path]/[node:title], so it will create an URL alias based on the menu trail and the node title.

However, for Chinese, it is coming up with the Chinese node title, is there anyway to make it display the English title instead? Possibly using Tokens?

I am aware of the Transliteration module, but I am not looking to transliterate, but use the English title altogether.

Instead of using [node:title], use [node:menu-link] instead.


Why are all of the non-value columns indexed, but the value column isn't? I'm working on improving performance for a Drupal 7 website and noticed that all of the non-value columns (entity_type, bundle, delete, etc) are indexed, but the actual value field isn't...does this make sense to anyone?

I know Drupal uses the other fields to join against other tables, but any views/custom queries that are searching for nodes with specific field values are going to suffer are they not?

Is there some reason why the value column isn't indexed by default? Will it cause problems if an index is added?

The specific field I'm looking to index is a date field if that provides any more insight into the situation

I'm not an expert in this but I think it's probably due to the fact MySQL enforces a maximum key length for indexes. For InnoDB this is 3500 bytes (further limited to 3072 bytes by MySQL itself), and for MYISAM it's 1000 bytes.

Whether or not the value columns are indexed is actually done on a per field-type basis. For example, the long text field type (for fields like the node body) has no index on the fieldname_value column, but it does have an index on the fieldname_format column.

The fieldname_format column is a varchar limited to 255 characters, and so would not produce an index key that is too long. Conversely the fieldname_value column is a longtext type, which has the potential to create a key that would be too long. (You can specify a prefix length to get around this but I don't think Drupal supports it).

As another example, if you then look at a table for an image (or file) field type you'll notice there is an index on the fieldname_fid column. Because this field is an integer type it naturally lends itself to be indexed, without having to worry about the maximum index key length.

I think it basically comes down to the type of data the field is storing. entity_type/bundle/etc. are all integer columns and so can be easily indexed by whatever storage engine you're using, while text types (or varchar types with a large enough length) will create an index key that's too large for the storage engine to handle.

Hope that helps a bit


CronJobs - I have two cron jobs but only one works I have created 2 cron jobs on my server(ubuntu), but only one works.

*/5 * * * * curl -s http://www.example.com/cron.php?cron_key=TzVesnZuNqR4mkjv_LgBemUV-oYvsfYalyHOfDtL4cc

*/5 * * * * curl -s http://www.example.gr/cron.php?cron_key=OrrbXhtfSEZ2NI7BlHjAPRtMT_ENAKaz68iH86Kl5wI

In my log file at /var/log/syslog there is an error stating "Cron could not run because an invalid key was used." but my key is correct. When I launch manually, it runs the cron successfully.

I can't understand why this is happening. Is there any solution?

The URL of the cron.php page requires a "cron key" to protect against
unauthorized access. Your site's cron key is automatically generated during
installation and is specific to your site. The full URL of the page, with the
cron key, is available in the "Cron maintenance tasks" section of the Status
report page at Administration > Reports > Status report.

As an example for how to set up this automated process, you can use the
crontab utility on Unix/Linux systems. The following crontab line uses the
wget command to visit the cron.php page, and runs each hour, on the hour:

0 * * * * wget -O - -q -t 1 http://example.com/cron.php?cron_key=YOURKEY

Replace the text "http://example.com/cron.php?cron_key=YOURKEY" in the
example with the full URL displayed under "Cron maintenance tasks" on the
"Status report" page.


Send attachments with drupal_mail I'm trying to send attachments with my email from Drupal. In my custom module i have added:

class SponsorprogramMailSystem implements MailSystemInterface {
  /**
   * Concatenate and wrap the e-mail body for plain-text mails.
   *
   * @param $message
   *   A message array, as described in hook_mail_alter().
   *
   * @return
   *   The formatted $message.
   */
  public function format(array $message) {
    $message['body'] = implode("\n\n", $message['body']);
    return $message;
  }
  /**
   * Send an e-mail message, using Drupal variables and default settings.
   *
   * @see http://php.net/manual/en/function.mail.php
   * @see drupal_mail()
   *
   * @param $message
   *   A message array, as described in hook_mail_alter().
   * @return
   *   TRUE if the mail was successfully accepted, otherwise FALSE.
   */
  public function mail(array $message) {
    $mimeheaders = array();
    foreach ($message['headers'] as $name => $value) {
      $mimeheaders[] = $name . ': ' . mime_header_encode($value);
    }
    $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
    return mail(
      $message['to'],
      mime_header_encode($message['subject']),
      // Note: e-mail uses CRLF for line-endings. PHP's API requires LF
      // on Unix and CRLF on Windows. Drupal automatically guesses the
      // line-ending format appropriate for your system. If you need to
      // override this, adjust $conf['mail_line_endings'] in settings.php.
      preg_replace('@\r?\n@', $line_endings, $message['body']),
      // For headers, PHP's API suggests that we use CRLF normally,
      // but some MTAs incorrectly replace LF with CRLF. See #234403.
      join("\n", $mimeheaders)
    );
  }
}

and i can send mails with html, that part is working.

But when i try to attach a file it does not arrive in my inbox. I attach my test file like this:

$attachment = array(
        'filecontent' => file_get_contents(DRUPAL_ROOT . '/README.txt'),
        'filename' => 'test.txt',
        'filemime' => 'text/plain',
      );

But nothing arrives.

Anyone know how i can fix it?

There might be other ways, but I have found that mailsystem and mimemail modules have to be installed to send email with attachment. So install these two modules first.

Then implement hook_mail to pass attachment to $message

/**
 * Implements hook_mail().
 */
function mymodule_mail($key, &$message, $params) {
  $message['subject'] = $params['subject'];
  $message['body'][] = $params['body'];

  // Add attachment when available.
  if (isset($params['attachment'])) {
    $message['params']['attachments'][] = $params['attachment'];
  }
}

There are two ways to add attachment, you can either pass filecontent or filepath when adding an unmanaged file as attachment (not recorded in DB) or pass file object when adding an managed file.

When adding unmanaged file:

$attachment = array(
  'filepath' => $filepath, // or $uri
);

or

$attachment = array(
  'filecontent' => file_get_contents($uri),
  'filename' => $filename,
  'filemime' => 'application/pdf'
);

By using filecontent way, you probably will get two php errors by Jan 08, 2015 including

Warning: is_file() expects a valid path
Warning: realpath() expects parameter 1 to be a valid path

When adding managed file:

$attachment = file_load($fid);

Then send email by:

$params = array(
  'key' => 'my_email_template',
  'to' => 'test@example.com',
  'from' => 'test@example.com',
  'subject' => 'Test email',
  'body' => 'test',
  'attachment' => $attachment
);

drupal_mail('mymodule', $key, $to, $language, $params, $from);


how do you add a cookie policy to the site so it appears when a user arrives? Possible Duplicate:
  eu cookie compliance

I think this is now a legal requirement in the uk so I want to add one but I have not been able to find a module to do it. Has anyone found one or achieved it by doing a workaround?

The Cookie Control module works fine to address this question.
Here is a quote from its project page:

On May 26th 2011 a new EU originated law came into effect that requires website owners to make significant changes to their sites and may fundamentally change the whole web browsing and shopping experience for everybody.This Cookie Law is amended privacy legislation that requires websites to obtain informed consent from visitors before they can store or retrieve any information on a computer or any other web connected device.
Cookie Control does just that, presenting users with clear information on whether cookies are present, linking to your privacy policy (where you should have specific information about what cookies are in use), and advising users on how to adjust browser settings and what cookies mean for them.