HTTP Client Manager $request->getStatusCode() == 200 return? When I read this HTTP Client Manager docs on Drupal, I don't understand why it returns the $build when $request->getStatusCode() == 200, is that supposed to be not equal 200? I also copy and paste the code from Drupal docs.

public function posts($limit, $sort) {
    $build = [
      '#theme' => 'mymodule_posts_list',
      '#posts' => [],
    ];

    $request = $this->httpClient->request('GET', 'http://api.example.com/posts', [
      'limit' => $limit,
      'sort' => $sort,
    ]);

    // This is the Part I don't understand.
    if ($request->getStatusCode() == 200) {
      return $build;
    }

    $posts = $request->getBody()->getContents();
    foreach ($posts as $post) {
      $build['#posts'][] = [
        'id' => $post['id'],
        'title' => $post['title'],
        'text' => $post['text'],
      ];
    }
    return $build;
  }

The information from https://www.drupal.org/docs/contributed-modules/http-client-manager/introduction was wrong and was updated, now:
   if ($request->getStatusCode() != 200) {
      return $build;
    }


How do I print a taxonomy term in node.tpl.php? (D7) I have a custom content type that I can select a vocab term for when editing the page (category more or less). How do I print this term to my page via node.tpl.php?

I've tried several different ways, but to no avail so far. Any ideas?

This works for me:

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


How to add the image url in the head tag Do youknow how to add the image url to the head tag?

This is what I've tried so far

Example

<head>
     <meta property="og:image" content="  {{ file_create_url(node.field_image.0.entity.uri.value) }}        "/>
     <meta property="og:image:secure_url" content="  {{  file_create_url(node.field_image.0.entity.uri.value)  }} " />
</head>

Thanks!

Or possibly a better solution - use the metatag module and you can customise this through the CMS globally or for specific pages. "og" stands for Open Graph so you just need to pop your data in the relevant open graph section

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


How can I set the help text as an input placeholder on the user login form? On the user login form, I am trying to take the "help text" and make it an input placeholder (so that the help text shows up in the input and disappears when the user enters their username and password).

Here's my code:

function mymodule_form_user_login_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['name']['#placeholder'] = $form['name']['#description'];
  $form['pass']['#placeholder'] = $form['pass']['#description'];
//  $form['name']['#description']['#access'] = FALSE;
//  $form['pass']['#description']['#access'] = FALSE;
}

This adds the placeholder correctly but it doesn't hide the help text, so the text appears twice (in the input and below the input).  In Drupal 7, I just set access to false, but in Drupal 8 the description is an object so I don't know what to do.

unset($form['pass']['#description']);

or

hide($form['pass']['#description']);

is probably sufficient for the description element. I wouldn't use both above on form fields/controls though, because that may lead to unwanted validation errors and so forth.

$form['name']['#description']['#access'] = FALSE;

does not work for 'description' element as it is not a form control(field).

If anybody knows of better ways for removing description element, please chime in.


Set boolean (single on/off checkbox) value while creating a user I am creating a user programmatically and there is a boolean field (single on/off checkbox) being used as a terms of use inside the users profile.

How do I set the value of it when creating a user object? I need it to be checked or 1.

$new_user = array(
                'name' => $username,
                'mail' => $email,
                //'pass' => $pass,
                'signature_format' => 'full_html',
                'status' => 1,
                'access' => 0,
                'timezone' => 'America/New_York',
                'init' => $email,
                'field_user_account_terms' => array(
                    'attributes' => array(
                        'checked' => 'checked',
                    ),
                ),
              );

$account = user_save(NULL, $new_user);

i've also tried

                    'field_user_account_terms' => array(
                    'und' => array(
                        0 => array(
                            'value' =>  1,
                        ),
                    ),
                ),

I've also tried setting the default value and a bunch of other syntax. Nothing seems to be working for me.

is this even possible? What is the correct syntax for setting the value of a checkbox, to be saved in a users profile?

The help message for this field says: If left empty, "1" will be used and if left empty, "0" will be used. So I left this field blank and assumed you could programmatically set the value while creating a user. This doesn't work at all for me.

You actually have to explicitly define the On and Off values in order to be able to set them while creating a user.

Then you can set the value in the user object.

'field_user_account_terms' => array(
                'und' => array(
                    0 => array(
                        'value' =>  1,
                    ),
                ),
            ),


What may cause Column not found (nid) in on clause? I'm using Drupal 7.14 and Entity API and Reference 1.0-rc3.

And I'm also using i18n, entityreference (not References) and field_sql_storage.

I get this error when saving a node that has some custom fields using references.

  PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column
  'field_data_body0.nid' in 'on clause': SELECT
  field_data_body0.entity_type AS entity_type,
  field_data_body0.entity_id AS entity_id, field_data_body0.revision_id
  AS revision_id, field_data_body0.bundle AS bundle FROM
  {field_data_body} field_data_body0 INNER JOIN {node} node ON
  field_data_body0.nid = node.nid WHERE (field_data_body0.deleted =
  :db_condition_placeholder_0) AND (field_data_body0.entity_type =
  :db_condition_placeholder_1) AND (field_data_body0.bundle IN
  (:db_condition_placeholder_2, :db_condition_placeholder_3)) AND
  (field_data_body0.entity_id IN (:db_condition_placeholder_4)) AND
  (node.language IN (:db_condition_placeholder_5,
  :db_condition_placeholder_6)) ORDER BY field_data_body0.body_value
  ASC; Array ( [:db_condition_placeholder_0] => 0
  [:db_condition_placeholder_1] => node [:db_condition_placeholder_2] =>
  news [:db_condition_placeholder_3] => page
  [:db_condition_placeholder_4] => 25 [:db_condition_placeholder_5] =>
  it [:db_condition_placeholder_6] => und ) in
  field_sql_storage_field_storage_query() (linea 577 di
  /home/morpheu5/web/xdatanet/modules/field/modules/field_sql_storage/field_sql_storage.module).

What bothers me is that, first of all there's a zero appended to the name of the table, and second, if I add that nid column to that table, Drupal is happy and everything seems to work.

I suspect there must have been some update gone horribly wrong, since maintenance is not under my control, and I had to implement some new features working on my local copy which at that time was already completely out of sync with the client's staging and production servers.

I tried a number of patches, and I've gone through the code myself but I'm not this familiar with Drupal.

EDIT

It seems the nid column is getting added at some point in function preExecute in includes/database/select.inc specifically at row 1236

drupal_alter($hooks, $query);

the hooks acting here are

query
query_entity_field_access
query_node_access
query_entityreference

but after a hour long investigation I only came up with a huge headache, and I'm still not sure if I actually found and debugged all of those hooks. As far as I could see, the nid column is not present before the drupal_alter call while it is after, but it's there at the beginning of each hook_query_TAG_alter I was able to find.

I must be missing something.

EDIT 2

The culprit seems to be i18n, specifically i18n_select, more specifically at row 137 of i18n_select.module where it adds the nid column.

EDIT 3

There, I opened a bug: https://drupal.org/node/1679646

The body field should definitively NOT have a nid column in the table. The field_data_body table provided by core will contain an entity_id column which is the reference to the node entity.

2 things I can think of that might be causing this:

You have custom code that's making an erroneous database query in a hook_node_load() function or similar (either directly or using an EntityFieldQuery)
(more likely I think) Core/contributed modules or files have been edited and the changes are only now causing problems.

The best advice I can give is to install the Hacked! module and determine whether or not core/contributed modules have indeed been hacked. If that comes back all clear then you're just looking at an error in some custom code somewhere which will be easy to track down.

If it doesn't come back clear, at least you know what the problem is and you can then decide how best to proceed with getting Drupal back into a proper un-hacked state.

Incidentally, don't worry about the table being referred to as field_data_body0...if you look further down in the query that's just an alias that's being used for field_data_body:

FROM {field_data_body} field_data_body0


Unable to edit node translation other than current language On my multilingual site I seem to have problem at admin/content when editing a particular translation.

I have a Contact Us page, translated:

Contact Us [EN], node/286
Contact Us [ES], node/300

I don't have an explicit Path Translation set, but the nodes are bound together, in the Translate tab.

Now the problem is, that when my current language is English and I want to edit the Spanish version from the Content listing, the edit link takes me to its English version (node/286). Apparently the admin overlay inherits the language prefix and forces the English translations to open.

What luckily works correctly is editing the node from within its view (by hitting the Edit tab).

Is this normal behavior?

Anyone having this issue should read https://www.drupal.org/node/1399506.

The problem arises from the feature Language Path Checking within the Global Redirect module. Use the dev version to correct the problem.


Why are some of my modules reporting missing inter-module dependencies after migration? I'm troubleshooting modules after a host migration--did I miss something? Before I changed my host I backed up MySQL database, made a list of all my used modules and burned a dvd of the Drupal root directory. Now, after I've successfully restored the database of 5/6 sites, three modules report missing inter-module dependencies within their module groups:

Event- Calendar Signup   - 6.x-2.x-dev - Depends on: Signup
(missing)
Rules- Rules Simpletest - 6.x-1.4 - Depends on: Simpletest
(missing)
Services -

servers - REST Server - 6.x-3.0-rc1    - Depends on:
Autoload (missing)
authentication - OAuth Authentication  6.x-3.0-rc1 - Depends on: Oauth_common (missing)

How can these other modules be missing if they were there before the migration? The folders are still the same. Do some modules "make" other modules in the database? Something like cTools 'makes' the css directory.

All of my sites are in the sites directory and share the same modules, though they each have their own database. Each is missing the same module dependencies.

Are those missing modules in your sites/all/modules folder? I'm not sure why they would have been left out of a file migration, but anything's possible.

