Send email with html template programmatically On board:

Drupal 7
Mail System
Mime Mail

mimemail-message.tpl.php is configurated

E-mails sends by Rules with HTML template, but template not used when it call programmatically:

$mail = array(
  'subject' => 'Test e-mail',
  'message' => '

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy <s>nibh</s> euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

  ',
);
drupal_mail('system', 'mail', 'to@example.com', language_default(), array('context' => $mail));

In the mimemail-message.tpl.php info you can read

  Copy this file in your default theme folder to create a custom themed
  mail.
      Rename it to mimemail-message--[module]--[key].tpl.php to override it for a
      specific mail.

Try to change your tpl name from
mimemail-message.tpl.php to mimemail-message--system.tpl.php


How to list entities and sort them by delta? I have a "stations" and "railways" node types and a custom "notification" entity type.
In "railways" node type I have an entity reference field ("field_stations") where I can select "stations" nodes which is good.
In "notification" entity type I have an entity reference field where I can select related stations. (entity reference to "stations" nodes)
I would like to create a view to list "stations" nodes with grouping and sorting. I would like to group them by "railways" and sort them by delta ("field_stations").
I tried it but I could not get the right order and get a lot of duplications. I have tried views_order_by_delta module as well with no luck.
Do you have any recommendations?

I think you're overcomplicating things here. From my reading, you really should be creating your view to:
Show content of type: Railway
This will be your "grouping". You don't want to using the Views grouping option here - that option is more useful when you want to group the result content by a field on each result, i.e. if your stations node type had a reference to Railways.
Fields to Display: Title, field_stations (or, preferable imo, configure a view mode for the Railway node that displays the fields you want to show).
Since we have a view of Railways, your results are naturally "grouped" by Railway. If you just display the stations field from the railway, you'll get the stations listed in the order on the field (its delta).
(optional) Contextual Filter: field_stations
I'm not sure if you actually need this from your description. You can configure a contextual filter for the field_stations field to allow you to show only the Railways (and their stations) if a Railway references a station you pass as an argument.


Mini pager work with ajax but not full pager? I don't know if someone has ever expected this error but i can't find "why" it's not working.

In the same page, i have 2 blocks. Each block represent a different view.

The first have mini pager, the second, full pager.

Mini pager is working well, full pager reload the page each time (Yes, i have Use AJAX to Yes).

The only differences i can see are into the HTML (The mini pager UL have class "pager" and the LI have class "pager-prev" and "pager-next"). In the full pager, UL have no class and LI have classes "next" and "prev".

Full pager is suppose to use ajax?

Thanks for your help folks!

This sounds like a theme issue, try switching to Bartik and seeing if the issue is resolved. For example Omega provides its own theme() function for full and mini pagers.

The class pager is required on the UL element for pager AJAX to work properly. Review your theme and make sure it is properly theming the full pager, or open an issue on the Drupal.org project page.


$content is only showing array text I have a theme, and for the life of me can't figure out why $content is rendering "array". I have switched to two other themes (framework and seven, and my new theme is based off of the framework theme that is working).

Here is an example of the theme code:

    <div <?php if ($left): ?>id="maincolright" <?php elseif ($right): ?>id="maincolleft" <?php else: ?>id="main" <?php endif; ?>class="nobg node-<?php print $node->nid; ?>">

    <?php if ($tabs): print '

'. $tabs .'
'; endif; ?>
    <?php if ($tabs2): print '
'. $tabs2 .'
'; endif; ?>
    <?php if ($tabs): print '
'; endif; ?>
    <?php if ($show_messages && $messages): print $messages; endif; ?>
    <?php print $help; ?>
    <?php print $content; ?>

So $content is there, and it should be fine, but on any pages I view, for instance, the page render, the edit page, or even my devel page, show only 'array'. See the screenshot:

Has anyone come across this?

print() is a command that doesn't work with arrays. print_r() will print out arrays for debugging but what you want is print render($content). Drupal uses large render arrays to output content, and they cannot be printed directly.


Fire a rule only when a specific webform has been submitted I am using the latest version of both drupal 8 and webform 8

Here is my use case:

I have on my drupal 8 website 3 different webforms (webform A, Webform B and Webform C)

Now, I want to fire a rule ONLY when "Webform A" is submitted.

I understand that we should use condition to limit the rule to one webform only.

For example in drupal 8 if i want to show a message on the website when a new content of type article is saved, i do the below:

1) EVENT: After saving new content (rules_entity_insert:node)

2) CONDITION: Node is of type; Node is of type: node; Content Types: article

3) ACTION: Show a message on the site.

And it is working pretty good when saving a content of type ARTICLE.

Now, i want ot do the same but using a webform instead of a node.

Here what i did so far:

1) EVENT: After saving a new webform submission (rules_entity_insert:webform_submissiom)

2) ACTION: Show a message on the site.

After saving a new webform submission, the message is indeed showing on the website which is perfect.

However, the problem is that the message is showing for any SUBMITTED WEBFORM.

In order to limit the rules to be fired only when the webform A is sumbitted, a condition should be added to the rule in question.

I have used the below conditions

"Entity is of type"

"Node is of type"

"Webform"

"Webforms"

trying to limit the rule for only one webform and all above conditions resulted an error on the site after trying to submit any webform:

(The website encountered an unexpected error. Please try again later)

And when i remove the condition added, the site work properly again.

Any idea what is going on ?

Or maybe i am using the wrong condition to specify only one webform ?

Main question:

What is the condition to be used in order to fire a rule ONLY when one specific webform has been submitted.

Thank you in advance,

I got this to work but i don't know if my answer will be the best approach for what i need:

Let's say, we want the rule to be fired ONLY for the webform ID: "contact"

1) EVENT: After saving a new webform submission (rules_entity_insert:webform_submission)

2) CONDITION: Data Comparision;

Data to compare: webform_submission.webform_id.target_id;

Operator: ==

Value: contact

3) ACTION: Show a message on the site.

Hope it will help somebody else as well, especially that there is no documentaion yet for rules 8.

Cheers,


Drupal 7 - field template - $item - img tag In drupal 7 theme, I have the following file:

field--field_photo.tpl.php
     clearfix">

    >:

    >
     $item) : ?>
    ">

Inside render($item) lies an image with img tag
How I may deconstruct this item, so that I write my code with img tag?
The reason is just that I want to add a class to this img tag. thanks

The path to the images are save in public:files format

I usually use Devel module to figure out things like this. Install and enable Devel, then add something like this to your field template file:

<?php kpr($item); ?>

This will show you all the contents of $item (arrays and objects). Then you can just print the part that you want (the img tag in this case), wrapped in the extra class.


Is there a simple way to alter core node/add/my_node_type to adding/my_node_type? I don't want to show "node/add" in my url "node/add/my_node_type", instead I want to have "adding/my_node_type". Is there a simple way to hide "node/add" but not loose those args?
I want to have "node/add/my_node_type" functionality after hitting "adding/my_node_type".

I can't see form add or form edit patterns in path so I think it is not so easy...

Of course after that I will need "node/%/edit" to be "editing/%"...

I didn't test this code, but if I'm not mistaken, it should be as simple as doing this in a custom module:

function YOUR_MODULE_NAME_menu_alter(&$items) {
  $items['adding/my-node-type'] = $items['node/add/my-node-type'];
  unset($items['node/add/my-node-type']);
}

Something similar could be done for the editing path.


#required attribute not letting me to redirect a drupal 7 form I have a form with 2 buttons. One is a submit button and another is a simple button when clicked, the page has to be redirected to another page.(I mean the user has to be redirected even if he hasn't filled in the entire form)

So after the submit button I put the following code for the other element

<?php
$form['health_calorie_consume']['view'] = array(
          '#type'=>'button',
      '#value'=>'View stats',
    '#validate'=>array('mymodule_form_view'),
     );
?>

inside the mymodule_form_view() function, I put the below code,

<?php
function mymodule_form_view()
  $form_state['redirect'] = 'http://localhost/d7/?q=node/3';
?>

To my surprise, Thhe function gets called but its not redirected..! and shows errors that some of the form fields with #reuired attribute haven't been filled out..! I tried using drupal_goto()function, it redirects to the other page properly but even in the redirected page those, "required" errors show up..!!

I even tried making #required attributes FALSE, inside the mymodule_form_view()and yet it didn't work.

So how to solve this problem..??

Modifying $form_state requires passing it by reference to the function.

function mymodule_form_view(&$form, &$form_state) {
  $form_state['redirect'] = 'http://localhost/d7/?q=node/3';
}


Diferences between "mysqldump" and "backup and migrate module" I always make backup using "backup and migrate" module. But now, need to automate this process using scripts.

When execute backup using "backup and migrate" this module generate .mysql file with approximately 3.3 MB(compacted) and 9MB(uncompacted) , but using the following script command, file have 17MB(compacted) and 53MB+(uncompacted) and .sql extension.

mysqldump -u user_mysql -pMY_PASS  --databases my_database | gzip > /home/my_user/my_docs/database.sql.gz

How generate ".mysql" extension file using  "mysqldump"?

My hosting is a non dedicated version, so, I don't install drush.
But I found a good solution. In config BAM (/admin/config/system/backup_migrate) have an tab "Schedules". In this option u can add backup schedule. Excellent solution, because winscp script (my script backup hosting) will get .mysql.gz generated in BAM private folder automatically. Additionally, about file size backup, BAM really exclude some data tables. This option is personalizable in "/admin/config/system/backup_migrate/profile/list/edit/default", "DEFAULT DATABASE BACKUP OPTIONS" option "Exclude the data from the following tables".


Update Drupal core from a low version I have to update a website from 7.14 to 7.31.

I feel like this contains a lot of risks. As anyone updated so many versions? What are your recommendations ?

I figured it would be better to update version per version instead of applying the 7.31 update right away.
I made sure the core was not modified.

Thanks,

As long as core is not modified in any way, there should be no risks of updating it straight from 7.14 to 7.31. It will apply all database updates from each version in between. There's literally no difference in doing it one version at a time compared to doing it straight to 7.31.

But as always, test it in a development environment before doing it in production and always make backups.


How can I defer parsing of Javascript on my Drupal 7 site? I am working on some performance issues for a site I launched recently.  Looking at Google's PageSpeed insights I see that High priority on the list is Defer parsing of Javascript. Here is a link:

