Dependent Term Reference Autocomplete I want to make the options for a (secondary) term reference autocomplete field dependent on the values chosen in another (primary) autocomplete term reference field. How can I limit the options in the secondary term reference field?

I have two vocabularies called chapter and sub-chapters. In the sub-chapters vocabulary, I have an additional term reference field linking each sub-chapter to the chapter in the chapter vocabulary. (I wanted to use two separate vocabularies, rather than a single hierarchical vocabulary to make it easier to use separate exposed views filters).

On my main content form, I want to limit the sub-chapters available in the autocomplete field to the values chosen in the primary chapters autocomplete field.

I have looked at many different modules for achieving this and haven't found any that will work with my scenario so need to write some code to achieve this. I need to use autocomplete fields as there are so many terms to choose from for both the primary and secondary fields. I have been using the autocomplete deluxe widget for the primary field but I can just use the standard autocomplete widget if this makes it easier.

Can anyone give me a rough outline of the basic code I would need to write in order to achieve this?

I guess there will need to be an update of the options of the secondary term reference field whenever the values are altered in the primary term reference field using AJAX?

The basic process would be to make the 2nd field an Ajax (AHAH) created field.  Then in this method, set the #autocomplete render element to a URL that uses the first field's value.  Something like:

function simple_ahah_select($form_state) {
if ($form_state['storage']['content']['simple_select_parent']) {
  $element = array(
    '#type' => 'textfield',
    '#size' => '60',
   // Define a autocomplete_path depend on the value selected on the parent select field
    '#autocomplete_path' => 'simple/autocomplete/' . $form_state['storage']['content']['simple_select_parent']
  );
  }
}
return $element;

The Autocomplete URL can probably be a view if you don't want to write code.  But code would be faster.

See this d.o page for some more details


How to add page restrictions for blocks in drupal? I'm using the drupal administrator menu for the settings
there i have a page called /desert/234234
the block should appear only when the url is /desert/(desert_id)
how can i restrict that

In Drupal 7 you can use PHP code in the block's "Visibility settings."

Steps

Go to admin/modules and enable the PHP filter module

Go to admin/structure/block and click on "Configure"

Enter the following PHP code (including <?php and ?>) in the Page settings.


How to modify the comment body while in comment.tpl.php At a Drupal 7 website dedicated to a card game I'm trying to color the special characters for hearts and diamonds in all plain_text comments red.

Since I haven't found the way to modify the text filter yet, I'm trying to "hack" the file themes/bartik/templates/comment.tpl.php as workaround by inserting the 5 lines below:

<div class="content"<?php print $content_attributes; ?>>
  <?php
    // We hide the comments and links now so that we can render them later.
    hide($content['links']);

    $body = $comment->comment_body[LANGUAGE_NONE][0]['value'];
    $body =  str_replace('♦', '♦', $body);
    $body =  str_replace('♥', '♥', $body);
    print "\n\n";
    $comment->comment_body[LANGUAGE_NONE][0]['value'] = $body;

    print render($content);
  ?>

In the HTML comment between  above I can see that the string substitution has worked okay.

But the comment itself isn't modified.

I've tried modifying both $comment->comment_body[LANGUAGE_NONE][0]['value'] and $comment->comment_body[LANGUAGE_NONE][0]['safe_value'] but the comment is still unchanged.

I've studied the output of print_r($content) and var_dump($content) but still can't figure out how to modify the comment body.

If you insist, you can always go like that:

 print str_replace(
   array('♦','♥'),
   array('♦', '♥'),
   render($content)
 );

But instead of deprecated , use  and CSS. Consider classes for all 4 colours, for black and red, and for card marks altogether, for future styling ease.


How to add a default controller to the  route? Is it possible to add a default controller to the '<front>' route? There's no default controller defined in system.routing.yml.

I'm trying to get a handle on it by using the following code:

<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Get front page and set controller.
    if ($route = $collection->get('<front>')) {
      $route->setDefault('_controller', '\Drupal\mymodule\Controller\MyModuleController::MyModuleMethod');
    }
  }

}

But it doesn't seem to do anything. However this code works when replacing '<front>' with another route like help.main. Why is that? Do I have to add the controller instead of setting it?
(D8)

<front> is not really a route that can be resolved for an incoming request, it's just a helper for building a URL.

It works in the opposite way, you create a controller at whatever path you want, and then you set the frontpage to that path on the system information page aka in the system.site configuration object.


View that display single node which has id the same as last part of url (from last / to the end) I have an urls:

website.com/portfolio-entries/23
website.com/portfolio-entries/25

I would like to make an view for them to display node which has id the same as last part of url (from last / to the end).

I have red the description for View > Url (administration panel > Content > Views > My_view):

  This view will be displayed by visiting this path on your site. You may use "%" in your URL to represent values that will be used for contextual filters: For example, "node/%/feed". If needed you can even specify named route parameters like taxonomy/term/%taxonomy_term

So I set it to portfolio-entries/%entry_id (I hope I understood it right).

But how now make this view display only sinlge entry which has the id set to %entry_id?

I've tried with View > Filters (add) > ID but I can only set there hard-coded values (e.g. 23 makes this view display only entry #23). How can I place there my %entry_id?

In other words I was reproducing steps from https://www.ostraining.com/blog/drupal/views-specific-node/ (it's for Drupal 7 but it works the same way in Drupal 8) but instead of har-coding the id value I want to take it from last part of the url.

Normally the parameter is not named, it is a single % without name:

portfolio-entries/%

The example node/%/feed is also a single % in the middle part of the url. The third part of the url is a fixed feed, so that only urls with a /feed at the end will match.

To use this parameter for filtering you need to set a contextual filter in the advanced settings. If you only have one parameter, this filter will automatically get this, when selecting the field you want to filter.


Creating menus links for displaying articles with specific tags How would you go about creating a categorization system which categorizes after tags and then displays a link to the page with only the specific tags linked/posted?

Aka 1 page per category. On each page there is series of blog-posts/content which has the same tag (I believe this is called the taxonomy term?)

and then of course add the links to the pages to the menu (got this one as long as there is an URL)

Thanks!

You need the taxonomy menu module. Here is a quote about it (from the module's project page):

Transforms your taxonomy vocabularies into menus with ease!
Features:

Custom Menu per vocabulary
Uses the default taxonomy term path or custom paths
Integrate with Views
Integrate with Pathauto: use URL/path aliases
Does not interfere with other menu modules


Read access to user's nodes based for referenced users I am trying to figure out how to provide access to nodes of the users, which have referenced users. Please note that users are referenced not from nodes, but the user profiles, so I can not use the Node access user reference module. I also can not use roles-based access modules, because otherwise there would be too many roles to create as users on this website should be able to reference unlimited users. I also can not user organic groups.

So basically users have other users referenced from their profiles. All referenced users should have access to nodes authored by the users who referenced them.

That will require custom code.

Here's one way to achieve it:

You'll need to use hook_node_view to get involved when the node is about to be rendered.  Your code should:

Check the node's author and use user_load to gain access to the referenced users
Check to see if the current user (global $user) is in the list of referenced users
Permit or deny the node view, or change how the node displays, depending on the result.


HTML special characters changed to foreign characters We have a Drupal 6 website and are using tinymce for the editor. Many of our pages included the pound (£) sign as well as other special characters. All of these have now been changed into foreign symbols. The pound sign now appears as Â£ and other strange symbols such as â€“.

I've checked the source code and the original characters have been changed into the strange new characters. It seems like the only way to fix it is to manually edit all the pages. I checked the character encoding tag and this is set to utf-8.

Can anyone help with why this might have happened in one go? The only thing I can attribute it to is possibly running update.php. Also, is there an easier way to convert then all back again?

Many thanks,

Ben

It should work in a proper Drupal environment

  Several people have asked how to specify the character encoding that
  Drupal uses. The short answer is: you can't.

How can I change Drupal's character encoding

  Drupal uses UTF-8 for encoding all its data. This is a Unicode
  encoding, so it can contain data in any language. You no longer need
  to worry about language specific encodings for your website (such as
  Big5, GB2312, Windows-1251 or 1256, ...). Also, when Drupal imports
  external XML data (such as RSS or XML-RPC), it is automatically
  converted into UTF-8 (iconv support for PHP will be required for most
  encodings).

From Stackers


Update Drupal core via Pantheon I push all my local changes to the Pantheon git repository, then I update core via the pantheon dashboard. Now I pull from the Pantheon repository with "git pull git://github.com/pantheon-systems/drops-7.git master"
I am assuming that both versions are identical now, however, when I run git status I get a message that my branch is ahead of origin/master.

Can somebody explain this to me and how I get the local and repository in synch?

Yes that makes perfect sense - you've merged changes from the core repo, so your working copy is one commit ahead of your site's dev repo on Pantheon. Note that origin/master refers to the remote representing your repo, not drops-7.git

git push

to send the changes up to your dev site when you're ready to test, then pull them through the dashboard as normal.


Views + Multiple dates I have a view that will display content (nodes) in a fields display having a multiple date field. Another filter is set to date:enddate > now.

What I want is just one row per node, but cant get it to work.

I've tried the following:
a) In the date field's "Multiple field settings" I set "All values in the same row" and "show 1 value(s)"
Did not work, no change in output

b) Under "Advanced - Query settings" -> Use distinct.
No changes in output

c) Adding a filter date:delta = 0
This will remove the duplicates, but because of my other filter (date:enddate > now) the row will also not show up

d) Use the module "Views distinct".
The problem here is that this module will filter away nodes that happen to have a date on the same day of another node, so there are others missing.

So I'm stuck here, do you have an idea how to solve this?

Drupal7

Thanks, Marc

May be a long shot, but I had luck recently with turning on "Aggregation" for the View, so that similar fields are bundled together, and this solved duplication problems that distinct/the other settings you mentioned have failed to fix:


How to render a field of a taxonomy term inside a view template? I'm trying to display an image as a banner above the items of a view (which creates a block). The image is a field associated to a taxonomy term and the view is used to display all items which have this term. Is it possible to inject the image into the render array using a hook in order to access and render it on a specific location inside the view's template (for example block--views-block--example.html.twig)? I can't find a good solution anywhere on the web. I'm thinking of something like this (pseudo code):
function suitable_hook(&$vars) {
  $image = getFieldOfTaxonomyTerm('taxonomy_term', 'image_field_name');
  $vars['associated_image'] = $image;
}