Modules do not 'create' other modules (except possibly Features, I haven't used that in awhile) in the sense that you're referring to w/ the cTools example, though there are modules that exist as part of the parent module package.


Nodes appear out of line - views Does anyone know what causes nodes to appear out of line when pulled to a view? Examples:

Photo profiles here:
https://international.permaculture.org.uk/about

Topics listed at the bottom of this page:
https://international.permaculture.org.uk/nextbigstep

I am wondering if it is because not all fields are populated - or because there are no teaser breaks and an uneven amount of body text?

Is there a way to stop this happening?

I think that you will find the answer here:

Responsive column resets

  With the four tiers of grids available you're bound to run into issues
  where, at certain breakpoints, your columns don't clear quite right as
  one is taller than the other. To fix that, use a combination of a
  .clearfix and our responsive utility classes.

If it is too difficult to add above mentioned classed divs in the layout (can be done via templating Views) you should add your own styling wherein you use the n-th group of CSS selectors to clear at the different media queries.

The problem arises from the fact that your views rows do not have equal height and therefore do not flow as you want it to.

Also look at this post Bootstrap 3.0:responsive column resets section of the documentation

And for a module to assist you can try this: gido's sandbox: Views Bootstrap Responsive Grid

  Views Bootstrap Responsive Grid module enable you to take advantage of
  the Bootstrap 3 Grid System columns reset. With this module you can
  define the number of items per row for each breakpoints. All of this
  within the great configuration settings of the View module.


Adding a hook to a contrib module I am trying to hook into the Print module after to call a custom function after the pdf is generated. I've got this working by simply patching a call back on the wkhtmltopdf.pages.inc:

 if (!empty($pdf)) {
  _callback_for_pdf();
  return $pdf;
}

This is pretty nasty. So ideally I would like to try and extend this contrib module to have a hook for this functionality.

How do I go about adding a hook to something to then use in a custom module?

Check out this documentation: https://www.drupal.org/docs/7/creating-custom-modules/creating-drupal-7-hooks

For your case, the simplest may work

So lets say your hook you want to be hook_pdf_generated()

module_invoke_all('pdf_generated');

in your custom module, have a function YOURMODULE_pdf_generated()

If you wanted to be able to alter the $pdf variable, use a _alter() hook

So in that code you posted, add:

drupal_alter('pdf_generated', $pdf);

and in your custom module you'd have YOURMODULE_pdf_generated_alter(&$pdf)


Drupal 7, no toolbar, strange code I am new to Drupal. After reading about it and watching some tutorials, I tried to install Drupal 7 on my localhost to see it for myself. But now it is installed, I see no admin toolbar on top of the page. On the place where the toolbar should be I get the following code: $S$DWqdyauf.rdiK9FyIjcO5oZuwyz2HaRQiTO2Ot/5o4YIN8fxcH3u

In the middle of the page it does say 'add more content', so I guess I do have an admin account.

I tried to change the rights via PHPadmin, but sometimes I ended up having no access to the page at all anymore. When I refresh the page I get a different code. It happens in both Chrome and Explore.

What can I do to see a toolbar?

Thank you for your time. Mariska.

Sounds like an incomplete or partially failed install. Delete all the tables in the database and try doing a fresh install.

Try performing the install with Drush so you can see in real time if there are any errors when writing to the database (look under "Quick installation with Drush"): https://www.drupal.org/documentation/install/developers

Also make sure you're running PHP 5.3+ and MySQL 5.0.15 or higher with PDO: https://www.drupal.org/requirements


How to set the url alias of a node created by Rules? I am using the Rules module to create some default group content upon creation of an organic group. The rule is copied below and works well except that the url pattern for the default content is not being generated as I want it to be.

I would like url pattern to be [node:og-group-ref]/content/[node:title] and I have this working for regular group content which is created manually once a group exists.

The problem is that default content created by rules is missing [node:og-group-ref] in the url. If I edit the generated content I see that the setting to 'Generate automatic URL alias' is unchecked. If I then enable this and re-save the url ends up as I need it.

And I am guessing that pathauto is not aware of the og-group-ref value when the node is first created by rules and can not use this token.

I have tried including an action to create a url in the rule, but this seems to get overriden by pathauto.

So my question is - How to set the url alias of a node created by Rules?

{ "rules_og_create_group_content_timetable" : {
"LABEL" : "OG Create group content - Timetable",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "og" ],
"ON" : { "node_insert--og_group" : { "bundle" : "og_group" } },
"DO" : [
  { "entity_fetch" : {
      "USING" : { "type" : "node", "id" : [ "node:nid" ] },
      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
    }
  },
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "og_page",
        "param_title" : "[entity-fetched:title] Timetable",
        "param_author" : [ "node:author" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created__page_stub" : "Created entity page stub" } }
    }
  },
  { "entity_save" : { "data" : [ "entity-created--page-stub" ], "immediate" : "1" } },
  { "og_group_content_add" : {
      "entity" : [ "entity-created--page-stub" ],
      "group" : [ "entity-fetched" ]
    }
  }
]

}
}

It is probably because you have not "made that field available yet to Rules".

To do so, add a "Rules condition" like "Entity has field", and use that "[node:og-group-ref]" in that condition to be added.

Not sure if it is the ONLY problem you have, but for sure something you should add to your rule.


How to Logout user with Basic auth? I can log in, perfectly fine, but can't get logout to give me a JSON response. Currently, I can only do POST to

d8.com/user/logout?csrf_token=123&?_format=json

and that would log out, even though the token 123 is not the same as the given csrf-token at login or the logout token. This doesn't work without the token query, even though cookie/session isn't enabled anywhere

  ("message": "'csrf_token' URL query argument is missing.").

The logout happens when hitting a 403 forbidden on that URL.

Other info:
csrf_token=123 is the actual query, doesn't need to be csrf-token or the log out token is given at login
Version: 8.5.3
The only basic_auth turned ON, at all endpoints.

The mistake is in the url parameters, it should be :

d8.com/user/logout?token=123

The _format is not needed for logout.
I found the parameter name for the token on this page https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Access%21CsrfAccessCheck.php/function/CsrfAccessCheck%3A%3Aaccess/8.3.x


How do you use BLOCK_VISIBILITY_PHP, in hook_block_info, to hide a block? I am user #1; I do have the PHP filter module enabled, but still my block is displaying, when I'd like it to be hidden. Here's my implementation of hook_block_info:

/**
 * Implements hook_block_info().
 */
function alerts_block_info() {
    $blocks['get_e_mail_alerts'] = array(
        'info' => t('Get e-mail alerts'),
        'status' => TRUE,
        'region' => 'sidebar_first',
        'weight' => 0,
        'visibility' => BLOCK_VISIBILITY_PHP,
        'pages' => '<?php global $user; if ($user->uid == 1) { return FALSE; } else { return TRUE; } ?>',
    );
    return $blocks;
}

Thanks.

I put this in my php code and it works just right:

<?php drupal_set_message("here"); global $user; if ($user->uid == 1) { return 0; } else { return 1; } ?>

The drupal_set_message is called and everything.


Page not found for a node that does exist? I have created a module which includes a custom form. When the form is submitted the module uses drupal_write_record to insert the form contents into the database. The first drupal_write_record is to the node table. Using phpmyadmin I've looked into the node table and I can see there is a record where nid is 11. If I request example.com/?q=node/11 I get a 'page not found' error.

Here is record 11 from the node table:

nid,vid,type,language,title,uid,status,created,changed,comment,promote,sticky,tnid,translate
11,NULL,game,und,Title,1,1,1365111019,1365111019,1,0,0,0,0

Why doesn't example.com/?q=node/11 return the contents of this record as a page? Do I need to do something else?

You cannot write a node using a single drupal_write_record(). Depending on how your content type is defined you will need to write to several tables. But you don't need to know the precise details because the right way to create a node is to use node_save() as Ahmed mentioned in his comment.


List of nodes within a block I have a page for available job positions, which has some content but I'd like to also place a list of the jobs in the middle of this content.

I would like this list to be dynamic based on currently published "job" nodes. The problem is this content is within a block. I know about views and can easy create a list with views, but I don't want this list to be a stand-alone block. Is there a way to pull a dynamic list like this into a pre-made block?

There are multiple ways to do this.

You can create a view page with list of nodes and you can add other
content in the views header or footer area.
You can create it as view attachment and can add to other view.

Basically views have a great flexibility to get embedded in one another,panels, nodes etc.


Can't place a custom block After adding a block file to src/Plugin/Block I can't add the block on the Block Layout admin page. When I filter by block name I can see it, but then when I try to place it I can't get to the configure block screen (pressing the 'Place block' button produces no effect).
I do not get any errors.

What could be the reason for such a behaviour?

The block file contents:

    <?php

namespace Drupal\Core\Block\BlockBase;
use Drupal\Core\Link;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a block with a link to start the toru.
 *
 * @Block(
 *    id = "iai_tour_link",
 *    admin_label = @Translation("Link for the IAI Product Guide tour"),
 *    category = @Translation("Links"),
 *    context = {
 *       "node" = @ContextDefinition(
 *         "entity:node",
 *          label = @Translation("Current Node")
 *        )
 *     }
 *   )
 */
class TourLinkBlock extends BlockBase implements ContainerFactoryPluginInterface{
    /**
     * The current user.
     *
     * @var \Drupal\Core\Session\AccountInterface;
     *
     */
    protected $currentUser;

    /**
     * Constructs an TourLinkBlock object.
     *
     * @param array $configuration
     * A configuration array containing information about the plugin instance.
     * @param string $plugin_id
     * The plugin_id for the plugin instance.
     * @param mixed $plugin_definition
     * The plugin implementation definition.
     */
    public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountInterface $current_user){
        parent::__construct($configuration, $plugin_id, $plugin_definition);
        $this->currentUser = $current_user;
    }

    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition){
        return new static(
            $configuration,
            $plugin_id,
            $plugin_definition,
            $container->get('current_user')
        );
    }

    public function build(){

        $node = $this->getContextValue('node');
        if ($this->currentUser->hasPermission('access tour') && $node->getType() == 'book'){
            $url = Url::fromRoute('<current>', array(), array('query' => array('tour' => 1)));
            $build['tour_link']= [
                '#type' => 'markup',
                '#markup' => Link::fromTextAndUrl(t('Take the tour!'), $url)->toString(),
            ];
            $build['#attached']['library'][] = 'tour/tour';
            return $build;
        }
    }
}

Fix the namespaces:

delete:
namespace Drupal\Core\Block\BlockBase;

add:
namespace Drupal\MY_COOL_MODULE\Plugin\Block;
use Drupal\Core\Block\BlockBase;


how to use URL_ALIAS for search result of apachesolr module? I am using apachesolr in drupal 6.22 module to search. the links of the results look like http://mywebsite.com/node/NID , how can i manage it to show the url alias instead of displaying node/NID representation.
Thanks for your help