https://developers.google.com/speed/pagespeed/insights#url=http_3A_2F_2Fwww.gastonia.com_2F&mobile=false&rule=DeferParsingJavaScript

Wow, over 1 MB of Javascript to parse!! Notice that most of these are from the facebook app (maybe the answers is to remove the fb app, ha!)

Has anyone successfully deferred this in Drupal?  I have tried using script defer="defer", and Google gives suggestions like "add script tags in comments and then eval() them, but they give no examples and I am having trouble finding a good tutorial.  Any resources or direction is appreciated!

On a side note, if you see anything else in that list that is easily overcomable by drupal, please add a comment. The site in question is http://www.gastonia.com in case you wanted to look at the source code.

Given that nearly everything in Javascript for Drupal is triggered by a $(document).ready() in jQuery, I don't see any real advantage to using defer.  In fact, I recently had a real headache1 from some code I inherited that mixed the two.

One recommendation (I think YSlow suggests it) that you can do is to move scripts to the end, right before the closing </body>.  This would mean moving the <?php print $scripts; ?> in your html.tpl.php.  While not deferring the parsing, it does delay the loading so your page renders out quicker, and I have never had any problems in Drupal doing this.

If you do want to add the defer, you need to implement hook_js_alter:

function mymodule_js_alter (&$javascript)
{
  $javascript['misc/drupal.js']['defer'] = TRUE;
}

If you want to defer everything, you could try

function mymodule_js_alter (&$javascript)
{
  foreach ($javascript as $key => $value) {
    $javascript[$key]['defer'] = TRUE;
  }
}

Otherwise, most of the normal Pagespeed fixes don't have much to do with Drupal itself.  As long as you deploy with JS and CSS aggregation enabled you should be good.  Configure Apache to use compressed responses and decent cache lifetimes and I don't think PageSpeed will complain about much and give you all A's and B's.


Aggregating but not taking the first result I have a set of profiles, and some users have two of the same type.

Well one of the views gets around these duplicate profiles by aggregating them. The problem is that it grabs the first of the two duplicates.

Provided that programmatically removing the extra member profiles isn't really feasible, is there a way to grab the second of the two duplicates?

A sample of the query is here:

select DISTINCT p.pid, p.type, p.uid, u.name from profile as p
join users as u on (u.uid = p.uid)
where p.type = "member"
group by u.uid
order by p.uid, p.pid DESC

You can use the Views Field View module, like so:

Create a view "user profile" master (not page)

use contextual filter user UID
In the pager: Display a specified number of items : 1 item and set offset to 1

Create the main view

add global field view
use user uid as a contextual filter

The problem with this is that if user have only one profile then you may encounter a problem but maybe you can change it
for more detail on how to create view inside view check Drupal Views Inside Other Views.


Approach to custom advanced search box I have a custom search form, made with Drupal Form API. It uses ajax, autocomplete, and some other properties defined in the built $form.

I use the data sent from the form to feed a views_embed_view call, and in the View I have defined some contextual filters, for each and every of the input boxes.

The problem is that Contextual filters do not apparently support the operator LIKE for several word or partial word matches, so the search is very restricted. Even putting Search field instead of Content field does not solve the problem completely.

If I use Exposed filters instead of Contextual filters, I don't know how to modify the input boxes to get all the functionality I already have. Maybe with hook_form_alter, but even so I do not know what to do with the sent data (it needs further PHP processing, this is why it was so convenient with Contextual filters).

I also found this piece of code I had already used (but forgotten), but I don't find the solution elegant (even if it works - it is taken from a different Drupal Answers question and adapted. It modifies the Contextual filter query and includes the LIKE operator):

function mymodule_views_query_alter(&$view, &$query) {
if( $view->name == "products_list" ){
    foreach($query->where as $key => $val) {
        $field = $val['conditions'][0]['field'];
        $operator = $val['conditions'][0]['operator'];
        $value = $val['conditions'][0]['value'];
        if(( $field == 'field_data_field_field_rf_producto.field_field_producto_value' || $field == "field_data_field_descripcion_producto.field_descripcion_producto_value") && $operator == '=') {
            $query->where[$key]['conditions'][0]['operator'] = 'LIKE';
            $query->where[$key]['conditions'][0]['value'] = '%' . $value . '%';
        } // if
    } // foreach
  } // if
} // function

You can programmatically change the filter configuration before executing the view:

$view_name    = 'my_view_name';
$display_name = 'my_display_name';
$handler_name = 'title';
$terms        = array('foo', 'bar');

$view = views_get_view($view_name);
$view->set_display($display_name);

$handler = $view->display_handler->get_handler('filter', $handler_name);
$handler->value = implode(' ', $terms);

$output = $view->preview();

This will work even without exposing the filter.


Is there a way to tell a browser to not cache a particular custom page? A custom module I'm building has a page callback that creates and Inbox listing. When a user clicks an item in the inbox, another page callback displays the message, and it updates the database to record that it's been read.

The problem is that when the user presses Back, they get back to their local cache of the inbox which suggests it has not been read. If they reload, it's OK.

Is there a way (in hook_menu?) to flag that a page should not be cached/expires immediately?

If I understand your expectation correctly, it's less of a Drupal and more of a browser thing. When the user presses the Back button, if you don't want the browser to show a copy of the web page that it might already have, the Cache-Control header in your initial response must have no-store. Drupal by default, doesn't have this. You can confirm this by checking the definition of this function.

Simply overwriting the Cache-Control header seems to fix this on Opera 16, Firefox 23 and Chrome 30. However, on Safari 6, it doesn't. Turns out that it might be a known issue. So, we might have to turn to a Javascript hack for that.

In summary, including the snippet below in your page callback should do the trick for you. I have assumed Drupal 7.

// Add no-store in Cache-Control.
drupal_add_http_header(
  'Cache-Control',
  'no-store, no-cache, must-revalidate, post-check=0, pre-check=0',
  FALSE
);
// Hack for Safari
drupal_add_js('jQuery(window).unload(function(){});', array('type' => 'inline'));

This seems to work on a fresh Drupal 7.22 install for an authenticated user. If the page in question has been asked to be stored in the Drupal cache or if you are using a contributed module that also messes with the response headers, this might not work as is for you.

Useful References

https://stackoverflow.com/questions/866822/why-both-no-cache-and-no-store-should-be-used-in-http-response
http://madhatted.com/2013/6/16/you-do-not-understand-browser-history
https://developer.mozilla.org/en-US/docs/HTTP_Caching_FAQ
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
https://drupal.org/node/197786#comment-1055633


Form Validation: Let the comma as separator to be valid in integer field input I'd like to let my users use separator (Comma) while entering values in an integer field such as price for instance.

I know that we can alter the validation of fields with element_validate_integer API, but seems like that I can't get it working.

I appreciate any helps, thanks.

Also note that I'm using Clientside Validation module as well.

If you have integer (or Big int) field you can't submit data with , in integer field and this means that you should strip all , before data passed to Drupal default form submit handler ( as you know before data passed to submit it must be  validated first ) So  the tiny and quick solution is  you set a custom  validate handler  that  called before Drupal node validation handler then in there try to strip all , ( manipulate data in your custom validation handler ) and then enjoy it.

 // in your custom module

function yourmodule_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == 'your_form_id' ) {
                array_unshift($form['#validate'], '_mycustom_validate_handler');
}
}

function _mycustom_validate_handler($form, &$form_state)
{
$form_state['values']['your_integer_field']['und'][0]['value'] =strtr($form_state['values']['your_integer_field']['und'][0]['value'] , ',' ,'');
}

And if you also  want save , in database(!!!) try text field instead using integer field  and then with client side validation  Regex  Rule validate what you want.


How can I be sure configuration is never changed on live system? The documentation for the Drupal 8 configuration manager says:

  Making configuration changes on a live site is not recommended.

When managing a site used by dozens of content managers, how can I make sure that this really never happens? Is there a way to prevent this with permission settings? For me it's still not really clear which permissions to set, to make sure those users are never able to change the configuration.

One option is to use https://www.drupal.org/project/config_readonly, it enforces that config writes can not happen on production.

So far, I haven't built/maintained a D8 site where that approach was practical. Most of our sites rely quite heavily on contact forms for example, with workflows where content managers create contact forms as well. And sometimes quick changes are necessary, e.g. for services and integrations.

One option to deal with that is to use a project like https://www.drupal.org/project/config_split, which allows to keep a part of configuration outside of git and not have it overwritten by deployments. So far, we just do a config export on production, commit that to the production branch and then merge the feature branches that we want to deploy. There's some risk for conflicts, but that doesn't happen often.

But sure, there are sites where it is critical that every change is reviewed and approved first, before it can be deployed, then something like config_readonly is useful. I wouldn't enforce it just because some d.o page says so, you need to figure out what works best for your site and workflows.


Get 404 for url specified in module.routing.yml I am new to Drupal and I got stuck with the problem that I don't know how to debug even:
I have made a simple module 'final', its structure:

Applications/MAMP/htdocs/drupal_dir_1/modules/final > ls
final.info.yml    final.routing.yml src

/Applications/MAMP/htdocs/drupal_dir_1/modules/final > ls src/Controller/
ExampleController.php

Files contents:

> cat final.info.yml
name: Final
type: module
description: This is an final module
core: 8.x⏎

> cat final.routing.yml
final.content:
  path: '/final'
  defaults:
    _controller: '\Drupal\final\Controller\ExampleController::content'
    _title: 'Hello world bitch!'
  requirements:
    _permission: 'access content'

> cat src/Controller/ExampleController.php
<?php
namespace Drupal\final\Controller;
use Drupal\Core\Controller\ControllerBase;
class ExampleController extends ControllerBase {
  public function content() {
    $build = [
      '#markup' => $this->t('Hello World, bitch!'),
    ];
return $build;
  }
}

I believe you did not install the module

if you tried to install you would get

drush en final

  ParseError: syntax error, unexpected 'final' (T_FINAL), expecting identifier (T_STRING) in /home/giorgos/share/gwebsites/dru8.dev/web/modules/custom/final/src/Controller/ExampleController.php on line 2 #0 /home/giorgos/share/gwebsites/dru8.dev/vendor/composer/ClassLoader.php(322): Composer\Autoload\includeFile('/home/giorgos/s...')
   #1 [internal function]: Composer\Autoload\ClassLoader->loadClass('Drupal\final\Co...')
  ...