If there are better approaches to this problem in general, please let me know as well. Thanks a lot in advance for your suggestions!

This can be done entirely from within the Drupal UI.
If you already have access to the taxonomy term in the view, you can add the term entity directly.
This is what the core taxonomy term pages view does.
To see for yourself, go to /admin/structure/views/view/taxonomy_term on a standard Drupal 8/9 installation.
In the header, you will find Global rendered entity: Taxonomy term. If you click this to open up the settings, you will see that Drupal is loading the term based on the argument {{ raw_arguments.tid }}, which is provided by the Contextual Filter Content: Has term ID. (Check the settings there as well.)
For your own block, I would use this same technique.  You say you want to render the image, not necessarily the whole taxonomy term.  To do that, I would create a new View Mode for the term that only has the image and whatever else you want to display.
You can create a View Mode for a taxonomy term by going to the "Manage Display" page for the relevant taxonomy vocabulary.
Then, in Views, in the header where you are rendering the term entity, you can set the view mode to your new custom view mode.


Attach a 5-star widget to a custom form How do you add a FiveStar widget to a (non-node) form using hook_form_alter?

$path = drupal_get_path('module', 'fivestar');
  drupal_add_js($path . '/js/fivestar.js');
  drupal_add_css($path . '/css/fivestar.css');

  $rating = votingapi_select_single_result_value(array(
        'entity_id' => YOURENTITY_ID,
        'entity_type' => 'YOURENTITY_TYPE',
        'tag' => 'vote',
        'function' => 'average',
   ));
   $form['votes'] = array(
      '#markup' =>  theme('fivestar_static', array('rating' => $rating, 'stars' => 5, 'tag' => 'vote')),
   );


Add a Button within the content type overlay window for the url link There is any way to add a button into the content type for example Article as show in the below figure

there is any module for adding the button within the content type in drupal 7.

The page in your screen shot is a 'node add' page for a particular content type in your drupal site. Therefore the best way to add more elements there is to utilize hook_form_alter()

<?php
function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'mynodetype_node_form') {
    dsm($form); // This function is available via Devel module. Here, it shows you the contents of $form in a structured manner, so that you know where to make the change to add a button.
    // Add code here to add button in the form etc.
  }
}
?>

The above code snippet assumes your module name is custom and your content type name is mynodetype

To understand what code you need to write to add new form element (in your case a button), refer drupal form api - http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7


How to unset a field in views? How can I unset a view field based on value of some other field in the same view ?
I cant use views php module ?
Is there any other option for it?

use hook_view_pre_render and in this, you need to check for that value in if condition...


How to display the number of contents of a node? We have a property site that we use to categorize our listings. I would like to know how to make each category show the number of content it has e.g. Sales(45), Lettings(20), etc.

Any help about how to do this? I am new to Drupal.

could you add some details to your question that will tell us WHERE you want to see these counts?   Is it in a page template? A view? A block?  The answer will change depending.

In the meantime, please look at this:
Count of nodes by type


Is it possible to force Views to collect a minimum count of nodes per group? I have a View that collects nodes of a certain type, grouped by term.

Term 1
 Node 1
 Node 3
 Node 4
 ...
Term 2
 Node 2
 Node 5
 ...

Can I force Views to list exactly 10 nodes per each term, rather than total of ten per entire query?

Check out Views Grouping Row Limit module.

From the project page:

  This is a basic Views style plugin that allows for a limit on the number of rows displayed within a grouping field.


How to add unique identifier to each submission? In short, I am trying to figure out how to add a custom and unique identifier to each submission from the Webform module.

Example: User fills out the Webform and submits. User then receives an email (email is captured from email field in Webform) confirming their submission and providing them with a Unique Identifier (ABC-14-001).

I know Webform asks what number to start the next submission (and I'm assuming this is considered the "SID"). If I am to utilize the SID, I need to be able to append the custom "ABC-14" prefix to each submission's SID.

I'm not very familiar with hooks (sorry for the ignorance), but I understand that hooks might be the only way, or at least most effective way, to accomplish this?

Update
Thanks all who responded! I have a working solution right now with this module:

function identifier_webform_submission_presave($node, &$submission)
{
  $component_id = 23; //that's your hidden field
  $submission->data[$component_id][0] = 'Text to be inserted';
}

You want to use hook_webform_submission_presave to record your special key. I would create a hidden textfield in the Webform that is optional so the value can be set by your PHP code upon submission.

For a basically full working example see Webform Issue #1964080.

To create your special value such as AB-001-12345 you just make a php function that creates a random string, or a string to your specifications:

function generate_special_submission_key() {
  $length = 10;
  $str = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
  return $str;
}


How do I make a profile select option on user registration? I thought this was easy but normal fields and media don't seem to do what I want. I can use normal fields, because it is Drupal 8 and the user is an entity. So all I want to be able to do is:

a) show the user a "profile picture" upload option upon registration
b) also allow them to choose one of the 5 pre-existing images I have uploaded
c) easily allow myself as admin to upload more images

Right now I'm thinking of doing a bit of a hack where I simply add an image field, but add another field with custom logic (somehow) that allows the user to choose an image.

But I was hoping someone can suggest something better? Or alternatively, advise perhaps on a way to re-use the image field and add a "choose image" feature to it?

P.s. I am trying to simply allow the user to choose an avatar when signing up. They must just be able to click on the one they like, out of a set of predefined options. If they don't like one, they must be able to upload their own.

Many problems in Drupal can be solved in more than one way. This is also one of them.

One way might be to use the Avatar Kit module.

Another might be to create a Select field with options linking to some images you uploaded to the files folder or similar. You'd probably have to do some custom formatting if you wanted to display the options as images, and not just links or text.

The complication comes in with your request to allow users to upload their own images if they don't like the present choices. Selecting one image from a set is simple enough, and allowing to upload their preferred one is simple enough, but the combination of these options isn't as simple, it's not so common, and requires more logic than is present in the core out-of-box.

A solution that is flexible and extensible is to create a separate Media Type for these user pictures, and use Entity Browser module to build a great user experience when filling their profile forms where they can choose from a set of images you chose, or are allowed to upload a new one. This solution isn't the easiest to implement though, or at least isn't to someone who expects these features should come out-of-box.

You have to think about the images uploaded by users, are they available to all users to use or are they limited to the person who uploaded the image? This affects how you structure your Media type, different access treatment usually means you need a separate structure for it.


Module that adds a script to the header How can I allow my module (created with Features) to add a new script to the head?

The script should be in the correspoinding module directory.

You can add a script using drupal_add_js and to have it added on every page, you can call it in hook_init.

Module directory path can be resolved by drupal_get_path('module', 'module_name')

module_init() {
  drupal_add_js(drupal_get_path('module', 'module_name')."/js/myscript.js");
}


How can I generate commerce file audio preview automatically? In a store of music files with the Commerce File module, how can I generate an audio preview of that file? Would be perfect if I could use the Rules module for detect the adding of file and SOX utility for audio trim (for example the first 20 seconds) and attach the generated file into another field.

If possibile compatible with Media and SoundManager2.

This sounds like an awesome companion module that could be created and would be popular. From a bit of Googling, you can use SOX or FFMPEG-PHP and the exec() command to actually trim the audio file. From there, it's just a matter of saving this audio file to a new field. I would not use rules unless you need to expose it in the interface for some reason. You could easily achieve the programmatic saving of an audio field (probably a specialized file field) using any of a number of examples out there on the web.

Found an example here: https://stackoverflow.com/questions/7884960/ffmpeg-php-code-example-to-trim-mp3-file

<?php
exec('$ sox input.wav output.wav trim 0 10');
?>


If user leave comment, print "You have already written a comment" how to show this 'You have already written a comment' if user have comment in this node -)

Thanks for any help)

Try this

function custom_cv_node_view($node, $view_mode, $langcode) {
 global $user;
  if ($view_mode == 'teaser') { /* Teaser */
      $cid = db_query('SELECT cid FROM {comment} WHERE uid= :uid AND nid = :nid', array(':uid' => $user->uid, ':nid' => $node->nid))->fetch();
      if($cid) {
          $node->title = $node->title.' (Commented)';
      }
  }
}


How to remove a URL from my XML sitemap? I have installed the XML sitemap module and included all my articles in the sitemap. By default, also the URL node/add/article is added, but I do not want that since anonymous users cannot visit this page. Google's Search Console tells me that the URL is blocked by robots.txt - which is great - but I want to get rid of the warning messages that show up due to the blocking.

How can I delete the URL node/add/article from my sitemap?

This could either happen because it's node/add/article is included within a menu that's indexed by XML Sitemap or a custom path that was added.

In either case, a drush command can update the path flag for exclusion & rebuild the sitemap so that it's no longer there.

drush sqlq "UPDATE xmlsitemap SET status = 0 WHERE loc = 'node/add/article'"
drush xmlsitemap-rebuild

If you need to do this through the UI, you'll need to check either /admin/config/search/xmlsitemap/custom for a custom link or edit the menu item that contains it (/admin/structure/menu).


drupal commerce - when adding to cart on review page, get redirected back to checkout I am using Drupal commerce. For particular reasons, I found it necessary to programatically add items to the cart one the review page. The problem is: when I do this, I get redirected back to the checkout page, which I don't want. Here is my code:

foreach($registrants as $key=>$registrant) {  //for each additional registrant in the event order object
          if($key == 0 && $memberStatus == "Member") { //the first additional registrant gets the member price free, if the applicant is a member
            //$line_item = commerce_product_line_item_new($product, $quantity);
            //$line_item = commerce_cart_product_add($event->product_id, $line_item, TRUE);
            commerce_cart_product_add_by_id($memberGuestId);
            $order = commerce_order_status_update($order, 'checkout_review', FALSE, TRUE, t('Additional registrants have been added to the cart'));
            drupal_goto('checkout/' . $order->order_id . '/review');
          }
          else {
            commerce_cart_product_add_by_id($nonMemberGuestId);
            $order = commerce_order_status_update($order, 'checkout_review', FALSE, TRUE, t('Additional registrants have been added to the cart'));
            drupal_goto('checkout/' . $order->order_id . '/review');
          }
        }