I am running the same configuration as you and this has the SEF urls by default.

Have you checked your URL Aliases? Does this problem occur for ALL nodes in SERPS? I would try rebuilding your aliases


Add second expression to query I have a probably trivial question, but I could not find an answer.
I have this query, which works fine:

$query = db_select('books, 't');
$query
  ->fields('t', ['publication_year'])
  ->groupBy('t.publication_year')
  ->orderBy('publication_year', 'ASC')
  ->addExpression('COUNT(t.publication_year)', 'n');
$data = $query->execute();
$result = $data->fetchAll();

I want to add a second expression:

(SELECT COUNT(*) FROM books WHERE open_access=1) AS n_oa

But I have two problems:
When adding a second expression I get the error Method 'addExpression' not found in null|string regardless of the content.

When only adding the single expression ->addExpression('SELECT COUNT(*) from books WHERE open_access=1', 'n_oa'); I get a syntax error.

Edit:

I tried this, and it generally works except, that the seond expression can't find the 'year' alias.

 $query
    ->addField('t', 'publication_year', 'year');
  $query
    ->condition('wg', 'ag_zzexternal', '=')
    ->groupBy('t.publication_year')
    ->orderBy('publication_year', 'ASC')
    ->addExpression('COUNT(t.publication_year)', 'n');
  $query
    ->addExpression('SUM(IF(open_access=1,1,0) AND IF(publication_year=year,1,0))', 'n_oa');
}

I think the easiest solution will be to use db_query, where you can write raw SQL, like this:

$query = db_query('SELECT publication_year FROM books etc.');


created block for image is not displaying I created the block for a image where in I want to display in all pages, but after creating the blocks once I see the page the created block is not displaying.

Following method  followed to create a block.

1] Structure->Blocks->Add Block

2]specified the name and browsed the picture( i have installed IMCE)

3] and chosen to display in bottom fist and also in all pages then save the
block.

But couldn't see the block in all pages, if any one know please help me.

when you create block then you have options for visibility where you want to show this block like below:


How to add cache contexts to a region How can I add cache contexts to a region. I have been able to do this to my blocks but have noticed that parts of the region remain cached.

You can add a cache context to a region the same way as to any other page element:

function mytheme_preprocess_region(&$variables) {
  if ($variables['region'] == 'myregion') {
    $variables['#cache']['contexts'][] = 'user';
  }
}

But this is probably not what you want, because regions are not cached. Usually the blocks inside a region are cached and the complete page which contains the regions. The cache context of the region will only have an effect on higher level elements, not downwards.


Add  element to node body field via WYSIWYG I am working on a project where the admin wishes to be able to insert a  element into a node's body field.  The site makes use of TinyMCE editor (wysiwyg module) to edit text area fields.

Currently admin is able to add the  element to the body field by switching to source mode of Full HTML text format (by toggling "disable rich-text").  He can then insert the  element and then save node.  In this case the  element will be preserved in the saved markup.

But if the node is edited again the wysiwyg appears to filter out the  element, which means the admin has to re-add it using the method just described.

This unwanted removal of  element also occurs when switching back and forth between the rich-text editor (toggling the "Enable rich-text" or "Disable rich-text" link below the field) after adding the element.

So it seems it is the wysiwyg is filtering this  element out.

Is there a way of preventing this from happening?

TinyMCE outputs HTML 4.01 Transitional markup by default, and  is not allowed inside  in that (or XHTML) because styles are not block elements.

You can however force TinyMCE to accept [the invalid] style elements inside the body by overriding the valid_children setting.

/**
 * Implements hook_wysiwyg_editor_settings_alter().
 */
function MYMODULE_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'tinymce') {
    $settings['valid_children'] = '+body[style]';
  }
}

Thanks to TwoD for supplying the answer.


page--front.tpl.php being ignore in favour of page--node--page.tpl.php I've got an issue which I'm not sure how to address. I've got a specific page that I've set as front page. I've created a custom template for it and named it page--front.tpl.php and it was as expected until I've added page--node--page.tpl.php which seems to be overriding page--front.tpl.php.

Is this the correct and expected behaviour? How can I force it the page--front.tpl.php to be used?

I'm using Drupal 7 with and a child of the Bootstrap's theme.

If you need to have a custom theme for nodes, try to do this using THEME_preprocess_node as follow

function THEME_preprocess_node(&$variables){
     $node = $variables['node'];
     if($node->type == "SOME_CONTENT_TYPE")
          $variables['theme_hook_suggestions'][]='page__node__SOMETHING';
}

Then create page--node--SOMETHING.tpl.php in your theme folder. To get the values of the fields you can use the entity module and do something like the following code (I supposed field_something is machine name of one of your fields):

function THEME_preprocess_node(&$variables){
     $node = $variables['node'];
     if($node->type == "ANY_CONTENT_TYPE"){
        $variables['theme_hook_suggestions'][]='page__node__SOMETHING';
        $wrapper = entity_metadata_wrapper('node',$variables['node']);
        $variables['title'] = $wrapper->title->value();
        $variables['something'] = $wrapper->field_something->value();
     }
}

By this code $title and $something variables are available in  page--node--SOMETHING.tpl.php file.


How do you turn off clean URLs in the database? How do I turn off clean URLs in Drupal 8 from the database? What table do I look in and what variable do I have to change?

In drupal 8 this setting has been removed:

'clean_url' configuration setting removed; clean URLs are autodetected each request

I checked the database, there is really no setting with this name.


How do I filter a view by the results of hook_node_access? I have been trying to wrap my head around a specific problem for a few days now and have been unable to find a solution. Here's my problem:

In my LMS I'm performing pretty complex access checks. (In particular, I need to check permissions over references: A lesson should be accessible, if it's part of some course that's marked accessible for that specific user.) I have already written a module implementing hook_node_access and, so far, everything is working fine. Here's part of the code:

function mymodule_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account){
  $type = $node->bundle();
  $user = $account->getAccount();
  $uid = $user->id();

  // only handle the lesson content type
  if ($type === 'lesson') {

    if ($account->id() !== 1) {

      // first, check the user's access to the lesson itself
      $lessonaccess = ...

      // then, check the user's access to the referring courses
      $courseaccess = FALSE;
      if ($node->hasField('reverse_entity_reference')) {
        $parentcourses = $node->get('reverse_entity_reference')->getValue();

        foreach ($parentcourses as $course) {
          $coursenode = \Drupal\node\Entity\Node::load($course['target_id']);
          // perform access checks for the referring course
          $courseaccess = $courseaccess || ...
        }
      }

      // combine the results; teasers should always be accessible
      if ($lessonisteaser || ($lessonaccess && $courseaccess)) {
        return AccessResult::allowed();
      } else {
        return AccessResult::forbidden();
      }
    }
  }

  else {
    return AccessResult::neutral();
  }
}

The problem is that I would now like to create a view listing all lessons that are accessible to the current user. So, simply filtering by node access -- as is straightforward to achieve in Views -- is not sufficient, as I need to filter by what is returned from the access checks in hook_node_access.

Can anybody think of a way to make that possible? Maybe storing the result somewhere?

The problem here is that hook_node_access is a PHP function that has nodes passed through it, but Views is doing a database query for the relevant nodes. These two are incompatible, as Views would have to fetch every node in the system from the DB, then pass them all through that function, which would add major overhead.

Drupal's solution to this is the node grants system, which writes a set of grants to the {node_access} table, which can then be used in querying nodes.

To implement a grants system, you'll need to implement hook_node_access_records(), which is called when each node is saved, and sets up a number of rules by which the node being save is allowed to be accessed. Then you implement hook_node_grants(), which generates a set of potential grants for the current user, and tries to match them with the grants created in hook_node_access_records(). When there is a match, the user is granted permission to access, and this will work with DB queries.


Views 3 "no results behavior" for different languages I use i18nviews for the translation and it works fine! Under the Point "no results behavior" can i only choose Global:Textarea, but this is not allowed in different languages.  What can i do?

This is a bug which is currently being worked on.


Disable profile field when module that created it is disabled? I have created a module that adds a field to the user profile. When I disable the module, I want the field to no longer be shown on the user profile. I do not want to wipe it out completely, since I do that on uninstall. I want it to come back with the original data when the module is reenabled I just want to have it not display when the module is disabled. Is there a way to do this? I am using Drupal 7 and the field is a text field and it is set to the default formatter when I create the instance. Is there a setting I can set the instance to in hook_uninstall that will hide it?

I managed to accomplish it through code by setting the field instance:

    'display'       => array
      'default'     => array(
        'label'     => 'above',
        'type'      => 'hidden',
        'weight'    => '1',
        'settings'  => array(),
      ),
    ),


need a help with if:else conditions cck function ruh_microblog_item($node) {
  $profile = content_profile_load('profile', $node->uid);
  $ava = theme_imagecache('microblog', $profile->field_photo[0]['filepath']);
  $noava = theme_imagecache('microblog', 'sites/default/files/imagecache/user_block_small/imagefield_default_images/no_photo.png');
  $content .= '
';
  $content .= l($ava, 'user/' . $node->uid, array('attributes' => array('title' => $profile->title, 'class' => 'micro'), 'html' => 'true'));
  $content .= l($profile->title, 'microblog/'. $node->uid, array('attributes' => array('class' => 'microname', 'title' => 'Микроблог - '. $profile->title)));
  $content .= check_markup($node->title, $format = 'Full HTML', $check = TRUE);
  $content .= '

';
  $content .= '
' . l(format_interval((time() - $node->created), 1, NULL), 'node/'. $node->nid) . ' назад
';
  $content .= '
';
  $content .= '
';
  return $content;
}

The code above displays a CCK field (field_photo), but what happens if the user has an empty "field_photo"?
Would the following code work?

if ($profile->field_photo == TRUE) {
  $content .= l($ava, 'user/' . $node->uid, array('attributes' => array('title' => $profile->title, 'class' => 'micro'), 'html' => 'true'));
}
else {
  $noava = theme_imagecache('microblog', 'sites/default/files/imagecache/user_block_small/imagefield_default_images/no_photo.png');
}

if(!empty($profile->field_photo)) {...}

Should be able to work for you.


How to make JS Async and eliminate unnecessary JS? I've been told this could be done with the Magic module but I couldn't find documentation\videos\readme anywhere for it so I ask how to do these specific things with it in my Drupal 7 site:

How to make JS Async?
How to eliminate unnecessary JS?

I need this for trying to take care the known Page spped insights advice "Eliminate render blocking JS above the fold content". Thanks.

Update: This could be done with AdvAgg module easily, see the following answer by Mikeytown2:

you can use async_js for loading asynchronly.

and in hook_js_alter you can remove js files you don't want to have on the page.

you can also place the JS at the bottom of the page in your theme's html.tpl.php, by printing

<?php print $scripts; ?>

just before the </body> tag.


Allow blank search/list all items with 1.x apache solr module When a user enters a blank search, by clicking "search" right away, or entering the search result url directly, the initial version of the Apache Solr Search Integration module, 6.x-1.x series, tells the user to "Please enter some keywords".

I would like it to issue the empty search, thereby returning all available results. This question List all available items with Apache Solr if the search keyword is empty asks the same for the second generation of the module, 6.x-3.x and 7.x-1.x, but that answer doesn't apply.

I've tried hacking out the if ($keys == '' check that yields the "error" message, but that simply results in no results at all.

I ended up with the below patch that seems to do the trick. The patch looks much larger than it needs to because I corrected the indentation after I removed an if.

Anyone that considers using this patch should be aware that this will hack the module. You should understand what that means, and be using a make file to avoid future complications.

$ diff -u apachesolr_search.module_ apachesolr_search.module
--- apachesolr_search.module_   2013-02-11 10:12:17.814561087 +0100
+++ apachesolr_search.module    2013-02-11 13:29:10.450336901 +0100
@@ -159,24 +159,22 @@
   if (isset($_GET['filters'])) {
     $filters = trim($_GET['filters']);
   }
-  // Only perform search if there is non-whitespace search term or filters:
-  if ($keys || $filters) {
-    // Log the search keys:
-    $log = $keys;
-    if ($filters) {
-      $log .= 'filters='. $filters;
-    }
-    watchdog('search', '%keys (@type).', array('%keys' => $log, '@type' => t('Search')), WATCHDOG_NOTICE, l(t('results'), 'search/'. $type .'/'. $keys));

-    // Collect the search results:
-    $results = search_data($keys, $type);
+  // Log the search keys:
+  $log = $keys;
+  if ($filters) {
+    $log .= 'filters='. $filters;
+  }
+  watchdog('search', '%keys (@type).', array('%keys' => $log, '@type' => t('Search')), WATCHDOG_NOTICE, l(t('results'), 'search/'. $type .'/'. $keys));

-    if ($results) {
-      $results = theme('box', t('Search results'), $results);
-    }
-    else {
-      $results = theme('box', t('Your search yielded no results'), variable_get('apachesolr_search_noresults', apachesolr_search_noresults()));
-    }
+  // Collect the search results:
+  $results = search_data($keys, $type);
+
+  if ($results) {
+    $results = theme('box', t('Search results'), $results);
+  }
+  else {
+    $results = theme('box', t('Your search yielded no results'), variable_get('apachesolr_search_noresults', apachesolr_search_noresults()));
   }
   if (empty($form)) {
     // The form may be altered based on the query that was run.
@@ -998,9 +996,6 @@
     $get['retain-filters'] = '1';
   }
   $form_state['redirect'] = array($base . $keys, $get);
-  if ($keys == '' && !$queryvalues) {
-    form_set_error('keys', t('Please enter some keywords.'));
-  }
 }


Entityform view block not displaying on page I can't seem to get Views-based blocks to show up on an Entityform page (Drupal 7). The View has a Contextual Filter of "Entityform Submission: Entityform submission ID". For the "When the filter value is not available" setting, I have "Provide default value: Content ID from URL" selected:

When I enter in an Entityform Submission ID in the Preview section, I get the results I'm after. However, when I place the Block on an Entityform page, it doesn't even show up.

What am I doing wrong?

I solved my own problem by changing the "When the filter value is NOT available" setting to "Provide default value: Content ID from URL" and using the 2nd path component (which is the Entityform submission ID):

This works for me. But I can imagine a scenario where the ID is obscured from the URL and this wouldn't work.


comment per page settings How can I change "Default comments per page" array to my own. What hook I need to use, if it needed?
hook_form_FORM_ID_alter(&$form, &$form_state)
with FORM_ID = node_type_form

$form doesn't contain this value

Drupal pulls the number of comments per page from variable_get('comment_default_per_page' . $node->type).   Its default is 50.  To change this go to content type X -> edit, then save.

To change the 50 to something else, you can create you own custom module and have this code

function example_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'node_type_form' && isset($form['comment'])) {
        $form['comment']['comment_default_per_page']['#default_value'] = 70;
    }
}

If you want to change it somewhere else,  then I recommend calling variable_set('comment_default_per_page' . $node->type,  'MYVALUE').  See below where it is hard-coded
inside comment.module & comment_form:

$form['comment']['comment_default_per_page'] = array(
  '#type' => 'select',
  '#title' => t('Default comments per page'),
  '#default_value' => variable_get('comment_default_per_page_'. $form['#node_type']->type, 50),
  '#options' => _comment_per_page(),
  '#description' => t('Default number of comments for each page: more comments are distributed in several pages.'),
);