final is reserved keyword thus it confuses the php parser when it sees

namespace Drupal\final\Controller;

Can also be caught with my vscode setup and linter

You have to change final to something else but then you have to rename it elsewhere in your module (folder name, file names, reference to the class etc)

Otherwise the module is working fine.


Possible to make image styles (thumbnails) public while original images are kept private in D7? I love the fact that D7 allows you to choose whether files should be stored in the public or private file system on a per-field basis.

But here's my question: is it possible to have image files that are stored in the private file system, while thumbnails etc. created via image styles are stored in the public file system, so anyone can access them? In other words, I want to protect the original image files, but not their thumbnails.

By default theme_image_style seems to place the generated styles in the same file system (public or private) as the original image, and I don't see any arguments to change that...

What about creating 2 fields ? One for storing the thumbnail and let it "public". The other one for storing the original image, mark it as "private" and define a permission for it using field permissions module ?

Edit Oct, 26: let's add some code :)
So if your confortable with creating a module, here are the instructions.
Create 2 fields: field_img_public and field_img_private, one will be on the public filesystem, the other on the private.

Then create a module to store this hook_node_presave():

function MYMODULE_node_presave($node) {
  //Retrieve the file object from the public image.
  $fid_items = field_get_items('node', $node, 'field_img_public');
  $fid = $fid_items[0]['fid'];
  $img_public = file_load($fid);

  //Create the private path.
  $img_private_path = str_replace('public://', 'private://', $img_public->uri);
  $private_dir = pathinfo($img_private_path,  PATHINFO_DIRNAME);

  //Verify if the private folder exists.
  file_prepare_directory($private_dir, FILE_CREATE_DIRECTORY);

  //Copy the image
  $img_private = file_copy($img_public, $img_private_path, FILE_EXISTS_RENAME);

  //Save the resulting file object.
  $node->field_img_private['und'][0] = (array)$img_private;
}

Then you just upload the public image and the private get populated.


field_attach_form removes image field default value when submit I need to get some fields of a node edit form, for that purpose I use field_attach_form() to get the fields that I want with the value of the node.

Here's an example of the code of my form function:

function my_form($form, &$form_state, $node_id, $fields) {
  $node = node_load($node_id);
  $node_form = $form;
  field_attach_form('node', $node, $node_form, $form_state);

  foreach ($fields as $field) {
    if ($field->show) {
      $form[$field->name] = array('#type' => 'fieldset', '#title' => t('Field'), '#tree' => TRUE,);
      $form[$field->name]['override'] = array('#type' => 'checkbox', '#title' => t('Override'),);
      $form[$field->name][$field->name] = $node_form[$field->name];
      $form[$field->name][$field->name]['#states'] = array(
        'enabled' => array(
          ':input[name="' . $field->name . '[override]"]' => array('checked' => TRUE)
        ),
      );
    }
  }

  return $form;
}

I just wrap every field (that I want to show) in a fieldset with a checkbox.

One of the field is an image type, when field_attach_form loads the field, it shows the image thumbnail and the image file name perfectly, but when I click submit (without edit the field content) the value of the field is empty. In fact, the image field is required so the validation fails.

When I remove the previous image and upload a new one, it works perfectly. Am I missing something?

I found a workaround: I just have the fields twice, one enabled and the other disabled. With the checkbox I show one or another.

function my_form($form, &$form_state, $node_id, $fields) {
  $node = node_load($node_id);
  $node_form = $form;
  field_attach_form('node', $node, $node_form, $form_state);

  foreach ($fields as $field) {
    if ($field->show) {
      $form[$field->name] = array('#type' => 'fieldset', '#title' => t('Field'), '#tree' => TRUE,);

      $form[$field->name]['override'] = array('#type' => 'checkbox', '#title' => t('Override'),);

      $form[$field->name][$field->name] = $node_form[$field->name];
      $form[$field->name][$field->name]['#states'] = array(
        'visible' => array(
          ':input[name="' . $field->name . '[override]"]' => array('checked' => TRUE)
        ),
      );

      $form[$field->name][$field->name . 'disabled'] = $node_form[$field->name];
      $form[$field->name][$field->name . 'disabled']['#disabled'] = TRUE;
      $form[$field->name][$field->name . 'disabled']['#states'] = array(
        'visible' => array(
          ':input[name="' . $field->name . '[override]"]' => array('checked' => FALSE)
        ),
      );
    }
  }

  return $form;
}

It seems that the action enabled / disabled is buggy.


Calendar View of Events shows 1st of month in header I would like my Calendar Page View of Events to show "August 2014" (or whatever the current month is) as the heading instead of showing "Friday, August 1, 2014" (see attached pic). Is there a configuration setting for this please? I have looked at various YouTube vids and it shows the date how I want, but I cant seem to figure out how they are doing it? .

Here's the fix, the reference to it is here : click on this link and scroll down to item #20 : drupal.org/node/2294973 , however its pasted below just in case that link becomes broken...

Quick workaround for people unable to apply the patch:

STEP 1: Edit date_views/theme/theme.inc and go find line 165.

Change these two lines:

$format_with_year = variable_get('date_views_' . $granularity . 'format_with_year', 'l, F j, Y');
$format_without_year = variable_get('date_views_' . $granularity . 'format_without_year', 'l, F j');

To these two lines:

$format_with_year = variable_get('date_views_' . $granularity . '_format_with_year', 'l, F j, Y');
$format_without_year = variable_get('date_views_' . $granularity . '_format_without_year', 'l, F j');

Note: the only difference is one underscore character added to each line.

Upload the changed file back to your web server.

STEP 2: Go to (YOUR_WEBSITE)/admin/config/regional/date-time/date-views and click Save. If you get permissions errors, try clearing caches.