I even tried forcing it back to the review page with a goto, and no luck. What is happening here?

I had this exact same problem with a very similar workflow.  I created a workaround to this issue by integrating the commerce_cart_product_add($uid, $line_item) function from the Commerce Cart module into my custom module.  This way I could test what was happening in Commerce without hacking the contrib module.  From there I discovered that the issue stemmed from an invoked rule at the bottom of this function:

 rules_invoke_all('commerce_cart_product_add', $order, $product, $quantity, $line_item);

Removing this rule from my local version of this function solved the redirect issue. I looked through the Commerce Settings and the Rules UI in the Drupal admin to see if I could find this rule to disable it, but I could not find a reference to it anywhere.  This is not the best solution, but for now it solves the redirect issue.  I would be interested to hear if anyone else has run into a similar issue though.


Put the access callback function in a separated file When I put the access callback function in a separated file I get an error.

$items['node/%node/join'] = array(
    'title' => t('Join Game'),
    'page callback' => 'agentweb_membership_join',
    'page arguments' => array(1),
    'access callback' => '_agentweb_membership_join_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
    'file' => 'join.page.inc',
);

When I put _agentweb_membership_join_access() in join.page.inc I get an error, but when I move it to agentweb_membership.module everything works correctly.

Why does it happen?

The access callback has to be in the same file; the file passed in the "file" property gets loaded only if the access callback returns TRUE. The only other "solution" is to use an include at the top of your module.


Recurring events - retrieving/displaying the dates for the current "instance" of the event I have an events page on my (D7) site, and the admin can set up recurring events.

When creating a list of the events, I see the recurring events come through in the right place intermingled with the non-recurring events.  However, their dates don't show up right:

My "normal" date fields only ever show the date of the first event.  There's an answer to this issue here, but that requires table layout.  I'd prefer not to have to use table layout.  Any idea how I could do this without it?

Secondly, I'm using a pre-process field (called big_date) to create a second date field but with a different display to the first, so I can display the same date in different formats simultaneously.  How could my code here know which of the many dates in $vars['node']->field_date_and_time[LANGUAGE_NONE] is the one relating to the "current" instance of the event?

I spoke briefly about this to a Drupal expert I know, and he suggested moving to using Views and the Fields view type as apparently the integration between the Date module and Views is very good.

At present, I'm using a View but also using Viewmodes and the preprocess field.  His point was that all of this could instead be accomplished by just using my existing content type, not using a custom viewmode but using the Fields view type.  And that this should be less buggy.


Route AJAX failure messages to console instead of popup How can I prevent ajax failure popups and instead route the failure to the console log instead?  Is this something I can do with Drupals implementation of jQuery?

You can check Prevent JS alerts module..

Project page says

  This module is an answer to the issue: #1232416: Drupal alerts "An
  AJAX HTTP request terminated abnormally" during normal site operation,
  confusing site visitors/editors, which describes a big problem for end
  users: JavaScript alert();'s for end users on AJAX errors by Drupal
  core. Perhaps it will one day become obsolete, when this bug is fixed.
  End users are often frightened of these errors and don't know, if they
  have "destroyed the internet" ;)

  This module completely suppresses ALL JavaScript alerts and instead
  prints them to console via console.error! Important: It does NOT ONLY
  suppress the core alerts, but also custom alerts.


Set Image Custom Field as Open Graph Image in Metatags I have installed the Metatags module along with the Open Graph and Twitter Card extension modules. In my default content type, I have added an Image field that allows an image to be uploaded for use on Facebook and Twitter.

Now I cannot get the Metatags module to accept this image custom field as the entry for the og:image and Twitter Card Image fields. I've tried entering [node:field_image] but the meta tags do not get added to the source code. If I enter a URL the tags appear.

How do I get Metatags to dynamically include a corresponding image for each page in the Open Graph and Twitter Cards metadata?

I used drupal_add_html_head in my case. In my theme template.php.

$og_image = image_style_url('200x200', $node->field_gallery_preview_image[LANGUAGE_NONE][0]['uri']);
// OG image meta property.
drupal_add_html_head(array(
  '#tag' => 'meta',
  '#attributes' => array(
    'property' => 'og:image',
    'content' => $og_image,
  ),
), 'node_' . $node->nid . '_og_image');


How can I override or alter a module's help text? I am trying to override or alter Layout Builder's default help text. Is is possible to do this? If so, how?

I have added some help text in a hook_help() function in a custom module but I can only get it to add to Layout Builder's help text. I can't find a way to override the default text.

I don't recall doing exactly this, but I think you can use a hook_module_implements_alter() for this:

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook === 'help') {
    unset($implementations['layout_builder']);
  }
}

This should disable layout_builder_help(), and then just yours will run.  A hook_help_alter() would be nice, but I don't recall ever seeing an issue for it.


Indexing custom entity types I have two custom content entity types that I've created with a module. Neither one of these content entity types extends Node.

Our site has a search bar, and we want to include these two custom content entity types in the core search results (searching within the name of the entity only).

The only demo I can find on this topic is this, but this doesn't seem to be working for me. I've modified the code to match the identifiers and properties of my custom entity type, placed the code in the module's src/Plugin folder, cleared the cache, but my entity type still does not appear as an option in /admin/config/search/pages. Only Content and Users continue to be available search pages. Additionally I am suspicious that this work for a custom content entity type since I am trying to match search index IDs with entity IDs in the queries within the code, but I think this consistency is only maintained for node entities.

I have also tried following this method of defining a search page through Views, but none of the options this poster has selected are available when I try to make a search page for a custom content entity type (for example "Search" as a filter criteria is not present).

I can't seem to find very much useful info on this topic and am wondering if there are any resources I'm simply missing or misunderstanding.

To answer the question, if an entity wants to be included in drupal search, it has to provide a search plugin, which is when discovered listed by the plugin manager from the search module. If not you should first check the annotations of the plugin, see for example the plugin from the node entity:

namespace Drupal\node\Plugin\Search;

/**
 * Handles searching for node entities using the Search module index.
 *
 * @SearchPlugin(
 *   id = "node_search",
 *   title = @Translation("Content")
 * )
 */
class NodeSearch extends ConfigurableSearchPluginBase implements AccessibleInterface, SearchIndexingInterface {

To debug this, clear the cache and list the discovered plugins:

drush ev "var_dump(\Drupal::service('plugin.manager.search')->getDefinitions())"

If all went well you have a third plugin here together with the node and user plugin and you should see it in the admin UI of the search module in the select box Search page type.

To give a recommendation, I agree with the commment from @Berdir. It's not worth the effort to write a custom search plugins, better use Search API:

  This module provides a framework for easily creating searches on any
  entity known to Drupal, using any kind of search engine.


I want to link file in views to files/fid I have a content type, which has video and image attachment. In the view created on this content type, the table shows the thumbnails of video and image file. I want to link thumbnails to files/fileid. And not sites/all/default/files/filename....I want to link to file-id and not generic file...
   Tried rewrite results as a link but the lin there doesn't supports the tokens (file:fid or file:filename)..

Adding a field above the field in the list doesnt works because, he has build content on content type that has attachment, and not mere files..Means the view is not build on files so it will not have the field file:filename or file:fid...
         The best solution is to use custom formatter module {https://www.drupal.org/project/custom_formatters} and in that use html plus tokens with following code

This will give the required link to the thumbnail, if you dont want thumbnail you can put text there....

and then in views select the custom formatter for the required image field...


How to list nodes in a view as checkboxes? For my drupal 8 website I need to create a view page with nodes of particular content type. I need to dispaly them as a list of checkboxes, and further implement a PDF manual, composed out of the "checked" nodes. Is it possible to implement it using standard Drupal tools?

You'll have to test that particular combination yourself, but there are modules that seem the best fit to try first.

To be able to select individual views results and perform actions on them you need Views Bulk Operations (VBO). You don't need to look further than that module for this part.

The tricky part is the PDF. Views PDF and Printer, email and PDF versions might have helped in D7 but they don't seem to be ready in D8.

In D8 Entity Print seems to be the rightful heir so try that one. Also I don't know how far you can get without custom code. You will probably need to use Rules to create the action that would be executed with VBO.


Use part of Date field for grouping / sorting in View I'm creating a Schedule page. I created a Schedule Item content type with a Date field which tracks the date and the time. I want to create a View which lists Schedule Items grouped by Date alone.

My data looks like:

2012-07-01 08:00, Event 1
2012-07-01 11:00, Event 2
2012-07-01 11:30, Event 3
2012-07-02 09:00, Event 4
2012-07-02 10:30, Event 5

I would like this to be displayed grouped by the Date portion of that Date/time object so it looks like this:

2012-07-01

08:00, Event 1

11:00, Event 2

11:30, Event 3

2012-07-02

09:00, Event 4

10:30, Event 5

I tried setting the Grouping on my View to use my Date field using a format that only displayed the Year-Month-Day. However, when doing the grouping, it is still grouping on the real value and not the displayed value. Meaning that since each Date/time value is actually different in the time portion, each value is being used as a separate group.

Is there a way I can generate a virtual field which only contains the Date portion of my Date/time field so that I can use it to properly group all items by Day?

Go to your view and add an extra date field, but hide it from display. Use that as the grouping field. Then create a views template for that field. You can look at the template name suggestions, something like views-view-field--field-date-1.tpl.php would work

The default content of that file would be

<?php print $output; ?>

But you need to replace that with

<?php print date('F Y', strtotime($row->node_data_field_date_field_date_value)); ?>

Where 'F Y' is the PHP date string format http://php.net/manual/en/function.date.php


#autocomplete_path doesn't present a "spinny thing" I'm working on adding an autocomplete field to a node edit form using hook_form. The field should not be stored in the database; hence the reason I am not adding a field to the node itself.

I seem to have the required components for autocomplete to work, and I've double checked spelling errors, but I can't get a "spinny thing" (aka "throbber") to appear, and there are no attempts by the browser to retrieve data from the autocomplete path when entering data into the autocomplete field.

Javascript is working in the browser, as evidenced by a working entity reference autocomplete field.

Some code:

/**
 * Implements hook_menu()
 */
function cao_contenttypes_menu() {
    $items = array();

    // autocomplete
    $items['cao_contenttypes/user/autocomplete/%'] = array(
        'title'            => 'Autocomplete C&O users',
        'page callback'    => 'cao_contenttypes_cao_handler_users_autocomplete',
        'page arguments'   => array(3),
        'access arguments' => array('C&O Administrator'),
        'type'             => MENU_CALLBACK,
    );

    return $items;
}

/**
 * Implements hook_form()
 */
function cao_handler_form($node, $form_state) {
    // Fields in the node add form are merged into the array we create
    // here.
    global $user;

    // Fetch the title field.
    $form = node_content_form($node, $form_state);

    // get a list of users that are allowed to have cao
    $users = _cao_contenttypes_cao_handler_users();
    $form['c__o_user'] = array(
        '#type' => 'select',
        '#title' => 'CaO User',
        '#weight' => -20,
        '#description' => 'Choose a user.',
    );

    if (0 < count($users)) {
        dpm($users, 'users');
        $form['c__o_user']['#type'] = 'textfield';
        $form['c__o_user']['#autocomplete_path'] = 'cao_contenttypes/user/autocomplete';
    } else {
        $form['c__o_user']['#options'] = array();
    }

    return $form;
}

function cao_contenttypes_cao_handler_users_autocomplete($str) {
    if (!$str) {
        return;
    }

    // choose users from among a limited subset
    $users = _cao_contenttypes_cao_handler_users();
    $list = array();
    array_walk($users, function ($item) use ($str, &$list) {
        $comp = substr($item->name, 0, strlen($str));
        if ($comp == $str) {
            $list[] = $item->name;
        }
    });
    drupal_json_output($list);
}

What you should do is change $item inside your menu() hook to be

$items['cao_contenttypes/user/autocomplete'] = array(
    'title'            => 'Autocomplete C&O users',
    'page callback'    => 'cao_contenttypes_ceao_handler_users_autocomplete',
    'access arguments' => array('C&O Administrator'),
    'type'             => MENU_CALLBACK,
);

eg, remove the trailing % (Drupal will add in the string for you just fine when it has one) and then inside your callback do something like this:

function cao_contenttypes_cao_handler_users_autocomplete($str='') {

  $list = array();
  if ($str) {
    // choose users from among a limited subset
    $users = _cao_contenttypes_cao_handler_users();
    array_walk($users, function ($item) use ($str, &$list) {
      $comp = substr($item->name, 0, strlen($str));
      if ($comp == $str) {
        $list[] = $item->name;
      }
    });
  }

  drupal_json_output($list);

}

eg, give $str a default value and always return the array of results, even if empty.

Additional comment:  Consider cache()ing the output of _cao_contenttypes_cao_handler_users() if it is a heavyweight function.


How to pass an extra argument to an entity form? Suppose, I've two entities:

entityA
entityB

A user creates an entityA and has the option of creating multiple types of entityB referenced from a single entityA. For example, a parent-child relationship. Parent being entityA and child being entityB.

In the module, I want the users to select an entityA object, go to a new page page for creating entityB. So, at this point, (add-form of entityB) I should have the data of that particular entityA object that the user clicked on.

So, far I'm able to get "all" the data of entityA on the add-form of entityB, which is of no help as I'm unable to get the specific id of entityA.

The relevant code are:

routing.yml

mymodule.entityB_add:
  path: '/admin/config/mymodule/{entityA}/entityB/add'
  defaults:
    _entity_form: 'mymodule_entityA_entityB.default'
    _title: 'EntityB'
  requirements:
    _entity_create_access: 'mymodule_entityA'

When, I'm shown the form addition page of entityB (type: ../../testentitya/entityA/add), how do I pass the entityA object to the form and what will be the structure of entityB's config schema?

Have a look at https://www.drupal.org/node/2310425

This should explaine everything needed.

Here is an example how it would look like:

mymodule.entityB_add:
  path: '/admin/config/mymodule/{entityA}/{entityB}/add'
  defaults:
    _entity_form: 'mymodule_entityA_entityB.default'
    _title: 'EntityB'
  requirements:
    _entity_create_access: 'mymodule_entityA'
  options:
    parameters:
      entityA:
        type: entity:entity_type_a
      entityB:
        type: entity:entity_type_b


How do I change the style used by the "Archive" view to show the dates? By default the "Archive" views module displays the dates as "May 2011." I want to change them to "2011 year May."

How do I do that? Is it possible?

from the instructions of googletorp: i made the following but it's not work. what's wrong with my code?

created a module named customviews. which have files(customviews.info, customviews.module, customviews.views.inc)
customviews.module has code:

    <?php
      function customviews_views_api(){
        return array('api'=>2);
      }

function customviews_views_data_alter(&$data) {
             // Set the argument to the handler you named above.
             $data['node']['created_year_month']['argument']['handler'] = 'custom_handler';
           }
customviews.views.inc has code

 <?php
   class custom_handler extends views_handler_argument_node_created_year_month {
     function construct() {
       parent::construct();
       $this->format = "Y year M month";
     }
   }

i have cleared the cache.

i put the function customviews_views_data_alter(&$data) into the .module file. it's still can't work. what's wrong with it?

Views haven't supplied an easy way of doing this, but it is possible. To do this you would have to create your own handler and make views use that:

1. Creating own handler

class custom_handler extends views_handler_argument_node_created_year_month {
  function construct() {
    parent::construct();
    $this->format = 'F Y'; // Write your custom format here.
  }
}

2. Making view use your custom format

function module_name_views_data_alter(&$data) {
  // Set the argument to the handler you named above.
  $data['node']['created_year_month']['argument']['handler'] = 'custom_handler';
}

Update.

The custom_handler class or whatever you choose to call it need to go in it's own file. For Drupal 7 the standard is to put it in a dir called handlers which is located in the dir that you specify with hook_views_api, and add the file as include in the .info file (Look at the views module for reference).
For the module_name_views_data_alter you need to replace module_name, with the name of your module.
Clear cache.


Edit CKEditor's config programmatically I've created a Drupal 8 module that adds a custom plugin to the core's CKEditor. This plugin allows users to add tabbed content to their pages.

The problem is that the plugin adds a class to the  element it creates and CKEditor by default removes classes from most elements once you save the node.

I can change CKEditor config for Basic HTML editor (admin/config/content/formats/manage/basic_html) to allow classes in  elements by changing  to  in "Allowed HTML tags" input.

Now I would love to be able to do this programmatically somehow. How can I change the configuration for CKEditor in a Drupal module? Especially the "extraAllowedContent" config value.

The project for reference purposes can be found at https://github.com/j-vee/ckeditor_tabber

I had a similar case, i had to add a few attributes to the basic_html format in the Allowed HTML tags so it could work with the module editor_advance_link which allows the users to add title, class, id and target attributes to the a tag when using the core's CKEditor.

So this is what i did with some code i found here ( https://www.drupal.org/files/issues/allow_image_style_to_be-2061377-224.patch)

if ($filter = FilterFormat::load('basic_html')) {
    if (($filter_html = $filter->filters('filter_html')) && $filter_html->status) {
      $config = $filter_html->getConfiguration();
      $allowed_html = !empty($config['settings']['allowed_html']) ? $config['settings']['allowed_html'] : NULL;
      $matches = [];
      if ($allowed_html && preg_match('/<a ([^>]*)>/', $allowed_html, $matches)) {
        $new_attributes = array_filter(explode(' ', $matches[1]));
        $new_attributes[] = 'target';
        $new_attributes[] = 'title';
        $new_attributes[] = 'class';
        $config['settings']['allowed_html'] = preg_replace('/<a ([^>]*)>/', '<a ' . implode(' ', array_unique($new_attributes)) . '>', $allowed_html);
        $filter->setFilterConfig('filter_html', $config);
        $filter->save();
      }
    }
  }

Don't forget to include:
use Drupal\filter\Entity\FilterFormat;

This code is needed to be run only once, so i had to include it in a .install file in a custom module.


Overriding region theme file for user profile pages I am on D7 using Omega as a base theme. The <h1> tag of my theme can be found in the region--content.tpl.php theme file.

But I want to override this theme in one specific situation: on the user profile pages, I don't want the title to be set on region--content.tpl.php. I will take care of the title on the user-profile.tpl.php theme file. So what I want is a theme file that will override the custom default region theme file in the specific situation where user profiles are being viewed. That theme won't have a title set in it.

I have tried creating specific themes called region--content--user.tpl.php and region--content--user-profile.tpl.php, but they didn't override the default region--content.tpl.php theme. Any ideas? Thank you.

I found solution on this blog http://eureka.ykyuen.info/2012/05/10/drupal-7-customize-region-template-file-for-specific-content-type/
and here is my code to suggest a user profile region.

    function YOURTHEME_alpha_preprocess_region(&$vars) {
      $menu_object = menu_get_object();
      if (isset($menu_object->type) && $vars['region'] == 'content') {
        $vars['theme_hook_suggestions'][] = 'region__content__'.$menu_object->type;
        $vars['attributes_array']['class'][] = 'region-content-'.$menu_object->type;
      }
//theme suggestion for user profile
      elseif ($vars['region'] == 'content' && $vars['elements']["system_main"] && $vars['elements']["system_main"]["#entity_type"] == 'user') {
        $vars['theme_hook_suggestions'][] = 'region__content__userprofile';
        $vars['attributes_array']['class'][] = 'region-content-userprofile';
      }
    }


Can invite module work for existing users? I'm using UR and invite module.  I'm trying to make it so you can "friend" "existing" users.  I don't know why Invite is only set for e-mail address invites for just non-users.  I want A FB style "friend" request.  Is there a way to fanangle this though these modules? Or, do I have to go in another direction with it?

The Invite module serves to invite those who are not yet existing users to become ones. That's why you cannot use it to invite existing users.

Anyway, when using UR, at existing user's public profile, there's a Become USERNAME's friend link which you can use to befriend an existing user. This is an equivalent of the Facebook Add Friend button.

With the UR's user_relationship_invites module enabled, you can give users the option of specifying a relationship when inviting new users, e.g. friend. Together with the Contact Importer this would be an equivalent of the Facebook Find friends page.


How can I save form data on a node in Drupal? I want submit form data and save on specific node but I don't know that how to do?

function test1_menu() {
  $items['mytest'] = array(
    'title' => 'My Tes',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test1_form'),
    'access callback' => TRUE,
    'weight'=> 1,
    'type'=> MENU_NORMAL_ITEM,
  );
  return items;
}

function test1_form($form, &$form_submit) {
  $form['firstname'] = array(
    '#title' => t('First Name'),
    '#type' => 'textfield',
    //'#required' => TRUE,
  );
  $form['lastname'] = array(
    '#title' => t('Client Name'),
    '#type' => 'textfield',
    //'#required' => TRUE,
  );
  $form['submit'] = array(
    '#value' => 'Test',
    '#type' => 'submit',
  );
  return $form;
}

function test1_form_form_submit($form_id, &$form_state) {

}

In your submit function, you just need to create a node, e.g.

$values = array(
  'type' => $node_type, // Drop in your desired node type.
  'uid' => $user->uid, // Want to set an author?
  'status' => 0,
  'comment' => 0,
  'promote' => 0,
);
$entity = entity_create('node', $values);

To make your life easier, I recommend to use entity_metadata_wrapper:

$ewrapper = entity_metadata_wrapper('node', $entity);

Now, you can just cycle through your form data and add the values to the correct fields of your node:

$key = '<MACHINE_NAME OF YOUR FIELD>'; // e.g. "field_firstname"
$val = '<VALUE TO BE SET FOR THAT FIELD>'; // e.g. $form_state['values']['firstname']
$ewrapper->$key->set($val);

This of course depends on the field type, the above works for example for simple textfields. Finally, if all is set, just save the freshly created node:

$ewrapper->save();


Wrapp every form item select with div, excluding label im trying  to wrap form item  with

I had success with hook_from_alter and #prefix #suffix that is wrapping whole element with div like this:

I used this hook:

function em_form_alter(&$form, &$form_state, $form_id){
if ($form_id == 'user_register_form') {
    $form['field_gender'][LANGUAGE_NONE]['#prefix'] = '
';
    $form['field_gender'][LANGUAGE_NONE]['#sufix'] = '
';
}
}

And i got this.

    Gender
    <select id="edit-field-gender-und" name="field_gender[und]" class="form-select required">
        <option value="_none">- Select a value -</option>
        <option value="1">Male</option>
        <option value="2">Female</option>
    </select>

But what i need to accomplish is this:

Gender

    <select id="edit-field-gender-und" name="field_gender[und]" class="form-select required">
        <option value="_none">- Select a value -</option>
        <option value="1">Male</option>
        <option value="2">Female</option>
    </select>

And i would like to have this on every select on whole website, so maybe hook_form_alter isn`t so good idea?

This theme function should do what you need.

function mytheme_select($variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id', 'name', 'size'));
  _form_set_class($element, array('form-select'));

  return '
<select' . drupal_attributes($element['#attributes']) . '>' . form_select_options($element) . '</select>
';
}


Adding a "title" field to video thumbnails in the Video Module I would like to attach a textfield field to the video field. How can I go about doing that programmatically?

How do you attach a field of a field?

You can use hook_form_alter(), there is no any built-in option to do that.

You can also use the Field collection module to create a new field collection with a text field, and the video field.

  Provides a field-collection field, to which any number of fields can be attached.

  A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.


How do I create a field that accepts only unique values? I am using the Field Collection module because I have some complicated relation between the fields, and I have tried to integrate it with the Unique field module, without success, because Unique field module is not supported by the Field Collection module.

Is there a simpler method to check if the value is unique, and the to display validation error, if the value is not unique?

Unfortunately, Drupal 7 has not this feature by default, so there must be a method to do this.

You need to implement this in a custom module, here is a sample code to achieve this:

function custom_node_validate($node, $form) {
  if ($node->type == 'page') {
    //retrieve the value for your field using Entity API
    $wrapper = entity_metadata_wrapper('node', $node);
    $value = $wrapper->field_collection->field_unique->value();

    //Execute a count query to see if there's other similar values.
    $query = new EntityFieldQuery;
    $query->entityCondition('entity_type', 'field_collection_item')
      ->fieldCondition('field_unique', 'value', $value)
      ->count();
    $count = $query->execute();
    if ($count > 1) {
      form_set_error('field_unique', 'Unique field value is already used.');
    }
  }
}

A few disclaimers:

I am really stocked by the complexity of Field Field Collection API and it was pretty complicated to find good information about how to retrieve values and make queries.
I really enjoy doing SQL queries (see How to change the legnth of field settings) but I tried to only use the API instead of doing a simple query on the table field_data_field_unique. However it may not yet be perfect so please feel free to chime in.
The form_set_error() isn't highliting the field, I was unable to find the correct name.

Here are the documentation I used:

hook_node_validate()
Get value of a field collection field (answer from fago), the Entity API module and entity_metadata_wrapper().
Checking out EntityFieldQuery (by Ryan Szrama) and the API.

Edit: Following chx advice, to pass directly field_name to fieldCondition().


Views CSV export, not exporting complete data I have one CCK field called "Questions" with type "Long text".

I'm trying to export this value using views data export in CSV format.

Below is the text to export.

  Some text, trying to export.

While export in CSV, I have got only partial data. ie, "Some text".

After comma "trying to export" value is missing in CSV.

Is there any way to get complete data?

Note: Other than "views_pre_render"

As an alternative to the 2 modules you're using, you could also try to use the Forena module (Disclosure: I'm a co-maintainer of it). Here is a quote from that page:

  ... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

And here is another quote from Reasons for considering Forena, related to the "CSV" in the question here:

  Reports created by Forena ... can be saved (exported) as PDF documents with embedded graphs. Other supported formats for saving a report are CSV, XLS, DOC, HTML, etc.

These are the steps for creating such CSV files are:

Create a custom SQL query, in which you have the full power of SQL at your fingertips (and various extra features related to it provided by Forena).

Here is a (basic) SQL I'd use for answering this question:

  SELECT nid, title, type, uid

  FROM node

Create a custom report, either by an admin, or by just any regular user who is either familiar with creating what is called 'FRX files', or otherwise using the WYSIWYG report editor.

Using the WYSIWIG editor, in about 10 secs (= a few mouse clicks later on) you'd have a report for which the layout (in XHTML) would look like this:

List of all nodes in this site

Report caption

      nid
      title
      type
      uid

      {nid}
      {title}
      {type}
      {uid}

As part of "designing" this report, you should enable (within what is called "Document types") the option to export to CSV files (possible other options like XLS, DOC, PDF, etc also if appropriate).

At then end just "Save" the design of such report. This will be used later on, to retrieve all the specs of your report, when you want to browse (run, execute) your report.
Browse the report (= enter its relative path, or click some menu link if your design included such link) and then use the CSV link in it to actually save (= export) the report in (eg) CSV format.
Note: These steps do not require any PHP coding.

Bonus: instead of CSV format, you also have an option to format it as either XML or JSON. For more details on that, refer to "How to add a link to the CSV download to my module page, for a report created with Forena?".

Example

Here is an example of (part of) a CSV file I created using the above approach:

  nid,title,type,uid

  33,Demo title,article,19

  39,"Demo, with some commas in the title, just a test",article,1

  72,Yet some other Article,article,8

  73,Article with some field collection data,article

The above CSV file contains:

the typical CSV header in record 1 of it, whereas the values in this record correspond with what was requested in the report design, as specified with the ...	 tags in the report layout.
1 record for each result that was selected.
1 specific record with a node title containing commas (shown with surrounding "...").

More info

For more info (prior to installing/testing Forena), checkout these links:

Reporting samples, about data stored in some SQLite database, and including things like drill down reports, creating charts (using the PHP SVG Graph library), etc.
Forena Documentation, which you also get in your own site after installing the module.


Notice: Undefined index: elements in block_theme_suggestions_block() I created block in the custom module. This block works, but I see Notice in the Recent log messages.

  Notice: Undefined index: elements in block_theme_suggestions_block() (line 179 of /var/www/html/drupal-8.3.x-dev/core/modules/block/block.module)

I see block_theme_suggestions_block().

function block_theme_suggestions_block(array $variables) {
  $suggestions = array();
  $suggestions[] = 'block__' . $variables['elements']['#configuration']['provider'];

And for my block $variables['elements']['#id'] is NULL.

I can't understand why my block can't pass the ID as other blocks.

The code I am using is the following.

/**
 * @Block(
 *   id = "hello_messages",
 *   admin_label = @Translation("Hello messages"),
 * )
 */
class HelloMessagesBlock extends BlockBase {

  // ....

  /**
   * {@inheritdoc}
   */
  public function build() {
    $config = $this->getConfiguration();
    $hello_messages = hello_messages_block_get_messages($config['amount_messages']);

    return array(
      '#theme' => 'block--hello_messages_block',
      '#type' => 'markup',
      '#content' => $hello_messages,
      '#attached' => array(
        'library' => array(
          // Custom .css styles for block.
          'hello_messages_block/hello_messages_block',
        ),
      ),
    );
  }
}

/**
 * Implements hook_theme().
 */
function hello_messages_block_theme($existing, $type, $theme, $path) {
  return array(
    'block--hello_messages_block' => array(
      'variables' => array('content' => NULL),
      'base hook' => 'block',
    ),
  );
}

This is the content of block--hello-messages-block.html.twig.

{% extends "block.html.twig" %}
{% set attributes = attributes.addClass('block-hello-messages') %}
{% block content %}
{% for key, value in content %}

{{ value.user }}

{{ value.time }}

{{ value.text }}

{% endfor %}
{% endblock %}

Why doesn't my block pass $variables['elements']['#id'] to the theme suggestion hook?

UPDATE:

Thank you, Berdir.
This solution helps me.

function hello_messages_block_theme($existing, $type, $theme, $path) {
  return array(
    'block--hello-messages-block' => array(
      'variables' => array('content' => NULL),
      'template' => 'block--hello-messages-block',
    ),
  );
}

You are not supposed to use the block template like this. This will be added automatically and it will be done so one level higher in the render array structure.

Check other block plugins, none of them use #theme like this, like SystemBrandingBlock::build()

You have two options:

Define the block template suggestions like system_theme() does it and then overidde the output there. (the first in the list is the one for the branding block linked above, so you can easily connect the two things)
Make your own template for the content within the block. It will be wrapped by a generic block template, so you don't have to worry about that at all.


Tabledrag with locked children We use Drupal's tabledrag component in one of our interfaces and we've got this requirement we don't know how to solve.

Basically, we have a tree structure with elements of 2 types - let's call them A and B.

An element of type A can be moved to any location in the tree (we use weight and parent-child relationships).
An element of type B is always a child of an A, and cannot be moved to another A. It is locked under it's parent A. However, it can be sorted with sibling As.

So for a tree like:

A1
\- A2
 - B1
 - A3
   \- B2
    - A4
    - B3
    - B4

We can move A3 up to be a child of A2, and all it's children (B2..B4) will move along (like normal).
However, B1 can only be moved up and down (in regards to A2 and A3), as we can change it's weight, but cannot change it's parent: it's locked under A1.

I have searched for a while, but have not found any examples of this. Is this even possible with Drupal's core tabledrag ?

Ok, found it.

If one includes this code, it will prevent all items with a class "tabledrag-parent-locked" from being dragged into another group, while still being orderable with their siblings.

This code uses a CSS class of 'parent' to target the parent relation field. The actual CSS class would obviously depend on what CSS class you pass to drupal_add_tabledrag().

/**
 * @file
 * Override some Tabledrag functionality.
 */

/**
 * If the dragged row has a class of 'tabledrag-parent-locked', check the rows with which it might get swapped.
 * If the row it gets swapped with has a different  parent, block the swap by returning false.
 * This will prevent the locked child from being dragged to another parent.
 *
 * @override Drupal.tableDrag.row.isValidSwap
 */
// Keep the original implementation - we still need it.
Drupal.tableDrag.prototype.row.prototype._isValidSwap = Drupal.tableDrag.prototype.row.prototype.isValidSwap;
Drupal.tableDrag.prototype.row.prototype.isValidSwap = function(row) {
  if (this.indentEnabled && $(this.element).hasClass('tabledrag-parent-locked')) {
    var nextRow;
    if (this.direction == 'down') {
      nextRow = $(row).next('tr').get(0);
    }
    else {
      nextRow = row;
    }

    if (nextRow && $('.parent', this.element).val() !== $('.parent', nextRow).val()) {
      return false;
    }
  }

  // Return the original result.
  return this._isValidSwap(row);
}

/**
 * If the dragged row has a class of 'tabledrag-parent-locked', disable the indentation for the duration of
 * the drag. Store the old indentation setting in _indentEnabled.
 *
 * @override Drupal.tableDrag.dragRow
 */
// Keep the original implementation - we still need it.
Drupal.tableDrag.prototype._dragRow = Drupal.tableDrag.prototype.dragRow;
Drupal.tableDrag.prototype.dragRow = function(event, self) {
  if (self.rowObject && $(self.rowObject.element).hasClass('tabledrag-parent-locked')) {
    if (self.indentEnabled) {
      self._indentEnabled = true;
      self.indentEnabled = false;
    }
  }

  return self._dragRow(event, self);
}

/**
 * Restore the original indentation setting, if needed.
 *
 * @override Drupal.tableDrag.dragRow
 */
// Keep the original implementation - we still need it.
Drupal.tableDrag.prototype._dropRow = Drupal.tableDrag.prototype.dropRow;
Drupal.tableDrag.prototype.dropRow = function(event, self) {
  if (self._indentEnabled !== null) {
    self.indentEnabled = true;
    self._indentEnabled = null;
  }

  return self._dropRow(event, self);
}


Editing a single field on a rendered node On a given content type called Tracking (which is also a Group), I have a title, OG fields, and a repeating text field called Log. I'd like a member of the OG to be able to enter a value and submit without entering the edit field.

The use case is a mobile site with observers in the field. They won't be editing the entire node. They're just taking notes into a repeating text field?

Is this possible or should I seek a different solution? Or should I just rely on Comments for such a function?

Use whatever works for you. I've used the below modules to achieve this type of functionality before.

Look at Field Permissions:

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.

And look at Editable Fields to easily edit a field when not on the edit page:

  This module allows CCK fields to be edited on a node's display (e.g.
  at node/123), not just on the node edit pages (e.g. node/123/edit). It
  also works within views etc. Anywhere a 'formatter' can be selected,
  you can select editable (or click to edit).

Or maybe Editable Views, modules:

  Editable Views lets you create Views where the fields can be edited.
  Fields show both the current value and a form to edit it. A 'Save'
  button allows saving of all the entities shown in the View.

  Editable fields can be added on the base entity as well as on entities
  brought into the View by a relationship. Other, non-editable fields
  may be added to the View, in which case they function normally.


Create a user Programmatically in Drupal 6.22 i was trying to create a new user Programmatically in drupal 6.22 but i can't seem to get it working.
I need to make a web service that can do a few things, one being create a new user.
This webservice is going to be consumed by a mobile device.
I was just trying to test the user_save from outside drupal in just a simple php file and it doesn't seem to work. I just need to know what i'm doing wrong.

Here is my code

<?php
    require_once(includes/bootstrap.inc);
    drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
    // Get an array of roles
    $roles = user_roles();
//Basic account information
$user = array(
    'name' => 'username',
    'pass' => 'Password',
    'mail' => 'email',
    'status' => 1,
   'init' => 'email',
    'roles' => array(array_search('authenticated user', $roles) => 1),
);
// See if the user exists by calling Drupal's user_load()
$existing_user = user_load(array('name' => $user['name']));
    if (!$existing_user->uid) {
    // Save the user
    $user = user_save(NULL, $user);
    }
?>

EDIT: Added the drupal_bootstrap, still not working for me.

Looks like you've included the bootstrap.inc but you haven't actually bootstrapped drupal.

Example:

require_once(includes/bootstrap.inc);
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


Loading a Taxonomy Term form for a user I have a User Profile page that loads specific taxonomy terms (associated with a user account and its form, user_profile_form) to filter specific content with. I've tried to implement these forms independent of any user profile form logic, but its troublesome to work around this logic.

This is further compounded by the fact that all this behavior is essentially split across a ctools_wizard form, since this component ties in a multi-page/multi-form process.

Is there a way I can load in these specific fields, inherited from user_profile_form, into a new form and have those changes save within that form, or is there an entirely separate approach to use here?

If you want to pass variables to a form you can. See this similar post.

Just add $vars as second argument.

drupal_get_form('new_form', $vars);

and...

function new_form($form, &$form_state, $vars) {

If you are trying to pass the user object to user_profile_form you can do it like so:

global $user;
$form_state = array();
$form_id = 'user_profile_form';
$args = array($user);
$form_state['build_info']['args'] = $args;
form_load_include($form_state, 'inc', 'user', 'user.pages');
print render(drupal_build_form($form_id, $form_state));

If you really want to load the user_profile_form inside another form (?) as suggested in your comment, you can do the snippet above but not render the form, just load it into an a variable and extract vars from it.

$loaded_profile_form_with_user = drupal_build_form($form_id, $form_state);


Watchdog database size I was checking out one of my Drupal sites and noticed that the watchdog table is > 3GB. I have plenty of space but it seems a big. Are there any best practices in regards to maintaining this table? I have run and cleared the cache.

Make sure that cron is running, that should clean that out the watchdog table regularly.

http://api.drupal.org/api/drupal/modules--dblog--dblog.module/function/dblog_cron/6

Drupal has a setting that controls how many rows should be kept, which you can configure at:

Drupal 6: /admin/settings/logging/dblog

Drupal 7: /admin/config/development/logging

Additionally, you should check what kind of logs you have in that table. Maybe a module or something is causing a lot of notices which are all logged there (And considerable slow down your site!)

You can of course simply truncate the table, but you should first figure out why it's not getting cleaned and what is filling it up like that. How many rows are there?


Are updates applied across multiple sites? When running updates for core and modules in a multisite configuration where modules are shared (sites/all/modules), are database updates applied across the multiple site's databases or do you need to run updatedb for each?

You need to run updatedb on each site individually.  Note that as soon as you update the shared code, any site that has not had updatedb run could show errors or otherwise fail to function.  You should therefore take all of the sites offline prior to updating the code, and bring each site back online again after updatedb completes.


How to guide user through multiple unrelated forms I have a content type with a term reference field. I want to give user a convenient way of grouping multiple nodes of that type together. I see it like this:

The user creates a first node
When he goes to a node page, he sees a link "subjoin another document"
After pressing it the taxonomy term creation form is shown, user fills required fields
After saving the term he gets redirected to node creation form
Second node is created, taxonomy term fields of both nodes point to newly created taxonomy term

What puzzles me is how it's best to implement such a multiphase logic in Drupal, when we need to guide the user through several unrelated forms.

I'm not sure, but you might find References and Relation module useful for this.


Displaying Webforms on Content Types in Page Manager/Panels The Webform module allows for a webform to be attached to each Content Type of the site.  I can "Enable webform functionality" on my Page and Blog Content types and don't need to use a separate "webform" content type, very cool!  This works great with Entity View Mode displays.

However, when using the Node Template in Page Manager, I can't get the Webform to render after adding the "Node being viewed" Webform element.

My goal is to use Page Manager to display every node, with the possibility of a unique webform attached to that node.

I brought this up at a meetup recently and was advised that it may be a bug.  But I didn't think to ask where!  So, if you think I should bring this up in an issue queue, where do you think that would be, Webform, ctools, or Panels?

Thanks,
Jim


Adding a submit button in a themed table doesn't work When I add a button inside the '#rows' key of a table element, the submit function is not called.
class MyForm extends FormBase
{

   public function buildForm(array $form, FormStateInterface $form_state)
    {
        $my_button = [
            '#type' => 'submit',
            '#value' => $this->t("Click"),
            '#submit' => [
                '::custom_submitForm'
            ]
        ];
        $form['my_table'] = [
           // '#tree' => TRUE,
            '#theme' => 'table',
            '#header' => [
                'Column 1','Column 2'
            ],
            '#rows' => [
                [$this->t("Blabla"), ['data'=>$my_button]]
            ],
        ];
        return $form;
    }
    // other stuff

What is the best workaround for this?
EDIT TO ADD:
As a first try to understand what is going out, I have allowed the children function to consider '#rows' as children (see   Drupal\Core\Render\Element::children)
  public static function children(array &$elements, $sort = FALSE) {
     ...
    foreach ($elements as $key => $value) {
      if (is_int($key) || $key === '' || ($key[0] !== '#' || $key=='#rows')) {
     ...

This is solving the issue (the handler is called), but of course, this change generate many other problems.. But now, we can understand why the submit handler was not called.
I have added an issue in the drupal queue: https://www.drupal.org/project/drupal/issues/3166899
I am not asking to correct this bug, but what would be the best workaround.

Use instead of #theme a form element #type:
'#type' => 'table'

The table form element has an extra step for processing when used in a form.
You don't need '#rows'. Any array key not starting with #, also the index added automatically by appending a row with [], is considered to be a renderable child and displayed as row.


How do I verify emails on a contact form? I want to implement a functionality where anonymous users can contact node authors. I have created a contact form with email field for each node. I would like to send an email verification link to the email address for email ownership confirmation. The form submit should be complete only when that happens.
What would be the best approach to handle this? There is a module in drupal 7 which could work but I didn't come across anything for D8. Will appreciate any help with this.

For validating an email just use client side validation in that case. mdn form validation
This will use the browsers checks for valid email and not send the form to you unless it’s valid.
For verifying an email I would say use Drupal accounts (that already has a superior methode for email verification.)
Btw. you can not check if email is valid at all.
The protocols involved do not allow a check like that.
What you can do is try and send a message and hope it arrives at the other end.
This would be a (as suggested) double take. But whether you are allowed to do so is another matter (it could be considered spam by local law). Safest bet is to either require an account or to to not validate it at all. (Possibly with a block list). And remember, do not make the cure worse that the disease. A mail validation could do that (quite a few sales people found that out)


What should I use in Drupal 8 instead of votingapi_set_vote()? VotingAPI docs are out of date. votingapi_set_vote() has been removed in Drupal 8.

What should I use in its place to programmatically set votes (for instance in a migration)?

Do you know how to set votes programmatically?

use Drupal\votingapi\Entity\Vote;

$vote = Vote::create(['type' => 'vote']); // this comes from /admin/structure/vote-types
$vote->setVotedEntityType('node'); // entity type
$vote->setVotedEntityId($nid); // node id
$vote->setValueType('points'); // this comes from /admin/structure/vote-types
$vote->setValue(1); // the number of points given per vote
$vote->setOwnerId($uid); // the user id of the person who casted the vote
$vote->setCreatedTime($timestamp) // timestamp of when vote was casted (optional)
// it will use the current time if you don't include it
$vote->save();

The above code will create 1 casted vote. Therefore, you will have to run this code for every single vote.


Creating a node with multiple joined fields I'm sure I used to know how to do this, but now I can't work it out.

I have a content type, lets say it's called "project". A project can have multiple contributors, and for each contributor I need to have two fields, let's say "Name" and "University". Can I set this up as a single Content type?

If not (and I have to have a Content type for the project and a Content type for the contributor, using entity reference to link them), then how do I set it up so it's easy to edit on a single page (i.e. create a new project, click something to add another contributor on the same page)

I'd recommend keeping the contributors separate with their own fields. In order to edit them on the one form you can use a number of different modules. We use Inline Entity form.
https://www.drupal.org/project/inline_entity_form


After node creation how do i add simple buttons to edit the field values ``I'm new to drupal,I'm trying a create a content type with some field values which the user can use to create the content for the content type.In the node_view i have added some markup html to create additional generated fields to the content type.Now i want to add few buttons for the user to change the values in my content.

I created a form in node_view hook with a submit button so when user clicks the button i get to modify the node's properties,but i dont understand how to pass the node_id to callback form handler.

Or In general what's the standard process to let users create content for content type with server generating the additional info for the content.

function mymod_node_view($node, $view_mode, $langcode) {
if ($node->type == 'app')

$node->content['apikey'] = array(
        '#markup' => "Client Key
 ".$key['client_key'] ."
 Client Secret
".$key['client_secret']."
 Node id". $node->nid.",",
        '#weight' => 10
    );

    $form = drupal_get_form('redirect_button_form');
    $node->content['redirect_button'] = $form;

function redirect_button_form($form, &$form_submit) {
    $form['submit'] = array(
        '#type' => 'button',
        '#value' => t('Reset Key'),
       // '#callback' => 'my_special_btn_function',
    );

  $form['nid'] = array(
    '#value' => arg(1),
    '#type' => 'hidden'
);
}

function redirect_button_form_submit($form, &$form_state) {

$nid=$form_state['input']['nid'];

drupal_set_message('The form has been created nodeid,'. $node->nid .',key reset');

The $node_id is blank as there is no value passed for it. In order to get node_id in the submit handler function, you should pass the node_id in the form. So pass the node id value as a hidden field in the form and get the value of hidden form element through $form_state of redirect_button_form_submit. In that way you can do it.
Example :
$form['node_id'] = array('#type' => 'hidden', '#value' => $nid);
Yes it is possible for you to edit $node->content['apikey'] if and only if it is saved in database. Create a new field as apikey in the content type and store it.
Hope it helps. Thanks.


Add float or align selector for CCK image fields I'd like to add a float/align drop-down selector for each CCK image field in my content items. Then, that image would float/align itself on either side of the content (left or right), depending on whether "left" or "right" was selected from the drop-down. Ideally, this drop-down would be in the same general area as the ALT and Title fields are in the admin view of the content item.

Does anyone know if this is possible without custom programming?

Look into the Display Suite Module: http://drupal.org/project/ds

It is designed to give you more control of the display of your content from the Admin UI. There are links to detailed screencasts on the project page. You'll see versions for both D6 and D7.

I don't know if you get those options on the 'add new content' page, but it wouldn't surprise me if you did.


Node limit for published nodes per user I am interested in limiting the nodes a user can publish.So Node limit module cannot help on this.
Someone suggested using userpoints and rules to achieve this.
How is this possible with these 2 modules?
Any help would be appreciated.
thanks!

Give a try to User Points Contributed module: This module includes the module called userpoints_nodelimit which enables a limit on node creation based on user points.

However if you want to do it with the userpoints and rules module than the idea would be to create the rule to grant certain point on publishing the new nodes, and than create another rule whose event would be the node creation and in the condition  check if the user already has reached limit than prevent node creation and display the custom message.

Alternatively one easy way to achieve the same is using the hook_node_validate(), one example of using the same is as below:

/**
 * Implements hook_node_validate().
 */
function MyModule_node_validate($node, $form, &$form_state) {
  // For now assign the static value to MAX_NODES (No. of nodes),
  // however you can make it dynamic, and get those values using variable_get().
  $max_nodes = 'MAX_NODES';
  $node_count = 0;

  // Get the user uid from the global user variable.
  global $user;
  $user_id = $user->uid;

  if ((isset($node->uid))) {
    // Use entity query to get the number of nodes already published by this user.
    $query = new EntityFieldQuery;
    $node_count = $query->entityCondition('entity_type', 'node')
      ->propertyCondition('uid', $user_id)
      ->propertyCondition('status', 1)
      ->count()
      ->execute();

    // Check if the node count exceeds the max_node value.
    if ($node_count > $max_nodes) {
      form_set_error('FIELD_NAME', t('Reached the maximum limit of creation of nodes.'));
    }
  }
}


How to change the query value using hook_views_query_alter? I am having a problem trying to change the query output on my view.

I am using this code:

function zed_views_query_alter(&$view, &$query){
  if ($view->name == 'questions_home' && $view->current_display == 'rates_related') {
    $or = db_or();
    dpr($query->where[1]['conditions'][2]['field']->condition());
  }
}

I am trying to alter the word %california%. The output is the following one.

DatabaseCondition Object
(
    [conditions:protected] => Array
        (
            [#conjunction] => OR
            [0] => Array
                (
                    [field] => node.title
                    [value] => %california%
                    [operator] => LIKE
                )

            [1] => Array
                (
                    [field] =>
                    [value] =>
                    [operator] => IS NULL
                )

        )

    [arguments:protected] => Array
        (
        )

    [changed:protected] => 1
    [queryPlaceholderIdentifier:protected] =>
)

How can I go about changing the value %california%?

function zed_views_query_alter(&$view, &$query) {
  if ($view->name == 'questions_home' && $view->current_display == 'rates_related') {
    foreach($query->where[1]['conditions'] as $idx => $condition) {
      if (!is_object($condition['field']) && $condition['field'] == 'node.title') {
        $query->where[1]['conditions'][$idx]['value'] = '%whateveryoulike%';
        // or you can unset this condition and write down a new one
        // unset($query->where[1]['conditions'][$idx]);
        // $query->add_where_expression('1', "$field LIKE %" . db_like("california") . "% OR field LIKE %" . db_like("somethingelse") . "%");
      }
    }
    dpr($query->where[1]['conditions']);
  }
}


How to return JSONP from a menu callback I can create JSON output using a menu hook using the drupal_json_output callback.

Example:

$items['page/%/json'] = array(
  'access callback'   => TRUE,
  'page callback'     => '_modulename_json',
  'delivery callback' => 'drupal_json_output'
);

function _modulename_json() {
  return array(
    'item1' => $field_item1[0]['safe_value'],
    'item2' => $field_item2[0]['safe_value'],
    'item3' => $item3,
    );
}

Output:

{"item1":"Field item1 content","item2":"Field item2 content","item3":"Item3 content"}

But I need to have JSONP, and am struggling to find an elegant solution... I have tried the code from the bottom of the API page, it does the padding, but makes a mess of the content.

$response = array(1,2,3);
$callback = check_plain($_REQUEST['callback']);
// If its a jsonp callback request
if (isset($callback) && $callback != '') {
  $json_response = drupal_json_encode($response);
  echo $callback ."(". $json_response .");";
}
else {
  drupal_json_output($response);
}

Output this way:

callbackName({\u0022item1\u0022:\u0022Field item1 content\u0022,\u0022item2\u0022:\u0022Field item2 content\u0022,\u0022item3\u0022:\u0022Item3 content\u0022});"

The array was being double encoded. First by the $json_response = drupal_json_encode($response); and then again by the menu delivery callback 'delivery callback' => 'drupal_json_output'.

To fix this, remove the delivery callback, and use just 'type' => MENU_CALLBACK,.

In the function change this:

if (isset($callback) && $callback != '') {
  $json_response = drupal_json_encode($response);
  echo $callback ."(". $json_response .");";
}

to this:

if (isset($callback) && $callback != '') {
  $json_response = drupal_json_encode($response);
  drupal_add_http_header('Content-Type', 'application/javascript');
  echo $callback . "(" . $json_response . ");";
  drupal_exit();
}


How to save configs in BrowserTestBase? In a functional test I try to test a functionality after changing the module configuration:

public function setUp() {
  parent::setUp();
  ...
  $config = \Drupal::configFactory()->getEditable('move_file.settings');
  $config->set('vocabulary', 'tags');
  $config->save();
  ...
}

The tested functionality is located primarily in MoveFileService.php. But the service does not see the configs. When I debug the configs directly in the service, then I get:

public function __construct(ConfigFactory $config_factory, LoggerChannelFactoryInterface $logger_factory) {
    $this->config = $config_factory->get('move_file.settings');
    $this->logger = $logger_factory->get('move_file');
}

public static function create(ContainerInterface $container) {
    return new static(
    $container->get('config.factory'),
    $container->get('logger.factory')
    );
}

public function configsAreSet() {
    ...
    fwrite(STDOUT, "Settings: {$this->config->get('vocabulary')}\n");
    // Returns: Settings:
    // The configuration is null.

    $config = \Drupal::service('config.factory')->getEditable('move_file.settings');
    fwrite(STDOUT, "Settings: {$config->get('vocabulary')}\n");
    // Returns: Settings: tags
    // This returns the expected value. But the good practice is to use the dependency injection.
    ...
}

How can I save the config in the setUp() method of the functional test, so that the service can get the saved configuration, when the test is running?

I have found, that the problem was caused, that in the setUp() method of the test class, was at first used the $this->drupalCreateNode([...]) method and then were created the settings. After moving the $config->set(...) method at the beginning of the setUp() method, works everything perfect.

See:

The test class
Test results


Can't access value of dropdown modified by Ajax I have two dropdown fields, #2 is modified by Ajax based on #1 selection. When I try to access #2 value in the submit handler, I get an empty result. I've checked this against the docs and examples and I can't see what am I doing wrong here?

The code:

function admin_select_meeting_type_form($form, &$form_state) {
  $meet_types = get_meeting_types();
  $form['meet_types']=array(
    '#type' => 'select',
    '#title' => t('Select meeting type:'),
        '#options' => $meet_types,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => 'ajax_select_meeting_type_callback',
      'wrapper' => 'meetlist-div',
      'effect' => 'slide',
    ),
  );
  $form['meet'] = array(
    '#type' => 'container',
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save')
  );
  return $form;
}

function admin_select_meeting_type_form_submit($form, &$form_state) {
    drupal_set_message('You selected:' . $form_state['values']['meet']);
}

// Implement ajax update of meeting select field
function ajax_select_meeting_type_callback($form, $form_state) {
     if ($form['meet_types']['#value']) {
        $dispmeet = array(); // truncated for brevity, my array processing is done here
        $form['meet'] = array(
           '#type' => 'select',
           '#prefix' => '
',
           '#suffix' => '
',
           '#title' => t('Select meeting:'),
           '#values' => array_keys($dispmeet),
           '#options' => $dispmeet,
           '#required' => TRUE,
        );
        return $form['meet'];
     }
}

You shouldn't build the form element in your callback.  You want something like this:

function admin_select_meeting_type_form($form, &$form_state) {
  $meet_types = drupal_map_assoc(array('conference' => 'conference', 'event' => 'event'));
  $form['meet_types']=array(
    '#type' => 'select',
    '#title' => t('Select meeting type:'),
    '#options' => $meet_types,
    '#required' => TRUE,
    '#ajax' => array(
      'callback' => 'ajax_select_meeting_type_callback',
      'wrapper' => 'meetlist-div',
      'effect' => 'slide',
      'method' => 'replace'
    ),
  );
  $form['meet_container'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );
  if (!empty($form_state['values']['meet_types'])) {
    $form['meet_container']['meet'] = array(
      '#type' => 'select',
      '#title' => t('Select meeting:'),
      '#options' => drupal_map_assoc(array('test', 'test2')),
      '#required' => TRUE,
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save')
  );

  return $form;
}

function admin_select_meeting_type_form_submit($form, &$form_state) {
    print_r($form_state['values']);
    die();
}

// Implement ajax update of meeting select field
function ajax_select_meeting_type_callback($form, &$form_state) {
  if ($form['meet_types']['#value']) {
    return $form['meet_container'];
  }
}


How do I insert site information data into another table? I have developed website using Drupal. I have created an application without using Drupal, using another framework. In my application I also stored site logo,site name etc. I want to update  my site information table when updating
Drupal site information from admin/settings/site-information.

The fields are the following ones:

id: int(12), primary key
site_title: varchar(60)
site_logo: varchar(200)

You can use a hook_form_alter to add a submit function to the form, see http://drupal.org/node/222158 (for D6 but should be the same for D7).

In your new submit function you can do whatever you want...

You can query other database following this doc http://drupal.org/node/18429

  $other_database = array(
      'database' => 'databasename',
      'username' => 'username', // assuming this is necessary
      'password' => 'password', // assuming this is necessary
      'host' => 'localhost', // assumes localhost
      'driver' => 'mysql', // replace with your database driver
  );
  // replace 'YourDatabaseKey' with something that's unique to your module
  Database::addConnectionInfo('YourDatabaseKey', 'default', $other_database);
  db_set_active('YourDatabaseKey');

  // execute queries here

  db_set_active(); // without the paramater means set back to the default for the site
  drupal_set_message(t('The queries have been made.'));


How to check order exist or not in commerce order? I am using Drupal 7.31 and the Commerce Kickstart distribution. I added an order using CSV file in commerce_payment_transaction table.

I want to check the condition below:

if (isset($_POST['submit'])) {
  $handle = fopen($_FILES['filename']['tmp_name'], "r");

  $i = 1;
  $f_status = FALSE;
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
      if($i > 2){

        $o_id = $data[1]; // I am fetch order_id from csv. I wont to check which order_id is coming from csv is present on commerce_order or not?
        $remote_id = $data[2];
        $created = strtotime($data[7]);
        $changed = strtotime($data[11]);
        $amount = $data[8] * 100;

        $db_query = db_select('commerce_payment_transaction','cpt');
        $db_query->fields('cpt');
        $db_query->condition('cpt.order_id',$o_id,'=');
        $db_res = $db_query->execute();
        $row_count = $db_res->rowCount();

        if($row_count == 0){
            $o_load = commerce_order_load($o_id);
        }
    }
  }
}else{
   $output = "Upload new csv by browsing to file and clicking on Upload
\n";
   $output .= "<form enctype='multipart/form-data' method='post'>";
   $output .= "File name to import:
\n";
   $output .= "<input size='50' type='file' name='filename'>
\n";
   $output .= "<input type='submit' name='submit' value='Upload CSV'></form>";
   return $output;
 }
 $i++;
}

How can I do so?

You can check this using commerce_order_load()

if(commerce_order_load($order_id)){
    //Do something
}
else{
   //Do something
}

Hope this will help you


How deal with taxonomy term parameter in multilingue site? I have a custom controller, who take the tid parameter :

/myroute/{tid}

The tid is upcast with the taxonomy Term so in my controller method I have:

public function index(TaxonomyTerm $tid)

In this function I can get the taxonomy entity.

But for call my controller, it's not SEO friendly... i have : /myroute/43 for example.

So I won't pass the term name, because you can have spécial caractere and it's not a good pratice in a multilingue site.

So for me the best way is to work with pathauto, generate the path for the taxonomy term so i can have :

/[term_category]/[term_name]

Now my question is how pass this to my controller.

I need to call my controller like that:

<a href="myroute/{param_taxo}">

So I am not sure how get the tid of the term with friendly url for SEO.

Any experience about that?

You must edit your route to be like this, /myroute/{alias}.

Then you can load the term in your controller like this:

public function index($alias) {
  // Find the term by path alias.
  $path = \Drupal::service('path_alias.manager')->getPathByAlias($alias);
  if (preg_match('/taxonomy\/term\/(\d+)/', $path, $matches)) {
    $term = $this->entityTypeManager->getStorage('taxonomy_term')->load($matches[1]);
  }
  if (isset($term) && $term instanceof TermInterface) {
    $term_id = $term->id();
  }
}

NB: The path_alias.manager service is added in Drupal 8.8.x, if you use an older version you must use the path.alias_manager service instead.


How to modify body of a node I have to add some data to body of my content type, how do I add it in hook_node_save. I tried adding it like shown below but it's not getting saved.

function mymodule_node_save($node) {
$node->body = 'test string';
}

Also when I do dsm($node) in the above function, the $node->body doesn't contain the string I added.

There's no such hook as hook_node_save(), you're probably looking for hook_node_presave()

  Act on a node being inserted or updated.

Also, the nody body is a field so you have to treat it as such when assigning values:

function mymodule_node_presave($node) {
  $node->body[LANGUAGE_NONE][0]['value'] = 'test string';
}


How to change Solution Name display on authorize.net under Transaction Source useing Drupal commerce I am using Drupal commerce Authorize.Net module for transaction.

When I review Transaction Detail on https://sandbox.authorize.net/ site, it display Solution Name:    Commerce Guys under Transaction Source.

How can I change it with my custom one?

It's unfortunate that Authorize.Net identifies it as "Commerce Guys". It should be identifying the request as coming from "Drupal Commerce", which allows them to monitor adoption by users of the module overall (and justifies their continued investment in our community). I'll follow-up with them immediately to change this so it's actually identifying the solution and not the creator of the solution instead (i.e. Commerce Guys). Changing what appears there is only possible from their end, but I have a contact who should be able to get it done.