function _comment_get_display_setting($setting, $node) {
  global $user;

  if (isset($_GET[$setting])) {
    $value = $_GET[$setting];
  }
  else {
    // get the setting's site default
    switch ($setting) {
      case 'mode':
        $default = variable_get('comment_default_mode_'. $node->type, COMMENT_MODE_THREADED_EXPANDED);
        break;
      case 'sort':
        $default = variable_get('comment_default_order_'. $node->type, COMMENT_ORDER_NEWEST_FIRST);
        break;
      case 'comments_per_page':
        $default = variable_get('comment_default_per_page_'. $node->type, 50);
    }
...

and inside comment_render($node, $cid = 0) {

$comments_per_page = _comment_get_display_setting('comments_per_page', $node);


Passing $form_state data into \Drupal::entityQuery('user') I have the following D8 form

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['bulk_perfplans_roles'] = array(
      '#type'          => 'checkboxes',
      '#title'         => $this->t('Generate plans for which roles?'),
      '#options'       => user_role_names(),
    );
    $form['bulk_add'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Create new Performance Plans'),
    );

    return $form;
  }

I'm trying to pass the information into an entityQuery as follows...

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $selectedRole = $form_state->get('bulk_perfplans_roles');
    $uids = \Drupal::entityQuery('user')
      ->condition('roles', $selectedRole)
      ->sort('created', 'ASC')
      ->execute();

I'm trying to make it so it conditionally alters the query based on the user selected roles from $form_state. It's currently not working, and I'm not sure where to go next. Any thoughts?

Does $selectesRole have the expected value? I'm pretty sure you want to use $form_state->getValue('bulk_perfplans_roles') instead. Details here.

Also is it a single value field? You may need to pass an additional IN parameter to your field condition and do some additional prep if the result from getValue is an array.

Also make sure you're passing the machine name of the role and not the label.


Drupal 7, GPS lat, lng closes value, is it possible? After multiple attempts to figure out how to find the closest gps point from the lat & lng fields (field_data_field_lat & field_data_field_lng) I would like to ask if such is possible? Is there any module that provides a solution with which it's able to create two fields for lat/lng and use them at views to find the closest one from an exposed filter?

I assume that there is no such ready made solution. In that case, I would like to write my custom sql statement for D7. Unfortunately, D7 doesn't support the D6 sql query functions and also the pager_query function.

Therefor I would like to write a statement that would bind the lat and lng fields and give back the nearest - closest gps points.
Similar, one field statement is written at: http://www.techfounder.net/2009/02/02/selecting-closest-values-in-mysql/ where the union and ABS is used. I've found the union option but didn't figured out how to make the comparison for both fields within the D7 db sql layer.

Thank you in advance.

Have a look at this article: Creating a Store Locator with PHP, MySQL & Google Maps. Especially the section about "Finding locations nearby with MySQL" is hinting towards your solution.

As you can read in the mentioned  article, calculating the distance between 2 points given their lat/lon requires quite some math (Haversine formula). So, I guess that the performance optimization in the article you are referring to won't be possible. This because it will be hard to use an index to retrieve probable points.


How can I redirect properly? Long story short I replaced an outdated site with a Drupal site at its previous url, let's say oldsite.org. But the old site was also accessed from oldsite.org/THIS, I think because it was a subdirectory of a larger site or something. But there are old links around that use oldsite.org/THIS and we want those to go to the homepage of the new site.

What is the proper Drupal way to do this redirect? I have thought of a handful of possible hacks, but I want to do it right.
Maybe a small module to handle the redirect. Or even htaccess somehow?

301 redirects are considered the best way to handle redirected pages, for they inform search engines to update their databases with the new paths.
Edit your .htaccess file in a text editor. [Note: Be sure to save the file in "UTF-8" format.]

In the file, you will find the commands:

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on
  # Modify the RewriteBase if you are using Drupal in a subdirectory and
  # the rewrite rules are not working properly.
  #RewriteBase /drupal
RewriteBase /

Immediately after that code -- and before the Drupal-provided "Rewrite old-style URLs" commands -- add your rewrite rules using the following format:

#custom redirects
RewriteRule ^old/URL/path$ http://example.com/new/path [R=301,L]
#end custom redirects

For detailed discussion https://drupal.org/node/38960


Content status, view different fields, different roles I want to know if there are any modules for the following situation:

User X of role A creates a case (special node type). If user Y logs on (of role B). He sees a case has been submit. He then can add pictures to the case (user X can't do this, he doesn't have the rights). Once that is done User X will see a the new node and can check out the pictures (but can't change them, or delete). And so on untill the case has the status closed.

I've looked at some modules for this and the Workflow module seems to lack what I want to do here.

I'm pretty sure people must have done something similar to this so that's why I'm asking.

Modules I know i'll have to know:

Views (to get my lists of a content type with a certain status)

Is this possible at all in Drupal? Worst case scenario is that I'll extend a node with my own entity and keep the node id, and programatically change the state of the node and let users add pictures.

Thanks for reading!

If pictures should be part (field) of a case node type, use Field Permissions module to set separate permissions for different roles.

If pictures should be separate node type, use Entity reference module to reference parent case from picture node. On the case page you can add a Views block with pictures referencing this case with a button to add new picture.

In both cases you would need some custom code to support your particular workflow.


Does disabling a views features module remove the view from the DB Inherited a site with 3 features modules, one is just a collection of views. i disabled it in the features interface. expecting it to disable all the views that were defined in that features module. but nothing happened... the site is huge (full publishing house)

I disabled it because theme hooks were not being applied think this has something to do with the way features is implemented.

I would like to know if once you've imported a views only features module it is imported to the db. and i can continue believing that i've broken nothing.

Disabling features will not disable all views in that features.
Feature is only used to export configurations,views etc to avoid manual work. You need to disable view from its UI page.


How to alter query of block inside a panel I have a View that contains many blocks. I want to customize the query for a specific block.
I have tried views_query_alter() hook and $view->query->add_where, but in this case the query will be modified for all blocks.

Any idea of how to customize the query using add_where for a specific block?

You can check $view->current_display in your hook_views_query_alter to alter the query differently for each different block.


How can I "form alter" fields in a nested Paragraph, depending on where the field is used I have these entity types:

A node type: nodepage
A Paragraph type: pg_a
A Paragraph type: pg_b
A Paragraph type: pg_child

I have a content model which is:

nodepage
  ->field_a
    Referenced bundles: pg_a
      ->field_child
        Referenced bundles: pg_child
  ->field_b
    Referenced bundles: pg_b
      ->field_child
        Referenced bundles: pg_child

You can see that pg_a and pg_b both have a field called field_child which allows a reference to pg_child. This has great semantic meaning to the site architecture.

Now something I would like to do is form alter pg_child, but only when it is referenced from pg_a and not from pg_b.

In hook_field_widget_form_alter, where I think I should be doing my alters, I can do the following:

$field_definition = $context['items']->getFieldDefinition();

// Get the current field widget being built, eg `field_child_thing`.
$name = $field_definition->getName();

// Get the bundle, ie. `pg_child`
$targetBundle = $field_definition->getTargetBundle();

// Get the bundle that $targetBundle is attached to in this instance...
$instance = ???

I thought I could look further into the $context variable, but so far this has alluded me. The best candidate so far is #parents in the form, but when I only find a reference to field_child which is ambiguous.

I now suspect I can inject more $context from somewhere, maybe in the parent build.

In this scenario, we have field_caption being used in various places inside a cta paragraph. The business has asked to limit field_caption to 25 charaters, but only when it is being used in a node on an entity reference field called field_foo_cta.

First we add a #process callback to the widget based on whatever rule, by implementing hook_field_widget_form_alter:

function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, &$context) {
  $field_definition = $context['items']->getFieldDefinition();

  if ($field_definition instanceof FieldConfig) {
    $config = $field_definition->id();
    list ($entity_type, $bundle, $field_name) = explode('.', $config);

    if ($entity_type == 'paragraph' && $field_name == 'field_caption') {
      $element['#process'][] = ['\Drupal\mymodule\BusinessRules', 'alterFieldCaption'];
    }

  }
}

Then we create a new class in src directory of the module.

namespace Drupal\mymodule;

class BusinessRules {

  public static function alterFieldCaption(array &$element, FormStateInterface &$form_state, array &$complete_form) {

    // Use whatever logic to target instances of `field_caption`.
    if (reset($element['#parents']) == 'field_foo_cta') {
      $element['value']['#maxlength'] = 25;
    }
    return $element;

  }

}

Thanks @larowlan for help on this.


How to display a node as multi-step? I have installed Multistep module and it worked well for forms (e.g. save node, edit node). But when I switched to "Manage Display" tab and add "Multistep Form" group, it didn't work. No multistep form block appeared in Structure->Block for displaying a node.

I have also tried "Div" for displaying field group, but it's just a collapsible box.

Is it possible to display node as multi-step?

It is possible to use node as multi step form with help of  page break field  Module . Enabled it and make it as one of the field where want in the node


access node field variables in theming view-field How can I access a filed value of the node that I don't want to display in the view, is there any way to pass the field variable in $fields using view but not include it in display, I'm just want to use this field for checking a condition.

You can simply check "exclude from display" for this field.


How to disable obligated address fields in Drupal Commerce in checkout? In D8 drupal commerce there is a step after the customer selects checkout.

Left in the screen is de payment information which contains a form with:

Country
Company
First name, Last name
Street address
Postal Code
City

We only want :

Country
First name, Last name

I created a hook_form_alter but retrospection of the form gives me no clue which field I can adjust.

Also I checked in the profile if there are any options and I could not find them?

Any suggestion

You need to edit the address field on the Customer profile type.
See admin/config/people/profiles/manage/customer/fields/profile.customer.address
In more recent versions of Commerce this can be found under
admin/config/people/profile-types/manage/customer/fields/profile.customer.address


Views PHP references I would like to use Views PHP module in my Drupal Site.

But I don't have any idea on how to use this and I can't find good tutorial for this module.
Anyone who can suggest any references or videos for Views PHP Tutorial?

There exists good documentation in Project Page of Views PHP module and Documentation under Read Documentation link in project page..

How to Use Views PHP in views filter
How to Use Views PHP as Views Output Field..

Some existing answers and tutorials which can explain better you can find below..

How can I insert PHP code in Views?

http://eureka.ykyuen.info/2012/03/10/drupal-7-add-php-field-to-view/


How do you theme the node edit page? What filename do you use to theme the node edit page in Drupal 7?

If you are asking about theme()ing the page on which the node edit form is displayed, you would use page--node--edit.tpl.php.

More information on Drupal 7 Template Suggestions can be found here.


How do I download a JPG file from the server? I have written a custom module in which i have a download button like given below.

$form['topics_info_graph']['download_graph'] = array(
 '#type'  => 'button',
 '#value' =>  t('Download Graph'),
 '#button_type' => 'button',
 '#ajax' => array(
   'callback' => 'digitaliq_bckgrd_variable_ajax_download_callback',
   'wrapper' => 'download_graph',
   'event' => 'click',
 ),
);

Onclick of this button i need to download a jpg image which is located in the temp folder.
I'm able identify the file name and the path, Not sure how to download. any help?

function digitaliq_bcgrd_variable_file_download($filename) {
  $temporary_directory = variable_get('file_public_path', conf_path().'/files').'/tmp';
  $temp_path = $temporary_directory . '/';
  // Download logic should come here, any help?
}

You can set the response headers from the PHP code to trigger a browser download of the file, e.g, something like:

function digitaliq_bcgrd_variable_file_download($filename) {
  $tmp = variable_get('file_public_path', conf_path().'/files').'/tmp';
  $filepath = $tmp . '/'. $filename;
  if ($data = file_get_contents($filepath)) {
    $file = new stdClass();
    $file->contents = $data;
    $file->filename = $filename;
    return EXAMPLE_serve_download($file);
  }
  drupal_not_found();
}

/**
 * Serve a file for download
 * @param $file
 * An object keyed with filename and contents
 */
function EXAMPLE_serve_download($file, $type = 'application/octet-stream') {

  if (empty($file->contents)) {
    drupal_not_found();
  }

  $headers = array(
    'Content-Type'              => $type,
    'Content-Disposition'       => 'attachment; filename="' . $file->filename . '"',
    'Content-Transfer-Encoding' => 'binary',
    'Pragma'                    => 'no-cache',
    'Cache-Control'             => 'must-revalidate, post-check=0, pre-check=0',
    'Expires'                   => '0',
    'Accept-Ranges'             => 'bytes'
  );
  if (ob_get_level()) {
    ob_end_clean();
  }
  foreach ($headers as $name => $value) {
    drupal_add_http_header($name, $value);
  }

  drupal_send_headers();
  print $file->contents;
  drupal_exit();

}


Webform conditional calculation depending on selected options count Users register for a conference via a webform. There are options for choosing a city [mandatory] and 1-4 dates [at least 1 date has to be checked]. E.g. user checks NYC + 2015-08-07 and 2015-09-01.

The price for the conference bases on the days count: if all 4 days has been checked = X USD; if 1, 2 or 3 of 4 days = Y USD/day.

Now, I have to calculate the price based on total count of checked dates and send it to the user in confirmation e-mail. How to do it?

You have to use javascript for this and multiply the price with the number of days (the number of checkboxes checked).


Is it possible to download sandbox projects with Drush? Normally, one can download a module from drupal.org like this:

drush dl views

However, this doesn't work for sandbox projects.  Is there an easy way to download them or I am stuck with git clone?

It's possible to download sandbox project with drush using make file.

Here is example.make file:

core = 7.x
api = 2
; Sandbox module
projects[range_field][type] = module
projects[range_field][download][type] = git
projects[range_field][download][branch] = "7.x-1.x"
projects[range_field][download][url] = http://git.drupal.org/sandbox/Taran2L/1848632.git
projects[range_field][download][revision] = a1cc04da3c1dd957e6808b7e6a381c5970904863

Then you can execute it via:

drush make --no-core example.make # optional options are: -y --working-copy --no-gitinfofile --verbose


Generate hyperlink on each row for html table that contains database data I created Ajax based dependent dropdown list and based on the selected item I selected table from database and displayed html table as output.

Now I want to generate hyperlink for each row of html table .This hyperlink is used to access public files based on the fid

I think i cannot use views because i am generating html table based on selected item from dropdownlist

I would be more thank full if anyone can share some ideas

If you have custom code that generates the table then it should be easy to output the link to files as well.

I assume you are looking for info on how to get the link to the file having your file id from the database.

You will need this:
Given a File ID (fid) how can I get the HTML that represents that fid?

EDIT:
After you provided some sample code I was able to figure out what you need:

You need a slash in front of drupal.

<a href=\"/drupal/sites/default/files/" . $data->FileName . "\">


Best way to migrate content and various other changes from development to production I'm about to make a bunch of updates and changes to content types, views, themes and actually adding content on my development server.  I was wondering if there was an easier way to migrate things from development to production beyond doing the following:

putting the production server in maintenance mode.
copying over everything  (development -> production) from site root (excluding sites/default/settings.php)
exporting the development database and importing it on the production server
crossing fingers and hoping that nothing crashes for unforeseen reasons.

I've seen that there's already some posts on workflows that involve using the features module, but does it actually export content or settings changes to things like blocks and views?  I was wondering if there was a module or a tutorial that I wasn't able to find on google that gave some good advice on this.

The most user friendly way to do the content migration you are talking about is by using the Backup and Migrate module.

You'll want to upload and enable the module on both development and production instances. The project page links to this tutorial series for a more detailed explanation. I also saw a helper module that backs up your files directory too.

Features does in fact allow you to quickly import a "feature" to a website that you may have developed on your development environment and want to move to production.

Ideally though, you'd want to use features to develop locally and then push to dev/staging server. The final push you'd want to just replicate the database from dev/staging to lessen the chance of configuration errors.

You could also use Drush if you want to do more advanced operations. You can write your own Drush commands and with aliases you can have this down to one command in a terminal if you'de want to. You can rsync files, sqlsync the databases, and use features commands to sync configuration options. Drupalize.me has a nice series on some of this stuff.

I highly recommend Drush, if you are getting more into Drupal, and also recommend checking out Drupal 8's CMI initiative for what lies ahead: https://groups.drupal.org/build-systems-change-management/cmi

P.S. I would have posted more links but don't have the reputation yet to do so. So, just Google the missing pieces.


How can I prevent 'Error messages' to be shown to anonymous users? Like any Drupal site, my site also shows red notifications from time to time...

The problem is that when these notifications are error messages, they appear at the bottom of the site in a new "Pseudo-reigion"... I use the term "Pseudo-region" because they establish a new "Region" under the site.

It's not really a region but rather a white area with an H1 and some text under it. It is displayed with the word "Error" (as a title, using a <h1> HTML tag), and the text below it is "The website encountered an unexpected error. Please try again later.". This is how it looks like in my site:

So my single aim is to not display these error messages (and this whole "Pseudo region" actually), at least for anonymous users, since it's uglyfies my site.

I've tried to use the following CSS syntax but with no success:

body.not-logged-in div.messages.error {display: none !important;}

This "error" pseudo-region is extremely problematic since it appears even in cases when I hide the notifications themselves via the "Disable messages" module.

I'm sure this error is native to Drupal but I've already tried everything I know to remove it, so any help is appreciated.

An important note

It's a long story why, but disabling the errors through /admin/config/development/logging doesn't help in this case. I'm looking for a solution which is either CSS, a Javascript (not jQuery) tweaking of the css by the text itself, or, some change in the Drupal PHP code that will prevent to program of printing this error.

Like @Screenack suggested.

Navigate to /admin/config/development/logging
Set the radio to None
Select Save Configuration

Please note that I recommend keeping the errors on locally and trying to fix them.


Drupal -> User error: Failed to connect to memcache server I had someone install memcache for one Drupal project. Apparently we moved to another hosting. Upon completing the migration, the site is having issues with memcache.

Can someone guide me on how to remove the error? Please see below. I believe this is the right section for the topic, but if you find it inappropriate for this category, please feel free to move it. Thank you.

User error: Failed to connect to memcache server: 127.0.0.1:11211 in dmemcache_object() (line 415 of/home/searchpa/public_html/sites/all/modules/memcache/dmemcache.inc).

You need to check how mem cached was run on your hosts. You can check this like so:

ps -Af | grep memcached

Check if it has -l 127.0.0.1 in arguments. If it is the case then just restart memcached with correct IP address instead of 127.0.0.1.


How can I theme field collection forms? I have a field_field_collection in content type (used to field collection module and have unlimited value). It has a number of fields as in the picture below:

And I want customize theme for it as template as in the picture below:

How I can I achieve that? I tried to write a template for it, but the result is bad. When I click "add another item" the result looks like shown in the picture under my code below.

Here is my code:

    <?php
    kpr($form);
    print drupal_render($form['title']);
    $i = 0;
    foreach($form['field_field_collection']['und'] as $items){
    if(isset($form['field_field_collection']['und'][$i])) {
        ?>

                    <?php
                    print drupal_render($form['field_field_collection']['und'][$i]['field_field_01']);
                    ?>

                    <?php
                    print drupal_render($form['field_field_collection']['und'][$i]['field_field_02']);
                    ?>

                    <?php
                    print drupal_render($form['field_field_collection']['und'][$i]['field_field_3']);
                    ?>

                    <?php
                    print drupal_render($form['field_field_collection']['und'][$i]['field_field_4']);
                    ?>

    <?php
        $i++;
        }
    }
?>
<?php
    print drupal_render($form['field_field_collection']['und']['add_more']);
    hide($form['actions']);
    hide($form['additional_settings']);
    print drupal_render_children($form);
?>

And here is the result when I click "add another item":

If your requirement is to format Field Collection in Table Format, then Field Collection Table Module will help.


How to get the value of a custom field in hook_node_presave? Using hook_form_alter I have added a custom field in my node creation form

function custom_assignments_form_alter(&$form, $form_state, $form_id) {
//print_r($form_id);exit;
if($form_id == 'node_assignment_form'){

    $lecture_options = array();
    $lecture_values = db_query("SELECT nid, title FROM `node_field_data` WHERE nid IN (SELECT entity_id FROM
                        `node__field_module` WHERE bundle='lectures' AND field_module_target_id=:tid)",
                        array(':tid' => $selectedWeek))->fetchAll();
    foreach($lecture_values AS $key => $value){
        $lecture_options[$value->nid] = $value->title;
    }
    //print("
");print_r($lecture_options);exit;

    $form['field_after_lecture']['#access'] = FALSE;
    $form['field_after_lecture_tmp'] = array(
            '#title' => t('After Lecture'),
            '#required' => true,
            '#type' => 'select',
            '#options' => $lecture_options,
            //'#default_value' => print_r($form_state->getBuildInfo()['args']);exit;,
            '#weight' => 100,
            '#prefix' => '
',
            '#suffix' => '
'
    );
}}

How to get the value of field_after_lecture_tmp in hook_node_presave
I printed the node fields using $node->toArray() function. But this field is not there. In Drupal 7 I was able to access it.

You can't get the value in the hook_node_presave() because this is not a node field, as you says is a custom field that you create altering the form.

In this case you need to add a custom submit handler to use the value, something like this inside the hook implementation:

function custom_assignments_form_alter(&$form, $form_state, $form_id) {
// ...
  if (isset($form['actions']['save_continue']['#submit'])) {
    array_unshift($form['actions']['save_continue']['#submit'], '_node_revision_delete_form_node_type_submit');
  }
// ...
}

And in the function you can access to the value and perform your actions

function _node_revision_delete_form_node_type_submit(array &$form, FormStateInterface $form_state) {
// Getting the form values.
  $field_after_lecture_tmp = $form_state->getValue('field_after_lecture_tmp');
}


Memcache module is working but with a strange error I have Memcache enabled both on Drupal and the server... It seems to be configured fine on the server-end (both by port & Settings.php).

If am being accurate, PSI grades even went up in about 4-5 points... So seemingly my site does use Memcache... And yet, Cron gives a strange error:

  PECL Memcache version 2.2.5 is unsupported. Please update to 3.0.6 or
  newer.

Tried to Google the error (or part of it) and found just nothing... I've also spoke with the server's support team and one of them told me to ignore this error... I'm not sure if this is the right thing to do... Will glad for the advice of Veteran drupal developers...

"Not supported" doesn't necessarily mean that it shouldn't work at all. I guess in this case it only means you shouldn't complain in case something breaks.

You may want to check if you can install a newer version of Memcache on your platform, just to be sure and future-proof.


Get form select field values from view I'm struggling to find a working method for populating the key & value pairs of a select field (created with forms api) with data from a view.

e.g.. I have a view of 'location' content types.

In the form I've created I need a drop down showing all these location names and a reference from their content type as the key.

Can anyone suggest the easiest method?

In lieu of using Views to handle the query, for performance reasons you are probably better off doing something more direct with the db, just make sure that you follow standards for security when accessing the db via any method. Here is a link to the Writing Secure Code documentation - a must read for anyone delving into this area.


Why do I get an error after adding a .theme file? After creating (e.g empty) .theme file in my template folder, I get the following error message:

  The website encountered an unexpected error. Please try again later.RuntimeException: Failed to start the session because headers have already been sent by "/homepages/d825952918/htdocs/themes/universaldenker/universaldenker.theme" at line 1. in Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage->start() (line 145 of vendor/symfony/http-foundation/Session/Storage/NativeSessionStorage.php).

If I delete the .theme file, everything works again. I think it has something to do with opcache, because the path "/homepages/d825952918/htdocs/themes/universaldenker/universaldenker.theme" comes from the .opcache folder.

How can I tell Drupal not to use it and clear all the cached files?

I suspect that your .theme file was not actually empty. Please try the experiment again and check the file size. If it is 3, then your file starts with a Unicode byte order mark (BOM).

The BOM is typically invisible in editors, but it gets sent to the browser before Drupal internally calls the header() function. This causes the error message you have seen.

From a glance on your paths, I would not conclude that the OPcache plays a role here.


hook_node_load for currently viewed node? I am trying to modify $node via hook_node_load but I do not have the current node in the list of $nodes handled by hook_node_load when I check it with devel's dpm. I only have some nodes from a node_load_multiple call I make in the module. Should I use hook_node_view instead? But hook_node_view says it can only modify node content.

It depends on when and where you trying to modify the $node. hook_node_load runs every time a node is loaded,whereas  hook_node_view runs only when a node is about to be rendered on the page.

The reason you might not be having the node id in question in you hook_node_load may be because the context in which you are calling hook_node_load might be wrong.
In order to test you can create a dummy callback and call the node_load() in it with you nid in question. You can see that once you call the node_load() api, it will invoke a call to hook_node_load.

Cheers


Why do I get Template "@bartik/block" is not defined? So I've created a small subtheme called bartik_graphql. It just overrides the 'Powered by Drupal' block. Besides it's bartik_graphql.info.yml file it has a templates directory containing one file block--bartik-graphql-powered.html.twig.

Contents of block--bartik-graphql-powered.html.twig:

{#graphql
query {
  admin:userById(id: "1") {
    name
  }
}
#}

{% extends "@bartik/block" %}

{% block content %}
  <div{{ content_attributes.addClass('content') }}>
    {{ content }} and some guy named {{ graphql.data.admin.name }}
  </div>
{% endblock %}

I've enabled my subtheme and set it to default. However I receive the following error:

  Twig\Error\LoaderError: Template "@bartik/block" is not defined. in
  Twig\Loader\ChainLoader->getCacheKey() (line 122 of
  web/core/themes/bartik/templates/page.html.twig).

What I expect to happen is have my subtheme's template override what is used by default to display the 'Powered by Drupal' message.

Drupal: 8.7.8
PHP: 7.2.17

Am I using extends wrong here?

I didn't know of Twig namespacing just until now. But what always worked for
extends and includes is to point to the template you want to extend/include directly, with the path starting from Drupal web root. So in your case it needs to say:

{% extends "core/themes/bartik/templates/block.html.twig" %}

You could also try the following which seems to follow theme inheritance but only up to the final base theme (which would be Classy).

{% extends "@block/block.html.twig" %}


Views conditional referenced field depending on user taxonomy term I have a Content-type that an admin can assign it's nodes to other users, and users are separated by their taxonomy term.

I'm using Entity Reference field to reference the user and overriding the output of it using views to reduce the user list to my preference.

This is how user referencing works:

Each user has a taxonomy term (e.g. Editor, Moderator, BadAss,
UberSuperEditor, etc...)
Each term parents more than 100 of users.

I want the Admin to be able to filter the output of users based on their taxonomy before selecting and assigning the node to them.

I want to make a view and make a conditional relation based on the "Term" selected then show the related users of that term.

I believe your explanation is describing the Reference Field Option Limit module:

  This module allows reference fields of several types to have their
  widgets' available options limited by the values of other fields in
  the current entity.

  This is best illustrated by examples:

  Example 1: countries and cities Suppose you want to label articles (or
  products, or businesses, etc) by both city and country so both can be
  used for filtering and searching. You could use a hierarchical
  taxonomy with city terms as children of country terms, but that
  doesn't make sense when you come to set up Views filters.

  With this module, create two separate taxonomies for country and city
  (or content types, or whatever entity you want to use). Then add a
  reference field so that each city points to its country: eg, the term
  'Paris' has a reference to 'France'.

  Then when editing an article, selecting 'France' in the country field
  will cause the city field to update to show only cities in France.

Give it a try and let me know how it works. The module currently supports Taxonomy terms and Entity Reference Widgets.


How to set value to an unlimited field collection using Rules? I want to copy the values of the field collections from entityform to node form, using the Rules module.

I tried to loop my field collection, then set value of the field collection from entityform to entitycreated, but this didn't work. I only get blank fields but the number of field collections are the same.

For example I have 5 field collection items per field collection and 5 field collections from entityform, after executing the rule I also have 5 empty field collections on the entitycreated.

Here's a sample of the rule:

{ "rules_after_submitting_entityform_custom_package" : {
"LABEL" : "After submitting entityform Custom package",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "entityform" ],
"ON" : { "entityform_update" : [] },
"IF" : [
  { "data_is" : { "data" : [ "entityform:type" ], "value" : "custom_package_entity_form" } }
],
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "sample",
        "param_title" : "Your Event",
        "param_author" : [ "site:current-user" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  },

  { "LOOP" : {
      "USING" : { "list" : [ "entityform:field-option-criteria" ] },
      "ITEM" : { "list_entity_form_option_criteria" : "Current list item" },
      "DO" : [
        { "data_set" : {
            "data" : [ "entity-created:field-option-criteria" ],
            "value" : [ "entityform:field-option-criteria" ]
          }
        }
      ]
    }
  },
  { "data_set" : {
      "data" : [ "entity-created:field-entityform-referenced" ],
      "value" : [ "entityform" ]
    }
  },
  { "entity_save" : { "data" : [ "entity-created" ] } },
  { "redirect" : { "url" : "[entity-created:url]", "destination" : "1" } }
] }}