why drupal webform form setting shows mysql errors in dblog? I have created one webform in Drupal 7 in which some form components are present. But when I'm going to view that webform the components(fields) are not displayed. Then I checked in form setting that form was closed but when I'm going to change the form setting to open and saving that form I'm getting error "The website encountered an unexpected error. Please try again later". Then in dblog there was the following mysql error.

  PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062
  Duplicate entry '39055' for key 1: INSERT INTO {webform} (nid,
  confirmation, confirmation_format, redirect_url, status, block,
  teaser, allow_draft, auto_save, submit_notice, submit_text,
  submit_limit, submit_interval, total_submit_limit,
  total_submit_interval) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2,
  :db_insert_placeholder_3, :db_insert_placeholder_4,
  :db_insert_placeholder_5, :db_insert_placeholder_6,
  :db_insert_placeholder_7, :db_insert_placeholder_8,
  :db_insert_placeholder_9, :db_insert_placeholder_10,
  :db_insert_placeholder_11, :db_insert_placeholder_12,
  :db_insert_placeholder_13, :db_insert_placeholder_14); Array (
  [:db_insert_placeholder_0] => 39055 [:db_insert_placeholder_1] =>
  [:db_insert_placeholder_2] => full_html [:db_insert_placeholder_3] =>
  [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => 0
  [:db_insert_placeholder_6] => 0 [:db_insert_placeholder_7] => 0
  [:db_insert_placeholder_8] => 0 [:db_insert_placeholder_9] => 0
  [:db_insert_placeholder_10] => [:db_insert_placeholder_11] => -1
  [:db_insert_placeholder_12] => -1 [:db_insert_placeholder_13] => -1
  [:db_insert_placeholder_14] => -1 ) in drupal_write_record() (line
  7194 of /home/indiawaterportal/public_html/includes/common.inc).

Please help me to solve this issue.

INSERT INTO {webform} (nid...

tries to insert the nid of the webform (got from auto-increment in the node table) in the {webform} table. So, every nid inserted in nid column of webform table should be unique. But it seems that the newly-created webform node got a nid that already exists in webform's nid column.

So I guess there's something wrong. Find that nid in webform table, see if it exists in node table, that must be the trick.


Assigning new region in a display suite layout does not show contents placed inside newly created region // rmch-content-2.tpl.php
<?php
/**
 * @file
 * Display Suite RMCH Two Column Header template.
 *
 * Available variables:
 *
 * Layout:
 * - $classes: String of classes that can be used to style this layout.
 * - $contextual_links: Renderable array of contextual links.
 * - $layout_wrapper: wrapper surrounding the layout.
 *
 * Regions:
 *
 * - $header: Rendered content for the "Header" region.
 * - $header_classes: String of classes that can be used to style the "Header" region.
 *
 * - $left: Rendered content for the "Left" region.
 * - $left_classes: String of classes that can be used to style the "Left" region.
 *
 * - $right: Rendered content for the "Right" region.
 * - $right_classes: String of classes that can be used to style the "Right" region.
 */
?>
<<?php print $layout_wrapper; print $layout_attributes; ?> class="<?php print $classes;?> clearfix">

  <?php if (isset($title_suffix['contextual_links'])): ?>
    <?php print render($title_suffix['contextual_links']); ?>
  <?php endif; ?>

      <<?php print $content_left_wrapper; ?> class="ds-content-left <?php print $content_left_classes; ?>">
        <?php print $content_left; ?>
      </<?php print $content_left_wrapper; ?>>

      <<?php print $content_right_wrapper; ?> class="ds-content-right <?php print $content_right_classes; ?>">
        <?php print $content_right; ?>
      </<?php print $content_right_wrapper; ?>>

   <<?php print $content_right_wrapper; ?> class="ds-content-footer <?php print $content_footer_classes; ?>">
        <?php print $content_footer; ?>
   </<?php print $content_right_wrapper; ?>>

      <?php print render(block_get_blocks_by_region('page_links')); ?>

</<?php print $layout_wrapper ?>>

<?php if (!empty($drupal_render_children)): ?>
  <?php print $drupal_render_children ?>
<?php endif; ?>

So I have added new footer region in the .inc for the layout
    rmch_content_2.inc

/**
 * @file
 * Display Suite RMCH Header 2 col, Content 2 col
 */

function ds_rmch_content_2() {
  return array(
    'label' => t('RMCH Content 2 col'),
    'regions' => array(
      'content_left' => t('Content Left'),
      'content_right' => t('Content Right'),
      'footer' => t('Footer'),
    ),
    // Uncomment if you want to include a CSS file for this layout (rmch_two_column_header.css)
    'css' => FALSE,
    // Uncomment if you want to include a preview for this layout (rmch_two_column_header.png)
    'image' => TRUE,
  );
}

I have added new region footer which is visible in the screenshot and added Links field inside Footer
When I add Links field in the Content Left , it displays links but when I add  it in the footer it does not show up and the variable
print $content_footer; inside tpl.php file turns out to be empty completely.
What should I do the make sure blocks or fields added inside newly created regions show up.?

You've made a footer definition but printing $content_footer. Try printing $footer or changing the name of the region to be consistent with the others (content_). Clear cache to see your changes.


Group search results by content type and limit count I am trying to group search results by its content type. Also, I want to show not more than 4 results per content type.

For an assumption, it should look like this:
Content type1-
  Result1
  Result2
  Result3
  Result4
Content type2-
  Result5
  Result6
...

I am able to achieve this using TEMPLATE_preprocess_search_results().

function custom_preprocess_search_results(&$variables) {
  $variables['search_results'] = '';
  $resultTypes = array();

  // Divide results
  foreach ($variables['results'] as $result) {
    $resultTypes[$result['bundle']][] = $result;
  }

  // Create fieldsets
  foreach ($resultTypes as $resultType => $resultTypeResults) {
    $value = '';
    $i = 0;

    foreach ($resultTypeResults as $result) {
      $value .= theme('search_result', array('result' => $result, 'module' => $variables['module']));
      $i++;
      if ($i == 4) {
        $value .= l(t('Show more'), current_path(), array('query' => array()));
        break;
      }
    }

  $variables['search_results'] .= theme('fieldset', array('element' => array('#title' => $resultType, '#children' => $value));
  }
}

But this is not an optimal method, since I trimmed down the results per content type (but actually they exist). Say if Content type1 has 10 actual results and Solr's maximum results per page is set to 10, then I will end up showing first 4 results of only Content type1.

Please suggest an ideal method to list 'n' matched results of every content type.

Thanks!

You can increase the page limit by apache solr hook

function custom_apachesolr_query_alter($query) {
  if(strpos($_SERVER['REQUEST_URI'],'/bundle/') == false)
    {
  $query->replaceParam('rows', '400'); // Note that high value increases response time
  }
}


How to send watchdog logs to email? I want Drupal send me watchdog logs by emails.
I found Logging and alerts 7.x.
But it sends every alert/warning etc. log in a seperate email.
But i want it to gather that entries and send emails.
For example 50-60 entry in an email.

Is it possible by using these settings in that module:
 - Maximum number of allowed consecutive similar email alerts
 - Email alerts should be considered "consecutive" if sent within

Or should i use something else?
Thank you

Create a module that implements hook_watchdog(). You could have your own cache of log entries and send a digest of them once a day, or whatever policy you like.


How to add breadcrumbs for view page? I have added content type breadcrumbs, but I don't know how to add view's breadcrumbs

You can achieve your requirement by installing any of the below modules:

Custom Breadcrumbs

  Many new features have been added including support for Views, Panels,
  Taxonomy vocabularies and terms, paths, and a simple API that allows
  contributed modules to enable custom breadcrumbs for module pages and
  theme templates. These are implemented using optional, independent
  submodules that depend on the main Custom Breadcrumbs module.

Path Breadcrumbs

  This module is a solution for all problems with the breadcrumbs on
  your site! Path Breadcrumbs module helps you to create breadcrumbs for
  any page with any selection rules and load any entity from the URL!

You can also follow this link.


D7 - Calling Form Into User Page We are trying to create a single page that has all the available user related forms available without have to click between pages.

We have been able to render some forms, like change password, but we are trying to include other forms rendered outside of the user module.

Specifically having trouble with rendering commerce_addressbook existing values and the 'add new address form'.
https://www.drupal.org/project/commerce_addressbook

Could anyone please outline the correct way to do this?

What you will want to do is add a preprocess hook to the theme for the user page, and inject some new variables to the template.

Example:

In template.php:

$variables['address_form'] = drupal_get_form('form_id', $arg1, $arg2, $arg3...);

In your template tpl:

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

You will need to know the form id of the forms you want to call. The optional second argument to drupal_get_form will pass those arguments to the form, like say, user object, or user id. Each form will have their own requirements; some don't need any additional arguments at all.


Add new images to existing nodes I am using imagefield to make photo albums. Now I want to allow all registered users to upload new images to any photo albums and it should get added to the exisiting album. I do not want to give them permission to edit the node. How can I do this?

You'll likely have to change what you mean by "edit the node". You could use Field Permissions to restrict what they're able to change when editing the node.

But to truly accomplish this without letting them "edit the node", you'll need a very complex custom solution that would be unreasonably complicated for an answer on this site.


How do I add a template suggestion for a node based on the current view? I have a view that lists a bunch of nodes of a certain content type. I want to style this list of nodes in a way that I can't do easily with the standard node.tpl.php that they're being rendered with. I'm trying to override my themename_preprocess_node function to add a template suggestion depending on what view the nodes were called from. I tried this:

<?php
  function themename_preprocess_node(&$variables)
  {
    // Add theming based on view name. If the view is named
    // 'featurefront' one of the template suggestions will be
    // 'node-view--featurefront.tpl.php'.
    if (isset($variables['view']))
    {
       $variables['theme_hook_suggestions'][] = 'node_view__'.
            str_replace('_', '--', $variables['view']->name);
    }
  }
?>

but it doesn't work because $variables['view'] isn't ever set anywhere. Basically my question comes down to this:

What variable can theme_preprocess_node use that will tell it the name of the current view or whether it was called from a view at all?

You can leverage the views_get_current_view() function to get the current view being rendered.  I haven't tested the code below, but it should get you close to what you are trying to do.  Note that it could have unintended consequences if nodes are being rendered somewhere else on the page.

function themename_preprocess_node(&$variables)  {
  if (($view = views_get_current_view()) && 'featurefront' == $view->name) {
    $variables['theme_hook_suggestions'][] = 'node_view__' . $view->name;
  }
}

Views doesn't set template variables for nodes, which is why the technique above has to be leveraged.


Problem installing REST Server module When I attempt to enable the REST Server module, I get the following error message:

  A library is missing for rest_server to work (Currently using Missing library Please download spyc and create a file called spyc.php in rest_server/lib)

The spyc.php file is included with the module in the rest_server/lib directory, but the error is still reported, and prevents the module from being enabled.

Drupal version: 6.22

Rest Server module version: 6.x-2.0-beta3

I reported the issue on the module page.

Just wondering if you see any patterns that could help me debug this issue.

Download spyc from http://code.google.com/p/spyc/. Inside the spyc folder find the file called spyc.php and copy it to the Services Module 'servers/rest_server/lib/' directory.


Node Acess User Reference and Organic Groups permissions I am using Organic Groups to give group-specific content to users.

The groups' permissions do not allow simple group members to edit group content.

By using the Node Acess User Reference module I wanted to grant permission to specific group members to edit specific nodes on an ad-hoc basis.

The devel information that I get is that allthough that rule works, it is being overriden by OG's permissions thus still not allowing the user to edit the node.

Nevermind, http://drupal.org/node/1171834#comment-6019078 answers it.


How do I skip language selection with installation profile? I am building an installation profile for Drupal 7 and trying to skip the language selection page.

In the .profile file I put the following code:

function efocus_install_tasks_alter(&$tasks, $install_state){
    $tasks['install_select_locale']['run'] = INSTALL_TASK_SKIP;
    $install_state['parameters']['locale'] = 'en';
}

This skips the page but apperantly the locale selection is not working for some reason. Anybody that has any experience with this? I am quite new to Drupal, just started a month ago and can't figure out why it is not working. Any tips on what I can try?

This cannot work, because $install_state is passed as value, not as reference. So changing it has no effects.

function efocus_install_tasks_alter(&$tasks, $install_state){
    $tasks['install_select_locale']['function'] = '_efocus_locale_selection';
}

// local callback function
function _efocus_locale_selection(&$install_state){
    $install_state['parameters']['locale'] = 'en';
}

This one works. I am simply replacing the standard_locale_selection with a custom function, which gets the install_state passed as reference. So i can change the value...


How can I move the modules that are dependencies for a module of mine in another directory? I want to create a custom module with 2 dependencies. My module will be in sites/all/modules, and I need its dependencies to be in /modules/contrib.

How can I move the dependencies? I don't need any Drush command. It must be done using the browser only.

Drupal 7 doesn't look for modules on /modules. The list of directories looked for modules by drupal_system_listing() is the following one.

profiles/$profile/modules and its sub-directories, where $profile is the short name of the profile currently installed
sites/all/modules  and its sub-directories
$config/modules and its sub-directories, where $config is the directory containing the settings.php file used for the site

All those directories are relative to the directory containing Drupal, so a directory like /modules will never be checked for any module.

Actually, there isn't any need for a module to look for a specific directory for its dependencies. If the dependencies are modules that comes as sub-modules of the main module, they are normally put in the modules directory of the directory containing the main module, but the main module doesn't normally force Drupal to look in a specific directory for its own sub-modules.

Instead of /modules/contrib, you can use sites/all/modules/contrib, or sites/$site_directory/modules/contrib. Those are directory where Drupal looks for modules.

There isn't any way to move a module from browser, and it is normally not necessary. You put the files with FTP or SSH, and you put the modules in the correct directory before installing the module using them.
If you already have your module installed, you disable it, disable its dependencies, move its dependencies in the correct directory (one that Drupal checks), enable them, and enable the module using them. If disabling/enabling doesn't work, you simply uninstall/install the modules.


Moving module location I have a test module located under site/all/modules/custom.
First, I did uninstalled the module, cleared cache.
then , I did moved the test module to modules/custom folder which is a new
location to put Drupal 8 module.

After that, I have enabled the test module, then Clear All Caches.
Now, Drupal 8 keeps says can not find the test module under old location (site/all/modules/custom).

I thought Drupal 8 probably stored path in a DB table, but i am unable to find the table.
Can any one tell a solution about How to fix above problem?

You can do this without uninstalling, but it takes some fiddling:

Move the module in filesystem
invoke drush ev "drupal_flush_all_caches();"
invoke drush cr

The crucial setting is the entry system.module.files in key_value database table. If you move the module(s), the try to run drush cr directly, it may fail because drush tries a full bootstrap and fails to locate the required files.

drush ev does an error-free bootstrap using drush_bootstrap_max(), and drupal_flush_all_caches rebuilds system.module.files config without trying (and failing) to load the moved files. Whereas drush cr does a full-site bootstrap, which causes drush to halt on any errors.


views exposed filter: Prevent a user from searching default Paceholder Text i have been looking for a solution all day, i need some help. I created a single search box using views combine exposed filters. i am using bartik theme. On the exposed filter, i have added some default text using the following code in my template.php file as per this code snippet:

function bartik_form_views_exposed_form_alter(&$form, &$form_state) {
  if (!isset($form_state['view']->exposed_input['combine'])) {
    // OK to set the default value
    $form_state['input']['combine'] = 'Find Professionals';
  }
}

So far, my default text is showing, but i need to achieve 2 things:

Make default text to disappear when user clicks on the search box
Prevent user from searching default text.

ps: "combine" is the name of my views exposed filter, while "views_exposed_form" is the form id.

Thanks for your help in achieving this.

@Bala You actually pointed me in the right direction by mentioning "placeholder", I have also added that word to the question, Thanks for the help, so i did more research since i wanted to avoid enabling 2 modules because of only one exposed filter (i have many modules enabled already), so adding this code to my theme's template.php file as per this comment worked perfectly for me:

<?php
function yourtheme_form_alter(&$form, &$form_state, $form_id){
  if($form_id == "views_exposed_form"){
    if (isset($form['combine'])) {
            $form['combine']['#attributes'] = array('placeholder' => array(t('Find Professionals')));
    }
  }
}
?>

For benefit of novices, "yourtheme" in the function should be replaced with the name of your theme, 'combine' is the name of my exposed filter (You Can find yours by right-clicking the form on firefox or google chrome and clicking "inspect element").

This solution works for drupal 7


How to see the results of my first module I created a module to alter the query executed by a view, but i cannot figure it out how to test it ...  I mean where should i see the results ?
I've created the following files:

my_module.info
my_module.module
my_module.views.inc

in the second file i have:

function my_module_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'my_module'),
    'template path' => drupal_get_path('module', 'my_module'),
  );
}