Any idea, how to set this the right way?

Also, after creating this rule, I get this error when trying to delete the node created:

  Fatal error: Call to a member function delete() on a non-object in /sites/all/modules/field_collection/field_collection.module on line 830

I also tried using the Entity reference autofill module but it's not auto-filling the fields if I try it with Rules.

Any suggestions?

I see 2 errors in your rule, which is about processing a list of field collection items. Each of these errors is further explained below (though I'm not sure if they are the only errors).

Error 1: Rules Condition 'Entity has field' is missing

You should add a Rules Condition "Entity has field" (prior to being able to use it anywhere later on in your rule), which refers to your field collection field. Since your rule doesn't have such condition yet, it may also explain why you got those blank values so far.

For way more details about this, refer to "How to iterate over all field collection items in an eMail body using Rules?" (which also includes a rule in export format you may want to experiment with, if you only adapt some machine names of the used fields).

Error 2: 'Set a data value' needs to be replaced by 'Add an item to a list'

The Rules Action Set a data value that your Rule uses, can only set 1 value, while you're trying to update something that is a list.

So try to replace that action (ie the first data_set within the loop) with an action "Add an item to a list". When doing so, you probably also want to set "ENFORCE UNIQUENESS" to true, so that you "only add the item to the list if it is not yet contained". Even though for your case it may not make a difference, IMO that is a kind of safety-belt when using this action.

For way more details about this, refer to "How to set multiple values to an unlimited Term Refence field with Rules". While reviewing this, also pay attention to the "Fetch entity by ID" (within the Rules loop): I'm about sure (99%), you'll also need to add a similar "Fetch entity by ID" (but from the variable names you used in your rule it's hard to tell).


How to fetch data from already saved nodes to the edit-form for node creation? I have this scenario: a content-type A (event) has an entity-reference to another content-type B (location). Now, if an editor adds a new event and enters the (already existing) location by "autocomplete" or dropdown-list, i want to display all other events referenced to that location in the edit form to prevent dups (and redundant work).

I imagine this like a "check colliding events for this location"-button, that is triggering a view perhaps, but it has to be "before" saving the new node.

I already tried a bit with Rules-module, but there's probably no way to trigger this, though the rules-event "before saving new content" is just one step to late, because all the work is already done and all fields are filled...

Is there an approach on module-level for this or do i have to dive into modifying hook_form_alter?

Can someone point me in the right direction?
Thanks a lot in advance.

(Drupal 7.14, Views 7.x-3.3+122-dev, Calendar 7.x-3.3+0-dev, Date 7.x-2.5+8-dev, BEF, Address Field 7.x-1.0-beta2)

Update: So far i achieved an approach with a combination of Views and Panels. I override the standard "Node add/edit form" with a panel for my content-type A. To show the nodes of Content-Type B i added a view to that panel. They are shown in a two-column layout.

This works until i bring the "check" into the game. I added an exposed filter to the view, but when i use it, the node form is submitted instead of showing the filtered view.

I opened another question on this issue: Exposed filter of a view embedded in a panel overriding a node form triggers node submission. How to prevent this?

Question: Am I totally wrong with this approach (Panel with View and Form)?

Is it possible to have a custom form with the exposed filter "before" the node form to use the results of the filter to show the view?

I'm lost a bit...

Any help highly appreciated...

SOLVED:

Via http://drupal.org/node/1028952#comment-3968840 i found this little module

http://github.com/Itangalo/Node-creation-block--Drupal-7-

that resolved my issue.

Another possibilty (although in dev-status) is the use of this module: http://drupal.org/project/formblock


Creating Nodes Of A Content Type on-the-fly While Creating A Different Content Type Exposition

On a Drupal 7 site I have two Content Types with the following fields:

Scenes

Scene Name
Starring (Actor's names)
Streaming Link

Releases (DVD Releases)

Title
Description
Starring (All actor's names from all Scenes referenced)
Multiple Scenes (Entity references to the Scene Content Type)

My Question

Is there a Drupal 7 module or some technique that will allow me to create new Scene nodes on-the-fly while in the Create Release (node/add/releases) form?

Avenues I Have Explored

Field collection (No way to set Scene Name or Create separate nodes)
Node Reference + noderefcreate (Creates blank Scene without prompting for the fields)
Inline References is an abandoned Drupal 6 module that looks like it was meant for using with nodrefcreate to add the other fields like I want.

The Solution

Thanks to Clive's Answer, I've found Node Connect which is exactly what I needed.

If you are able to use the node reference field from the References module instead of the Entity Reference once the Node Reference Create module might be of some help:

Node Reference Create is an enhancement to the nodereference autocomplete widget that allows users to reference non-existent nodes.
When no matching node is selected, the new nodes are automatically created allowing for a seamless and intuitive user experience that is similar to free tagging.

I think the Contextual Administration module might also be useful too; there's some video documentation under the title of "Automatic Node Reference on Node Create" which will probably interest you the most.
UPDATE
You also might want to check out the NodeConnect module, it doesn't append the fields of the referenced node to the original node's edit form but does this instead:

Node Connect expands the node reference (of the references project) auto-complete field by adding a add new content and edit current content button.
The add a new button will all a new node to be added via a node add form and then return the user to the original form.
The edit button will take the user to the edit form of the referenced node, and return them when they are done editing.
Unlike other module that have provide this functionality this module does not use popups of kind, but caches the original forms when switch to child forms. This allows for multiple levels of adding and editing


is autopostback available in jQuery or Ajax for Drupal 6 sites. I know that autopostback is an ASP.NET piece of functionality. Is there something similar that I can apply in Drupal 6. I want to apply autopostback to a drop-down select list in a view.

All I have found so far is this piece of code:

document.getElementById('mytextbox').AutoPostBack = true;

<select id="autosubmit" name="autosubmit" class="autosubmit">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</select>

jQuery

$(document).ready(function () {
  $(".autosubmit").each(function (index) {
    $(this).change(function () {
      // write your custom trigger here.
    })
  });
});


Ajax reload of block on an event I have created a block through custom module. The content of the block should be random every time it loads the block. Call back function for this was written. The block also has a link say "Next" and when clicked on should reload the block with next random content.

How to get the block to reload without reloading the whole page when the link Next is clicked on?

Below is the module code I am using and js file.

/*
 * Implement hook_menu
 */

function my_module_menu(){
    $items['tips/reload']=array(
        'title' => 'Block Reload',
        'page callback'=>'reload_tip',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );
    return $items;
}

/*
 * Implement hook_block_info().
 */
 function my_module_block_info(){
    $blocks['my_module']=array(
        'info' => t('My Tips'),
        'status' => TRUE,
        'region' => 'content',
        'weight' => 0,
        'visibility' => 0,
    );
    return $blocks;
 }

 /*
  * Implement hook_block_view().
  */
 function my_module_block_view($delta=''){
    switch($delta){
        case 'my_module':
            $block['subject'] = t('Teamie Tips');
            $block['content'] = my_module_block_content($delta);
            return $block;
        }

 }

 /*
  * tips block content function
  */
 function my_module_block_content($delta){
    $output = "
".getrandomtip()."
";
    $output .="Next";
    return array('#markup'=>$output);
 }

  function reload_tip(){
    $tip = getrandomtip();

    return drupal_json_output(array('nexttip'=>$tip));
    exit;
 }

 function my_module_theme(){
    return array(
        'my_module_javascript'=>array('arguments'=>array(),),
    );
 }

 function my_module_init(){
    theme('my_module_javascript');
 }

 function theme_my_module_javascript(){
    $jsfile = drupal_get_path('module','my_module').'/my_module.js';
    drupal_add_js($jsfile);
 }

and my js file is as below

 (function ($) {Drupal.behaviors.my_module = function (context){
    $('a#NextTipLink').click(function(){
        var nextTip = function(data){
            $("#divTip").html(data.nexttip);
        }
        $.ajax({
            type:'POST',
            url:this.href,
            success:nextTip,
            data: 'js=1',
        });
        return false;
    });

}})(jQuery);

When I click on next link, pop up is coming with file having json object. But I need to reload the blok content. Am I doing something wrong?

To answer my own question below is the correct js file that is working.

(attach:function ($) {Drupal.behaviors.my_module = {function (context){
    $('a#NextTipLink').click(function(){
        var nextTip = function(data){
            $("#divTip").html(data.nexttip);
        }
        $.ajax({
            type:'POST',
            url:this.href,
            success:nextTip,
            data: 'js=1',
            dataType:'json',
        });
        return false;
    });

}};})(jQuery);


Regex Jquery in Drupal 7 not working (I have posted this on Stack Exchange as well)

I have a Drupal 7 page on which I need to remove text bracketed by "Keywords:" and "Description:", there are a number of text blocks all with the class .feedDesc

Page is here: http://www.cafe.gen.nz/node/236/feed-items

I have this working on a plain html page with this Jquery below but can not for the life of me make it work in the Drupal setup:

  $('p.feedDesc').html( function (index,text) {
    var regex = /Keywords(.*)Description/;
    return text.replace(regex,"");
  });

On the site the below does work indicating the whole stack is good.

  $('p.feedDesc').html( function (index,text) {
    return text.replace("Keywords","Foobar");
  });

Help !

Any ideas?

Update:

This works to do the find/replace:

    $('p.feedDesc').html( function (index,text) {
      text = text.replace(/Keywords:([^"]*)Description:/gi,"");
      return text;
    });

However I also need to trim whitespace and $.trim does not work:

    $('p.feedDesc').html( function (index,text) {
      text = text.replace(/Keywords:([^"]*)Description:/gi,"");
      text = $.trim(text);
      return text;
    });

If that's the exact code, then

var regex = /Keywords(.*)Description/;

should be

var regex = '/Keywords(.*)Description/';


Add empty links from a BreadcrumbBuilder For several specific parts of a website, I'm using a custom BreadcrumbBuilder, like this:

...
class SpecificBreadcrumbBuilder implements BreadcrumbBuilderInterface
{
    /**
     * @inheritdoc
     */
    public function applies(RouteMatchInterface $route_match)
    {
        $node = $route_match->getParameter('node');
        return $node->getType() == 'specificpage';
    }

    /**
     * @inheritdoc
     */
    public function build(RouteMatchInterface $route_match)
    {
        $node = $route_match->getParameter('node');

        $breadcrumb = new Breadcrumb();
        $breadcrumb->addCacheContexts(["url"]);
        $breadcrumb->addCacheTags(["node:{$node->nid->value}"]);

        $breadcrumb->addLink(Link::createFromRoute('Home', '<front>'));

        if (!empty($node->field_specific->value == '...')) {
          $breadcrumb->addLink(Link::createFromRoute('Specific pages', '<front>'));
          $breadcrumb->addLink(Link::createFromRoute($node->getTitle(), '<front>'));
        }

        return $breadcrumb;
    }
}

I would like to not use URLs for the two last links. Something like <nolink> (from the "Special Menu Items" module), but made from code.
I cannot find a way to add a text-only element to my Breadcrumb (and from what I can see, this class only have an addLink() function).

Any thoughts?

Drupal 8 has now a special <nolink> route to define empty links:

$breadcrumb->addlink(Link::createFromRoute('Empty link', '<nolink>'));

See issue (patch commited to 8.2.x): https://www.drupal.org/node/2693725


How can I send a Privatemsg using Rules and have the name of the site as the sender? I am using the Privatemsg and Rules module and I am trying to set up an automatically generated welcome message to new members registering on the site. This message will go into the new member's inbox.

I do not see a token that would allow the site's name to be the sender. All I see is the token for the logged in user. As expected, this doesn't trigger the message.

I have toyed with the [account] token. So when John creates an account, the message comes from John himself. This would be acceptable but it isn't consistent: Sometimes it works, sometimes it doesn't.

I know some tokens exist that are not always displayed. Does anyone have the name of the mysterious token? Or the magic to get this to work?

You could create an account for sending the messages and in rules, use direct input and enter its user id. That way, you could also see replies to welcome message.


Approach to adapting a traditional PHP solution into a Drupal module I find that traditional PHP development strategies don't help a great deal when trying to mould Drupal into areas it isn't directly built for and I'm hoping for assistance in how I might approach Drupal module development starting with a traditional approach.

I specifically have a project where I know pretty much how I would tackle it in PHP but am a babe in the woods trying to get this to work in Drupal.

I have new tables that I'm adding to the database that reference the 'user' and 'node' Drupal tables. The data used in the site from these tables will have some fairly complex SQL joins etc.

I will be needing a block or two; some summary pages; various admin pages; and permissions and access control for different items.

I've generated my rough wireframes but now I need to get this working in Drupal!

My traditional approach would be to create a class file for the data handling and then build pages or classes to handle the various views and controllers. Template files would be used for individual pages/blocks.

With this in mind what is the best approach to make this work in Drupal - or do I really need to think differently?

For my development environment I'm using PhpEd and running DrupalForFirebug in Firefox. I also use the Devel module and Themer where I need to. Building themes in Drupal is not a big issue for me but modules are something I've avoided.

Thanks :)

Here is what I would do (Drupal 7 assumed):

Look into http://api.drupal.org/api/drupal/modules--system--system.api.php/function/hook_schema/7 for defining your tables. You don't need to do anything special to reference node and user; Drupal doesn't make heavy use of foreign keys. Look into the database abstraction layer to get an idea of the functions you can use to interact with the database. db_select is particularly cool and naturally supports joins.
You may also want to look into Data and Views. Through the use of these modules, you may be able to cut down on the amount of custom code you have to write.
For the blocks, it depends on if they have dynamic or static content. If dynamic, look into Example: Block. If static, check out the Boxes module. Also look into Context as an alternative for placing the blocks instead of using the block visibility settings. This is assuming I understood your use of terminology when you said blocks.
For the pages, look into hook_menu. You can define your own this way; of course, you can also just create pages through the interface...so it depends again on what you meant.
Your development environment sounds fine. You'll find the tools you like as you go along.
There'll be a learning curve, but what you learn will be extremely reusable across future sites you build. It's worth it.


Use drush to download drupal core files directly into directory rather than subdirectory When you use drush dl normally, it will download drupal into a subdirectory ie: drupal-7.16

I would like to skip creating the subdirectory and just install the drupal root directory files into the pwd or destination directory.  ie: /var/www/install.php

Can this be done with drush commands?

Other shell workarounds also welcome and will be considered for answer status if this is impossible with drush.

drush dl drupal --destination=/var --drupal-project-rename=www


Put html in variable_get and Email I am using custom form to store email content using variable_set.
Using drupal_mail and hook_mail to send that content using variable_get.
Now in email I want to add image using html.

$pre_body = '
'
$body = variable_get('email_content');
$post_body = '
';
$full_body = $pre_body . $body . $post_body;
$message['body'][] = t('@body', array('@body' => $full_body));

but in email it shows me...

Hello obv
You have placed a bid on lot 'AA' of auction 'Test Curator Email'.
You currently the highest bidder.

how to achieve it...???

What you basically need to do is add headers to your email. You can implement a solution like the one that can be found in this Drupal.org's comment. The code is pretty much straightforward:

$body = '';
$body .= variable_get('email_content');
$body .= '';
$my_module = 'foo';
$my_mail_token = 'bar';  // A key to identify the e-mail sent
$from = 'tanvir@gmail.com';
$message = array(
  'to' => '"'.addslashes(mime_header_encode('Winnie Pooh')) .'"<james@gmail.com>',
  'subject' => t('Example subject'),
  'body' => $body,
  'headers' => array(
    'From' => $from,
    'MIME-Version' => '1.0',
    'Content-Type' => 'text/html;charset=utf-8',),
  );
$system = drupal_mail_system($my_module, $my_mail_token);
  if ($system->mail($message)) {
    // Success.
  } else {
    // Failure.
  }

Keep in mind that if your needs for html mailing become more complex and you need to theme your mails using template files or filter the mails' contents after the theme has applied, you can check the HTML Mail module.


Display users webform submission as readonly? Is there any built-in way to display the questions on a webform and the user's responses as read-only?

The site I'm building allows a user to answer survey questions up to a given cut-off time. Once they've submitted the answers and the time-limit ends they must be able to see what they said, but not change it.

I can't see any obvious way of doing that, is there an easy answer? :-)

I know I can modify each field individually in a form_alter hook but that's not ideal...

I have done an identical task, unfortunately this one of those unique use cases. Here is a snipped in my hook_form_alter

Basically, assuming there is no page element (not multi page):

if ($cutoff_time > $current_time) {

  $form['elements']['field_name']['#disabled'] = TRUE;

  $messenger = \Drupal::messenger();
  $messenger->addMessage(t('Time has expired, you can no longer change the value'), $messenger::TYPE_WARNING);

}

Otherwise (multipage):

$form['elements']['page_name']['field_name']['#disabled'] = TRUE;