and in the third one:

function my_module_hook_views_query_alter(&$view, &$query)  {
  var_dump($view);
}

Where should i be able to see the result of var_dump ?

hook_views_query_alter() is supposed to alter the query passed as second parameter, or the view object passed as first argument, not to output anything. If you want to debug the hook, you should use code similar to the following one.

watchdog('my_module', 'View: @view', array('@view' => print_r($view, TRUE)), WATCHDOG_DEBUG);

The name you gave to your hook is wrong: You just need to replace hook with the short name of your module. For a hook like hook_views_query_alter(), the function name is not my_module_hook_views_query_alter(), but my_module_views_query_alter().


Get data and uploaded files from android (mobile) version of website I built a website and it works well in browser. We need to create android version of this website, and in this version users must be able to log in to the site and upload images in their profile.

I really have no idea how Drupal does this and how can I let that android software to connect to my website, upload images and data. I would be appreciated for any help.

thanks.

YOu need to provide services using RESTful API to mobile app developer. Required modules are services, services definition and rest server through it you can connect to mobile application because it returns json or xml. Thorugh our site endpoint. Further you can go to its tutorial here.


How can I change a form input to not be required? I want to change a form from required = True to False

<input data-drupal-selector="edit-attributes-alt" type="text" id="edit-attributes-alt--SMq1dTLhZG8" name="attributes[alt]" value="" size="60" maxlength="2048" placeholder="" class="form-text required" required="required" aria-required="true">

I thought that using form alter is the right thing to do but how can i use the $form_id if keeps changing ?

Here is my code :

<?php

use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

function alt_not_required_form_alter(array &$form, FormStateInterface $form_state, $data_drupal_selector) {
  if ($form_id == 'edit-attributes-alt--????') {
    $form['postal'] = array(
      // Don't make this field required. Use the validate hook.
      '#required' => FALSE,
    );
  }
}

The third argument to hook_form_alter is $form_id - which will hold the id of the form, not an attribute. You need to know the form id of what you are trying to alter, which is not the literal id of a form input field.

Once you identify what form is showing this field, you can do:

function alt_not_required_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'form_id_foo') {
    $form['input_to_affect']['#required'] = FALSE;
  }
}

Also, once you know what the form ID is, you can use hook_form_FORM_ID_alter and eliminate that if statement.

Plus, in your example, since we are altering existing form elements, you do not need to declare it as an array. You just access its properties. $form['postal'] = array(...) would take any existing form item named 'postal' and obliterate it, which will likely cause errors in validation or submission.

It might be helpful in learning to use xdebug or devel to dump arguments and variables so you can see what they are. Otherwise, it will be difficult for you to step through this.


Taxonomy Sidebar view with Nodes I'm building a sidebar for my taxonomy and node pages.

I've got it as

Show (View Setup): Taxonomy Terms
Unformatted List
Show: Fields
Relationship: Taxonomy term: Representative node

Fields:

Taxonomy term: Name
(Representative node) Content: Title

This works pretty well, each row starts with the taxonomy term name as a link and is followed by a node from that term. The trouble is, it'll only show the first node. How do I get it to display all nodes?

The Representative node relationship will show you a single representative node for your term, so that's not what you need in this case. Instead, try this:

Relationship: Taxonomy term: Content with term

Your results will now look like this:

Term A

Node 1

Term A

Node 2

Term B

Node 3 etc

Assuming this is not what you want, you can next add some grouping like this:

Under Format: settings set Grouping field Nr. 1 to Taxonomy term: Name.
Finally, in Fields, set the Taxonomy term: Name field to Exclude from display. Now you should have a list of node titles grouped by taxonomy term.


Rendering contact_form I have call my current contactform with this function in mytheme.theme.

$form = Drupal::routeMatch()->getParameter('contact_form');

I have this

object(Drupal\contact\Entity\ContactForm)#412 (23) {
  ["id":protected]=>
  string(8) "feedback"
  ["label":protected]=>
  string(14) "Nous contacter"
  ["recipients":protected]=>
  array(1) {
    [0]=>
    string(21) "mymail@gmail.com"
  }
  ["reply":protected]=>
  string(0) ""
  ["weight":protected]=>
  int(0)
  ["originalId":protected]=>
  string(8) "feedback"
  ["pluginConfigKey":protected]=>
  NULL
  ["status":protected]=>
  bool(true)
  ["uuid":protected]=>
  string(36) "6e997e8b-9d85-4e59-9e43-67004270fe13"
  ["isSyncing":"Drupal\Core\Config\Entity\ConfigEntityBase":private]=>
  bool(false)
  ["isUninstalling":"Drupal\Core\Config\Entity\ConfigEntityBase":private]=>
  bool(false)
  ["langcode":protected]=>
  string(2) "fr"
  ["third_party_settings":protected]=>
  array(0) {
  }
  ["_core":protected]=>
  array(0) {
  }
  ["trustedData":protected]=>
  bool(false)
  ["entityTypeId":protected]=>
  string(12) "contact_form"
  ["enforceIsNew":protected]=>
  NULL
  ["typedData":protected]=>
  NULL
  ["cacheContexts":protected]=>
  array(1) {
    [0]=>
    string(28) "languages:language_interface"
  }
  ["cacheTags":protected]=>
  array(0) {
  }
  ["cacheMaxAge":protected]=>
  int(-1)
  ["_serviceIds":protected]=>
  array(0) {
  }
  ["dependencies":protected]=>
  array(0) {
  }
}

But how can I rendering this ? My goal is to render the current contact form.

Edit1: I have tried this How to programmatically render a contact form in a theme in D8

But when I try this

    $form = Drupal::routeMatch()->getParameter('contact_form');//get the current form called
    $message = \Drupal::entityManager()
      ->getStorage('contact_message')
      ->create(array(
        'contact_form' => $form->id(),
      ));
//$form->id() = 'feedback'
        $form = Drupal::service('entity.form_builder')->getForm($message);

I have a very big array (Firefox and Chrome crash when in print them )

When I try this

$form = Drupal::routeMatch()->getParameter('contact_form');//get the current form called
ContactController::contactSitePage($form);

I have this error

PHP Fatal error: Call to a member function getStorage() on null in /var/www/drupal8/core/modules/contact/src/Controller/ContactController.php on line 83

Why I would like to do this in my .theme file ?

Because I have begin to migrate a website in drupal 6 to drupal 8 .(I have try Drupal Upgrate and they works very good ) The page of this website has been built with a little home framework. It call many others not Drupal script. With this, not Drupal Script (Ex:tagada.com/horoscope.php ) and drupal page ( tagada.com/drupalpart/node/10) works with same css and html structure file in a external folder. In Drupal6 the theme worked correctly with a global variable object with node content $node

Finnaly I have find the answer to my problem's .

It was a drupal permission problem's .

User Anonymous users do not have permission to use the general contact form. I gave permission and everything worked .

Thank you alot for the advice .


Cannot get JQuery plugin working on Drupal 7 I am trying to run a Jquery plugin QTip. The problem is that it is not running even though all the files are in the corect folders (plugin is both in info file and attched as a script below) and I took the code below from the plugin's website and pasted in the html section of WYSYWIG editor. Can anyone tell me why this is the case?

Why this not working

From the Drupal 7 upgrade guide:

  Javascript should be made compatible with other libraries than jQuery
  by adding a small wrapper around your existing code:

(function ($) {
      // Original JavaScript code.
})(jQuery);

  The $ global will no longer refer to the jquery object. However, with
  this construction, the local variable $ will refer to jquery, allowing
  your code to access jQuery through $ anyway, while the code will not
  conflict with other libraries that use the $ global.

(function ($) {
  // Create the tooltips only on document load
  $(document).ready(function() {
    // By suppling no content attribute, the library uses each elements title attribute by default
    $('#content a[href]').qtip({
      // Simply use an HTML img tag within the HTML string
      content: 'dfdfdfdfdf'
    });
  });
})(jQuery);


HTML tags are counted in for the length of a teaser, instead of words? How to limit teaser length by words rather than characters?

Below is a very simple, but mostly complete, and un-tested text formatter with a setting for how many words to allow.

It's five different functions, that

Tell Drupal there is a new formatter.
Provide the "How many words? form.
Outputs the current setting from above in the display settings form
Limits the number of words in the current text field
Render the actual output

/*
 * Implements hook_field_formatter_info().
 */
function HOOK_field_formatter_info() {
  return array(
    'HOOK_limit_by_words' => array(
      'label' => t('Text limited by words'),
      'field types' => array('text'),
      'settings' => array('number_of_words' => 100),
    ),
  );
}

/*
 * Implements hook_field_formatter_settings_form().
 */
function HOOK_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $element = array(
    'HOOK_limit_by_words' => array(
      '#type' => 'textfield',
      '#title' => t('Number of words to use'),
      '#default_value' => $settings['HOOK_limit_by_words'],
    ),
  );

  return $element;
}

/*
 * Implements hook_field_formatter_settings_summary().
 */
function HOOK_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  return t('The current word limit is @wordlimit', array('@wordlimit' => $settings['HOOK_limit_by_words']));
}

function HOOK_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $element = array(
    0 => array(
      '#markup' => word_trim($items[0]['value'], $settings['HOOK_limit_by_words']);
    ),
  );

  return $element;
}

/**
 * Trim a string to a given number of words.
 * Thanks Lullabot.
 *
 * @param string $string
 *   the original string
 * @param int $count
 *   the word count
 * @param bool $ellipsis
 *   TRUE to add "..."
 *   or use a string to define other character
 *
 * @return string
 *   trimmed string with ellipsis added if it was truncated
 */
function word_trim($string, $count, $ellipsis = FALSE) {
  $words = explode(' ', $string);
  if (count($words) > $count) {
    array_splice($words, $count);
    $string = implode(' ', $words);
    if (is_string($ellipsis)) {
      $string .= $ellipsis;
    }
    elseif ($ellipsis) {
      $string .= '&hellip;';
    }
  }
  return $string;
}


Add a class the the form element (tag) of the search block form How do I add a class to the form element of the search block form?

I mean, add a class to this element:

<form action="/search/node" method="get" id="search-block-form" accept-charset="UTF-8" data-drupal-form-fields="edit-keys"></form>

I've tried:

function mytheme_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['#attributes'] = array('class' => array('abc'));
  }
}

and

function mytheme_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    $form['#attributes']['class'][] = 'abc';
  }
}

I've tried:

function mytheme_preprocess_form(&$variables) {
  if ($variables['element']['#form_id'] == 'search_block_form') {
    $variables['element']['#attributes'] = array('class' => array('xyz'));
  }
}

I've looked into altering core/modules/system/templates/form.html.twig, which does not look like the way to go.

I'm using the Bootstrap theme as my base.

you can use the prefix and suffix tag
like

$variables['element']= ['#prefix' => '
',
                        '#suffix' => '
']


how to make a field disabled, greyed out I found the hide() function to make a form field hidden. Is there a similar function for making a field disabled or greyed out? I want it to display but not allow it to be edited.

I am pretty sure you are looking for the #disabled property, eg the Form API Reference Disabled Property that...

  Disables (greys out) a form input element. Setting #disabled to TRUE results in user input being ignored, regardless of how the element is themed or whether JavaScript is used to change the control's attributes.


Is it possible to display a field value as part of Views title? I'm building a block in Views where different brands show off their respective products, now I'm wondering if it's possible to pass a field value to the title.

I know that %1 results in displaying the title

I've tried searching for a solution, but fail to find one as I'm not that familiar with the terminologies of Drupal (as in I don't really know what specifics to search for). This might be super simple, but I can't seem to find the answer and if possible it could become pretty useful in the future.

Changing a View's title is a theming issue. Have a look at Views: how to programmatically change Views title?. The accepted answer is almost what you need. Add the function to your theme's template.php file (or your custom module if you don't have a custom theme yet).

The rest is simply coding. Store the field that you need as a variable $my_field and adapt the code from the referenced answer as follows:

function MY_THEME_views_pre_render(&$view) {
  if ($view->name == 'YOUR_VIEW_NAME') {
    \\ Store your field: $my_field = ...
    $view->build_info['title'] = "YOUR TITLE" . $my_field;
  }
}

You can use the Devel module to inspect $view in order to easily find the correct code for $my_field.


How do I prevent a link on an overlay page from opening in another overlay page in Drupal 7? I have created a custom module that opens up a page in the admin overlay.  Upon going to that page, a PDF is generated and the link to the file is displayed on the page.  I created the link using l(), and gave the link a target attribute of '_blank' to open in a new tab/window.

l('Click here to download your PDF file.', $f_url, array('attributes' => array('target' => '_blank')))

The link looks like it is generated correctly.

Click here to download your PDF file.

When I click on it, it opens in a new window, but somehow the overlay fragment is tacked onto the end of the URL in the new window address bar, which appears as the following:  http://xxxx.com/sites/default/files/custom-pdf/xxxx_4.pdf#overlay-context=test.html.

The browser throws up a dialog box with a title of "Adobe PDF Document" and a message alert of "This operation is not allowed".

If I click this link from a non overlay page, it does exactly what it's supposed to do: Open the PDF in a new window.

I'm not exactly sure what's going on here.

How is the overlay fragment being appended to the URL, and how can I prevent it?

I was having the same issue.

There is a patch here.


Add a custom VBO action I want to add a custom VBO action.

It display in the actions list of the view, it should like a tree, like this:

-Add Role-

RoleA

RoleB

-Remove Role-

RoleA

RoleB

And When I select RoleA(-Remove Role-), check some users, click the submit.

The users checked should be removed RoleA.

How can I code a custom VBO action like this ?

You can create custom VBO action by implementing hook_action_info() hook. Here are some useful links which can help you achieve what you want:

Views Bulk Operations development guide (Drupal 7)

Programmatically adding and removing roles to users in Drupal
HOWTO assign a user to a role programatically

additionally, Examples module can help you to learn about Actions.


Drupal's built-in xss filters vs. HTML purifier module Does the  htmlpurifier module for Drupal provide better security against xss (and possibly other vulnerabilities) than Drupal's built in functionality such as filter_xss?

Looking for some guidance on why I should use htmlpurifier module for Drupal if I'm purely concerned with security (NOT concerned with preserving inline styles).

I trust the filter_xss function a bit more than htmlpurifier simply due to the complexity of the htmlpurifier code. Neither function is easy to understand, but at least filter_xss is shorter and more stable.

It is true that htmlpurifier is a general library used by other systems and therefore it could have "more eyes" on it. If you look at the HTMLPurifier Summary they claim that kses (which is what filter_xss was originally based on) is "Probably" XSS safe but misses out on other features of HTMLPurifier. The Drupal input format system handles many of the other features that HTMLPurifier mentions in that table so it's not an apples-to-apples comparison.

By the way, you may want to post questions like this to https://drupal.stackexchange.com/ in the future.


Allow user to enter unpublished content from the site in Drupal 7 I have a content type "User Bio" in my Drupal 7 site. On my site I created a form with all the fields in User Bio for the anonymous user to fill.

Now when the user enters and submits this information I want the node of "User Bio" type to be created but it should be unpublished. When the admin reviews, only then it can be published.

Is there a way to do it?

Thanks

You will probably want to set the content type to not be published by default, by simply editing the content type, and un-checking "Published" in the lower tab menu.

This will create the content unpublished, and from there you can handle the approval process however you'd like.


Is there a way to create hierarchical taxonomies checkboxes? I have an issue where I want to keep sub category inside a parent category. Say, for preferred vehicle I want a checkbox like this in node creation form

[]Car
  []Volkswagen
  []Toyota
[]Bike
  []Kawasaki
  []Harley Davidson

Is there a way to implement this using taxonomy?

Taxonomy is hierarchical by nature, you can create category/sub stuff in it.

AFAIK, there is not any field widget as you describe in drupal core with taxonomy field. Maybe some contrib module (have a look at term_reference_fancytree ).

You also may define your own and generate a field widget dedicated to taxonomy.


taxonomy name filter to get terms with special characters I am getting my term description using taxonomy_get_term_by_name().

I'm having problems with term names like "barnes & noble" and "Café"; I guess it must have something to do with the special characters. How can I filter my taxonomy name input the best way to get back term results?

I'm using the function in a views-view-list.tpl.php template, where $title is outputting the taxonomy; then I use $title with the following code.

$terms = taxonomy_get_term_by_name($title, 'places');

$title seems to be stripped from all kind of htmltags - its plain text.

It was only the & charter there was making problems.
This was the solution:

$terms = taxonomy_get_term_by_name(str_replace('&amp;', '&', $title), 'places');


How can we edit www.example.com/user page? The user page doesn't look good. I want to edit it, but (If I am right) that is a default page. I am not able to find where to edit it.

How can I edit the user page?

The page at http://example.com/user has two purposes:

Showing the login form for the users who are not logged in
Showing the profile page for the users who are logged in

In the first case, there isn't anything that you can edit to change how the login form is rendered. What you can do is implementing hook_form_user_login_alter() in the theme you are using, or in a module, to alter how the login form is rendered. In this case, you can use the #prefix and #suffix properties to inject CSS classes to the form fields, and #attached to load a new CSS file containing the CSS styles you need.
The alternative is associating a theme function to render the login form, through #theme.

In the second case, with the exception of the template file used to render the page, there isn't any file you can edit to change how the user profile page appear. Editing the user-profile.tpl.php template file used by the currently used theme is the easier, and faster way to change how the user profile page appears.
The alternatives are:

Changing the page callback associated with the user/%uid path with hook_menu_alter()
Implementing hook_user_view() or hook_entity_view() to add items to the user profile page
Implementing hook_user_view_alter() or hook_entity_view_alter() to alter what the user profile page contains

See also Gisle Hannemyr's answer; if you just need to change the order in which the fields associated with a user account are rendered, or slightly changing how those fields are rendered, that is the answer for you.


Unable to access admin I am trying to access the admin of my Drupal site but .../admin and .../user are not working.
When I try to access those pages I get the 404 page.
I believe this may have been redirected similar to https://www.drupal.org/project/rename_admin_paths.

I have access to the database and files where would this configuration change be stored?

Please specify the drupal version you  are using and is there any problem with non admin pages.

Also ensure the following:

Include .htaccess files
Enable clean urls
Clear caches


Views data export only exporting for current page I have a view which show Tabular data and i have attached data export on this view which should export in CSV format. The problem is if the data is paginated exportation is only downloading the records on the current page, but I want all records. Is there a way of making it to ignore the pagination.

In the data export display you need to set the pager to: Display all items. This will return you all the data in your file without pagination.


Is it possible to alter the data passed into a Rule? I have a bunch of Rules and some things require a bit more complex logic than usual. What I want to do is use a hook that runs when a particular rule fires, access the data that's passed in to it and manipulate it accordingly so when the rule executes it does it with the manipulated data. I looked through the Rules API and tried some of the function but none seem to have what I want. Is there such a function, or this there a better way?

A simple example: For a rule that sends an email, I want to hook in to it, check some stuff with code and then change the email address it sends to.

I think there are no hooks in rules by which you can achieve it. So you have 2 possible solutions.
1) In rules use the php code for action (Not recommended for security)
2) Use custom module to perform the action rather than using rules.


How to redirect the user to an external website with POST data? I want to implement an offsite payment method and everything is going well except the fact that I can't find how to redirect the user to the offsite payment gateway after submitting the cart checkout review

When the user submits the checkout review, the orderSubmit function is called. Inside this function I create the array with all the parameters required in the request, but I don't know how to send this request

public function orderSubmit(OrderInterface $order) {
    $fields = array(
      'version' => $this->configuration['version'],
      'TPE' => $this->configuration['tpe'],
      'date' => date('d/m/Y:H:i:s', time()),
      'montant' => round($order->getTotal(), 2).\Drupal::state()->get('uc_currency_code', 'USD'),
      'reference' => $order->id(),
      'texte-libre' => md5(uniqid(rand(), TRUE)),
      'mail' => $order->getEmail(),
      'lgue' => 'FR',
      'societe' => $this->configuration['company'],
      'url_retour' => Url::fromRoute('uc_cmic.cancel', array('absolute' => TRUE)),
      'url_retour_ok' => Url::fromRoute('uc_cmic.success', array('absolute' => TRUE)),
      'url_retour_err' => Url::fromRoute('uc_cmic.return', array('absolute' => TRUE)),
      'MAC' => "",
      'options' => ""
    );
    $fields = uc_cmcic_complete_request($this->configuration['security_key'], $fields); // This function fills the 'MAC' key by using the security key
    $host = UC_CMCIC_URL_CM_TEST;

//TODO send the request and redirect the user to the offsite payment gateway here
  }

What I tried to do and didn't work :

$response = \Drupal::httpClient()->request('POST', $host, [
  'form_params' => $fields,
]);

I tried some other variations of this too (like returning the $response after), which didn't work either

Question : What can I do to redirect the user to the offsite payment gateway while sending POST data in the request ?

In D8 for redirection you need to use RedirectResponse Object & thats best way forward. However for improved security the same RedirectResponse object does not allow External URL redirections. For this You may want to use TrustedRedirectResponse. Sample below with assumption that you are trying to post data to the payment getway which can be added as a query string on the URL.

use Drupal\Core\Routing\TrustedRedirectResponse;

public function myController() {
  return new TrustedRedirectResponse($host.'?xyz=abc);
}

PREFERRED

However the above suggestion does has security implications as the data is exposed on the URL. Below solution is a minor tweak from your code.

$response = \Drupal::httpClient()->post($host, [
        'form_params' => $fields,
        'headers' => [
          'Content-type' => 'application/x-www-form-urlencoded',
        ],
    ]);

You can try below if you would like to capture response (If its an XML / JSON)

$response = \Drupal::httpClient()->post($host, [
        'form_params' => $fields,
        'headers' => [
          'Content-type' => 'application/x-www-form-urlencoded',
        ],
    ])->getBody()->getContents();


Is it possible to combine two filter criteria exposed filter into one dropdown Is it possible to combine two filter criteria exposed filter into one dropdown. In drupal 8 I am creating a view to search certain content type. One of the content type has three select list field, I do not want to create three seperate exposed filter dropdown on the search page, Is there is a way to combine all into
one exposed filter dropdown ?
Any suggestions and guidance deeply appreciated.

Even with Better Exposed Filters you will not achieve what you need. As I understood you want one selectbox for the end user which merges three different fields of your content type?
This is not possible out of the box. When filtering the name of the selectboxes and the chosen values will be added to the URL like "?selectbox1=123&selectbox2=abc&selectbox3=xyz" (not exactly, but this is not important). Views does it for you to translate these URL parameters into the field names and the database query.
For your idea you need a way to tell Drupal that "?my_merged_selectbox[]=123&my_merged_selectbox[]=abc&my_merged_selectbox[]=xyz" needs to be somehow translated into the seperated filters / field names and values like above.
The only way would be to write your own views filter plugin. Helpful link: https://zanzarra.com/blog/custom-views-filter-plugin-drupal-8-bounding-box-geofield
I do not know if you have programming skills but what you want to achieve will need custom programming and is not trivial.


Drupal Commerce Kickstart 2 Adding Attrubutes to SPECIFIC Products I have a product type and I sell a number of different items within that category, where most of them have the same 3 options (color, type, voltage).  However, I have a couple of products of this type that don't conform to the same option set in that they have an one additional option for the customer to select.

The way I see it, I have two workarounds here, and neither of them seem like it's the "right" way to do it.  Either I create a separate product/ variation type with all of the existing options, plus the additional option, or I add the additional option to ALL of my variations, even the ones that don't come with that option and just leave it blank for those products.  Neither of these solutions are ideal in that it separates these products from others of their "type" or it creates the possibility for options to become available to the end user that are not possible.

Perhaps this is just me coming from an ubercart background, but I feel that I should be able to create an option that is specific to an individual product.  I've scoured the internet and I'm not finding a way to do this, nor am I finding anyone else asking this question and getting an answer.  What am I missing here?

I think you can use Conditional Fields module which can help you in showing and hiding fields based on any other field value.

You can also watch these tutorials in case you need to understand Drupal Commerce in detail.


PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column I am tring to perform the following sql query to check if the name that was inserted to the form already created as taxonomy name. But I keep getting this error message:

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'test' in 'where clause': SELECT COUNT(*) FROM {taxonomy_term_data} WHERE name = test; Array ( ) in get_google_map_api() (line 79 of /Applications/MAMP/htdocs/Drupal/sites/all/modules/toodate/toodate.module).

my function is:

function get_google_map_api($item){
    $city_name = $item;
    $chack_if_is_taxonomy = (db_query("SELECT COUNT(*) FROM {taxonomy_term_data} WHERE name = ".$city_name));
    var_dump($chack_if_is_taxonomy);
    drupal_exit();
}

Quick fix would be adding the missing single quotes around your variable. Forgetting the quotes can throw odd errors from this function, such as mixing a string for a column, like in your case.

There are less error prone ways to make short queries like this. See also Molot's answer.


Possible to save plain text value when entity reference doesn't exist? I have a user entity reference field. When I type in a name, but the entity/user doesn't exist I would like to save the name as a plain text value.
Is this possible?

Thanks.

Instead of adding an user entity field you can create a normal text field and then use formalter function to make it an auto complete.

The steps would be as follows.

Create a custom module.

First you would need to create a menu item to get the list of users to do that you can create a hook_menu function

function module_name_menu() {
  $items['userlist/autocomplete'] = array(
    'page callback' => '_module_name_autocomplete',
    'access arguments' => array('you can define the permissions here'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

The next step would be to create the call back function.

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

  // Some fantasy DB table which holds cities
  $query = db_select('users', 'u');

  // Select rows that match the string
  $return = $query
    ->fields('u', array('name'))
    ->condition('c.name', '%' . db_like($string) . '%', 'LIKE')
    ->range(0, 10)
    ->execute();

  // add matches to $matches
  foreach ($return as $row) {
    $matches[$row->name] = check_plain($row->name);
  }

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

The last step would be to create a form alter function to

function module_name_form_page_node_form_alter(&$form, &$form_state, $form_id) {
  $form['field_name']['#autocomplete_path'] = 'userlist/autocomplete';
}

This would change your textfield into an autocomplete field. you would also be able to enter any other name as well.


Can jPlayer be integrated with the Video module? With the Video module, the admin panel shows a large list of video formats with dropdowns allowing the user to select one of the supported players. The list that is included consists of:

Divx
Quicktime
RealMedia
FLV flash
SWF flash
Director/Shockwave
Windows Media
Theora

I installed the jPlayer module and put the jPlayer library into /sites/all/libraries. Is there an established way to get jPlayer to appear in this list, or to otherwise integrate Video with jPlayer?

I hope I can help you

First of all.

The jplayer you have installed

here is a tutorial that will help get up and running with that Jplayer Tutorial

Second of all, the video module you have, Is for making a new filefield with a new content type, make a view that shows the filefield.
You should either choose one of the following options. and not both of them.

Hope this helps. I am currently myself working on something smiliar.

I would also like to help you by showing you this link

Its a Drupal distribution called Octopus : Octupus Drupal

Hope this helps :)


Extended default form inside block, possible? Ok. So I have a content type, let's say "My favorite places".
So naturally Drupal has a form to create new "favorite place" at node/add/my-favorite-places which appears as a page. I managed to create a customized template for this form my_favorite_places-node-form.tpl.php following this very helpful thread.
How do you theme a content type's create/edit form in Drupal 7?

I'd like to use this form in several pages on my site. So I was thinking to make it into a block. In below mockups, My favorite places = Content Type A.

However......
I had some experiences customizing front page for anonymous users showing login & register form at the same time, which doesn't run properly with a block (messaging issue). An expert mentioned that form rendering calls should never be fired from inside blocks.

So, I was wondering whether this is a good idea. And if so, how should I do that, if possible without installing another contrib module.

Please advise. Thanks.

Using php inside blocks or simply pouring your database with php used to be bad practice.

Said that, the function toy are looking for is drupal get form:

https://api.drupal.org/api/drupal/includes%21form.inc/function/drupal_get_form/7


Why is ddebug_backtrace coming up blank? I've been using the Devel module for a couple of years now but every time I try to get a backtrace I run into issues.  I remember getting it working once, but I don't remember how.

It seems like using dpm(ddebug_backtrace()); should do the trick.  I have tried it with no argument, TRUE, and FALSE, and I have also tried removing the dpm function it's wrapped in.

I have dpm calls directly above and below this code that print variables appropriately, but the most I get out of dpm(ddebug_backtrace()); is a blank line in the Krumo output.

Suggestions mightily appreciated.

For me the command had to be called without the extra d

dpm(debug_backtrace());


ahah_helper or ctools for ahah in Drupal 6? The excellent ahah_helper module (http://drupal.org/project/ahah_helper) improves the core ahah functionality to the point where it works quite nicely.

Ctools (http://drupal.org/project/ctools), seems to bypass the core functionality totally, offering its own brand solution.

Ctools seems to be quite a bit more complicated, needing more complexity to deal with no-js situations : http://drupal.org/node/1025448#comment-4196882

Where as ahah_helper seems much cleaner/simpler to deal with : http://drupalcode.org/project/ahah_helper.git/blob/refs/heads/6.x-2.x:/ahah_helper_demo.module

So.

Which is better?
Which is more like the implementation in 7 (so we only learn once)?

You're better of using ctools in D6. Also all the ctools ajax implementation is whats in Drupal 7 known as the Ajax Framework


Why does the Wysiwyg module and Ckeditor library not show the CKEditor when editing a node? I installed latest version of the WYSIWYG module (dev version) and also the latest CKEditor library. This module can find the library, I selected the ckeditor for text format "Full html" only.

But when I try to edit the content it does not show up. All modules are update to date. I have other Drupal sites and this module works with no problem.

What to do?

Notes:

The text is there when you start an edit session of the node. But it is just full html text, with all the HTML code being shown, as in this example:

I also tried by enable of an additional editor, as shown here:

But still nothing happens.
The link to enable/disable the editor is missing (and it should be there). I spotted that problem at first. I wanted it to be disabled by default and then by clicking on it it should be enabled. but the link is not there. Here are the scripts errors:

I cannot see something.

In the CKEditor page you have to select Enable in CKEditor -> EDITOR APPEARANCE -> "Default editor state".

This you can find in admin/config/content/ckeditor/edit/<yourtextformat>

Or if you dont want to enable that by default, then you can click manually "Switch to to rich text editor" in /node/<nid>/edit


How to disable auto submit on value change in date_popup form? Is there a quick way how to disable auto submit on value change in date_popup forms?

Thanks.

Add 'event' => 'submit' in #ajax' => array()


Set value of List field of a node with multiple values I'm attempting to programmatically generate nodes of a custom content type from a form plugin. For most fields I don't have any trouble at all. For example for the title field I can set the value like so.

$node->title->value = t('My title');
$node->save();

However there is also a list(text) field that allows for multiple values. And I'm not sure how to go about saving values of field with multiple values. I'm assuming if there was only one value allowed I could do it just like I set the title in the previous example, but how do I deal with it when the field is an array? As a test I performed a die statement of the field on a node that already had values in that field to take a look at what it looks like and this was generated:

Array ( [0] => Array ( [value] => test_3 ) [1] => Array ( [value] => test_4 ) ) 1

But I'm not sure what to do with that. How would I set the field value of a list field with multiple values allowed?

You can replace the complete content of a field by assigning an array:

$node->field_multivalue = [
  ['value' => '1'],
  ['value' => '2'],
  ['value' => '3'],
];

If you want add another value to the field you can use the field like a php array:

$node->field_multivalue[] = ['value' => '4'];

You can omit the main property of a field:

$node->field_multivalue[] = '5';

Now you have 5 values in the field.


$page not targetting views block but $is_front is. Need help with trying to solve this in any way I wrote this poorly the first time, more succinctly:

I need a custom node.tpl for the same content type in the front page teasers, the node itself, and a views listing of that node in the sidebar on every page. The problem is the front page uses teasers, while the nodes use full view, so I can't edit the markup of the sidebar nodes with just $page or $teaser because they would share the markup with the main content of either page.

The front page uses teasers to display nodes. I want different markup in the sidebar for the "most popular" views block, so I set it to use full view. This works fine on the front page.

The problem is on the individual nodes. I can't target the views block's markup in node.tpl. I made an identical views block with teaser view (because nodes use full view) instead but

<?php if ($page): ?>
<?php if ($view_mode == 'full'): ?>
// Node
<?php endif; ?>
<?php if ($view_mode == 'teaser'): ?>
// Views list
<?php endif; ?>
<?php endif; ?>

doesn't work. The opposite works fine on the front page:

<?php if ($is_front): ?>
<?php if ($view_mode == 'teaser'): ?>
// Node
<?php endif; ?>
<?php if ($view_mode == 'full'): ?>
// Views list
<?php endif; ?>
<?php endif; ?>

I tried <?php if ($page == 1): ?> as well, though I'm not sure if that's used.

Either way, why I can't just use views for everything is because 1. it breaks the AJAX of the rate module. Which is fine in the sidebar, but not on the front page. And 2. I'm using a link from within a field like this:

    <a class="full-link" href="<?php echo $node->field_download_link['und'][0]['value']; ?>">

                <?php print render ($content['field_parent'][0]['#markup']); ?>

                    <?php echo $node->title; ?>

so I can't have all of the "field-" divs, which break the link. If it matters I'm using $block to get the views list, again, to avoid those "field-" divs.

        <?php $block = module_invoke('views', 'block_view', 'sidebar_popular_full_view-block'); ?>
            <?php print render($block['content']); ?>

See template_preprocess_node() for details on how the $page variable is created.

It is this:

$variables ['page'] = $variables ['view_mode'] == 'full' && node_is_page($node);

So it is only for the full view mode and only if you are viewing the node page of the node that is currently being themed.

So something like this will not work because $page will not be true if $view_mode == 'teaser':

<?php if ($page): ?>
  <?php if ($view_mode == 'teaser'): ?>
    // Views list
  <?php endif; ?>
<?php endif; ?>

There is also currently a bug in the views module where if you have a view on a node page and one of the results of that view is the same node as the one whose page you are on then views will break the $page variable in the node template, causing it to always be FALSE.

To see if that is part of your problem try the patch at https://www.drupal.org/node/1574806

I would not theme a view mode differently in different places. For example the teaser would always look the same regardless of what page it was on. Then you just use:

If you are using teaser already for something else then use a different view mode (you could use the entity view mode module for this if you don't want to code it).


How can I add commerce product automatically when saving a node 'product display' I want to create a default product reference with the price to zero, title to node_title, sku to author_node_title. So each time I create a display product node type I haven't to fill the product reference info. If I created one display product node type -> system will create one product and auto reference that product to display product node.

Thanks in advance!

You could use a triggered rule using Rules on the event "After saving new content", creating the product entity, saving it and editing the product reference field after as well.


Force an empty region to display I'm looking for a way to force an empty region to display. I notice Omega does this via a theme-settings checkbox, but I'm unable to track down how it's done.

Regardless of removing the if ($page['regionname']): around print render, the region still does not display unless it's populated with block content. Perhaps injecting content into the $content var somehow?

Example:

In a custom theme, the header variables such as logo, sitename and secondary links are placed in a region template called region--branding.tpl.php.. (the variables have to be passed from preprocess_page to preprocess_region so this can work and a template suggestion needs to be made). Once this region is printed in page.tpl.php, it must always be rendered even if there is no block content in that area.

Omega does it this way:

in omega.info

settings[alpha_region_xxx_force] = ''

in `omega/alpha/includes/theme-settings-structure.inc

$form['alpha_settings']['structure'][$section][$zone]['regions'][$region]['alpha_region_' . $region . '_force'] = array(
  '#type' => 'checkbox',
  '#title' => t('Force this region to be rendered'),
  '#description' => t('Enabling this will always render this region, even if it is empty.'),
  '#default_value' => $item['force'],
);

Call alpha_alpha_page_structure_alter() in alpha_page_alter()

#omega/alpha/template.php
foreach ($theme->regions as $region => $item) {
    if (($item['force'] || !empty($vars[$region]))) {
      $temporary[$item['section']][$item['zone']][$region] = !empty($vars[$region]) ? $vars[$region] : array();
...

this way your code should be:

function THEMENAME_page_alter(&$page) {
    $regions = system_region_list($GLOBALS['theme'], REGIONS_ALL);
    foreach ($regions as $region => $name) {
        $page[$region] = !empty($page[$region]) ? $page[$region] : array();
    }
}


Workflow assign user to handle node in given state I am using Workflow module to implement moderation policy in one of my project. It is working fine.
But I want is when a user changes workflow state of user, he must be able to select a given user also from given user group, who will be responsible to manage the node in that state.

So, ideally it would be drop-down of user, form where admin can select user to whom the the node be assigned.

I searched a lot, but didn't find any solution yet. Is there any way to achieve this.

-- Many thanks for your time.

I am developing a module that address that very issue and some other things. Besides it is on sandbox yet, it is fully usable (I am using it on production).

  Workflow Hide Fields is an addon to the Workflow module.

You can clone it:

git clone --branch 7.x-1.x git://git.drupal.org/sandbox/fpap/2575131.git

And can visit the module page.


How to layout the theme within the regions? I'm very much beginner to the drupal and learning to themeing, and I'm confused how to make regions within the regions?

+----------------------------------------------------------+
| +--------------+                +---------------------+  |
| |              |                |                     |  |
| |    header1   |                |   header2           |  |
| |              |                |                     |  |
| +--------------+                +---------------------+  |
|                       header                             |
+----------------------------------------------------------+

page--front.tpl.php

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

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

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

And I did the change in .info file like:

regions[header1]        = Logo Area
regions[header2]        = Search bar and Navigation

But it's not displaying as the picture describes better it:

Update:

The rendered html is like this:

But What I wanted to be like this:

You cannot make region within region. You can place block in a region.
Fix the width of block and float that. You have to use only css to achieve that.

Print wrapper like this

<?php if($page['header1'] || $page['header2']) :?>

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

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

    <?php endif;?>
    <?php if($page['header2'] ) :?>

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

    <?php endif;?>

<?php endif;?>