Overriding Pathologic when it comes to img src I have Pathologic installed and it is working great from normal links in a document, but for anything that points to the file system ( img src for example) I can't get it to not use ?q= in the url.

You could alternatively use the scanner module or export the DB and use a text editor to replace the domains. Therefore getting rid of pathologic.


View or module that shows which nodes are linking to the current node? Has anyone found a way to show which pages (nodes) have internal links to another page (node)? This could be a view that shows a listing for each node of a particular content type and then all the nodes that have a link to it, or perhaps a block that shows on each page (when logged in) which shows all the other nodes that link to the currently viewed node.

This would be most valuable if it not only showed links found in a "body" field or even the actual node content type fields, but rather the entire page display including blocks, etc.

For SEO reasons its nice to know what pages you have linking to each other (as well as link text would be helpful). (Its good to know other external pages linking to your website, but that's not what I'm referring to in this question - only internal links.)

Curious if anyone else ever came up with a way to do something like this.

Thanks!

Drupal is far too complex to do this in regards of all the modules there are.

You could use a module like this:
https://www.drupal.org/project/intlinks

Still not all texts that are available on you page can be applied to this.

Only thing you could use is a rather weird and costly JS thing. I mean Google Analytics tracks any link on your site. So this already happens. But is this a wise idea for your internal linking? imho not.

For reliable links between Drupal Entities please rely on a node or entity reference field. By this you have links you can query and evaluate.


Rule to create a new view when a node is created I have an event registration site that uses the Entity Registration module for its registration forms. There is also an admin section that uses the Views Data Export module to export all of the registration details.
The trouble is there is no views field (like there is with Webform) that says get all fields from this registration.
As the site hosts multiple events throughout the year, it means that I have to create a new view for each event.

Is there a way to use rules to create a new view or (preferably) view display when saving a node of the Event type.

I think a better solution would be to use a single view with a contextual filter here.
I don't have experience with the Entity Registration module but since it's entity based it should have an Registration id contextual parameter which you can give a default from the url.


Is there a module to modify messages? I am looking out to change the message displayed after user registration submits the user details. Is there a module to achieve it, or do we need to hard code the message to display?

Sounds like you're looking for String Overrides.  It will work with any string that is handled in the proper manner (ie, it is run through t()), not just messages.


Using Drupal Commerce as a Quote Form I have a client who needs to allow customers to put products in a cart so that they can be custom quoted, instead of purchased online. Is Drupal Commerce aptly suited for this? If so, what are some strategies to hide pricing throughout the process?

Actually, Drupal Commerce fits this need perfectly as you can pretty much disable the entire notion of payments etc. no problem and the rest of the system won't mind at all.

The default "add to cart form" you use for adding stuff to your cart doesn't even display price.

Also, making a view out of the current user's shopping cart order (shopping cart contents are for Drupal Commerce "orders", just incomplete ones) to make a custom display of what the user has compiled and to make a rule for checkout that just sends the "order" to you(r) client.

I'd be happy to answer any more detailed questions you might run into, but in general, the answer is "yes" as the architecture of Drupal Commerce is very flexible and as it's fully entity-based, it integrates seamlessly with all other aspects of your Drupal site.


avoid fatal guzzle exception error how can i avoid fatal error due to ?

 |GuzzleHttp\Exception\ConnectException: cURL error 6: Could not resolve host|

My code here do not catch it

try {
      $client = new Client();
      $response = $client->request('GET', $url);
      $content = json_decode($response->getBody(), true);
    }
    catch (Exception $e) {
      \Drupal::logger('amu_hal')->error('this url aint good'.$url);
    }

This is an example on how to catch this error:

try {
     $client = new Client();
     $response = $client->request('GET', $url);
     $content = json_decode($response->getBody(), true);
} catch (\GuzzleHttp\Exception\ConnectException $e) {
     var_dump($e);exit();
}


Drupal 8 custom block with html and javascript In Drupal 8 what is the process for creating blocks with html and javascript?

Here is my sample code for creating the block

class TopNewsBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
     //Fetch data
     return array(
      'type' => 'markup',
      '#markup' => '

',
      '#attached' => array(
        'library' =>  array(
          'custom_cms_blocks/dataTables.dataTablesjs',
          'custom_cms_blocks/top-news-library'
        ),
      ),
     );
  }

}

It works but the problem I have is - I want to seperate out the html code from the php code. Is it possible to include a html file within the block just like the way a javascript file is attached as a library?

You need to use hook_theme() in your module, and declare a new Twig template that you want to use for your block.

Here's an example that needs to go to YOUR_MODULE.module file:

function YOUR_MODULE_theme() {
  return [
    'YOUR_TEMPLATE_KEY' => [
      // Here you can pass any variables you want, if necessary.
      'variables' => ['var1' => NULL],
    ],
  ];
}

Then create a folder called /templates in your custom module, and YOUR_TEMPLATE_KEY.html.twig file where you can have any markup you want. See below how to use the variables you pass to the template:

<div id="your-block">
  {{ var1 }}
</div>

Finally, to use it:

public function build() {
  return [
    '#theme' => 'YOUR_TEMPLATE_KEY',
    '#var1' => 'Variable one passed here',
  ];
}

Hope this helps.


is it possible to hack a module by mymodule? A few times i had (sadly and not proper) to hack a module, like changing some functions or default images, is it possible to hack a module in a proper way by "mymodule", in order to override simple things like changeing the returns of htlm or css with something like

mymodulefunction_moduleoriginalfunction(%args)

and make sure "mymodule" overrides my code running after original module?

No, it's not possible in the manner you are describing. However, Drupal provides many _alter() hooks that allow various things to be altered as necessary, so that you don't have to hack anything.

However, without specifics on what you want to do, I cannot suggest any specific methods.


How to get all values from a new node being created in hook_ENTITY_TYPE_presave() Drupal 8.7.2

function mymodule_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  data_dump($entity->original); //is empty because its a new node, not a node being updated.
  // How to get all values at one time?
  // By values I mean the same value you would get from:
  data_dump($entity->get('title')->value);
  // but from all fields and not just one field at a time.
}

I have a custom content type that has 30 custom fields that I need to examine inside this hook.  I'd like to avoid getting the value of each field individually.

Thank you for your time.

There are probably a few different ways to get that info, but if the returned format suits your needs then EntityInterface::toArray(), which Gets an array of all property values, is probably the most succinct:

$field_data = $entity->toArray();


Shell problem with remote hosts I'm having a problem when executing a drush command on a group of aliases that are all remote.

When I do this:

drush -y @group.host1 status -v

all works fine.

When I do that:

drush -y @group status -v

it fails with the following message for each host in that group:

ssh -o PasswordAuthentication=no host1 'DRUSH_PHP=/usr/bin/php drush  --backend=2 --verbose --yes --uri=www.example.com --root=/var/www --reserve-margin=28  status 2>&1' 2>&1
fish: Unknown command 'DRUSH_PHP=/usr/bin/php'. Did you mean to ru
n drush with a modified environment? Tr
y 'env DRUSH_PHP=/usr/bin/php drush…'. See the help section on the set command by typing 'help set'.
Standard input: DRUSH_PHP=/usr/bin/php drush  --backend=2 --verbose --yes --uri=www.example.com --root=/var/www --reserve-margin=28  status 2>&1

So, how I read the error it looks like fish (which is the shell used instead of bash) is having an issue with the command

ssh -o PasswordAuthentication=no host1 'DRUSH_PHP=/usr/bin/php drush  --backend=2 --verbose --yes --uri=www.example.com --root=/var/www --reserve-margin=28  status 2>&1' 2>&1

Now what's the difference when I call the same thing for @group.host1 instead of @group? Then the command looks like this:

ssh -o PasswordAuthentication=no host1 'drush  --backend=2 --verbose --yes --uri=www.example.com --root=/var/www --reserve-margin=28  status 2>&1' 2>&1

The difference is that the leading "DRUSH_PHP=/usr/bin/php" is missing and then it works fine.

I have played around with /usr/bin/drush and removed the option --php="$php" from the last line in that file, and then everything works fine again too.

Important: This only happens since I've upgraded to Drush version 6.2 - before I had 6.0 on my local laptop and 5.9 on the host1.

Drush was designed for use with bash, not fish.  Would it be an option to make your login shell bash for your remote Drush user?

Your other option would be to submit a patch to Drush to fix this problem.  There are two possibilities:

Modify Drush to use env DRUSH_PHP=... in backend invoke.
Modify Drush to not pass --php when --remote-host is set.

Option (1) may be harmful to remote sites where env is not in the PATH, so it may be a dubious proposition.  It might be okay, though; env is probably in the PATH on most systems.

Option (2) seems better.  There is little reason to think that the path to php will be the same on a remote system as it is on the local system, so Drush probably shouldn't be assuming that the php option is relevant for remote aliases, unless it was set in the alias' %path section.

Either of these actions would require a discussion in the Drush issue queue.


How to add a complete menu as an item in other menus? Let say I have 3 MENUS:

MENU 1 with these items:

item menu 1 - a
item menu 1 - b
item menu 1 - c

MENU 2 with these items:

item menu 2 - a
item menu 2 - b
item menu 2 - c

MENU 3 with these items:

item menu 3 - a
item menu 3 - b
item menu 3 - c

I need to add MENU 1 as a clild in MENU 2 and MENU 3 to get this:

MENU 2 with these items:

item menu 2 - a
item menu 2 - b
--item menu 1 - a
--item menu 1 - b
--item menu 1 - c
item menu 2 - c

MENU 3 with these items:

item menu 3 - a
item menu 3 - b
--item menu 1 - a
--item menu 1 - b
--item menu 1 - c
item menu 3 - c

Is there any way to get this?

There is a sandbox project for combining menus: https://www.drupal.org/sandbox/klickreflex/1989788

Someone with a similar issue found code that was of value.

The poster also suggests Advanced Menu which has some merging capabilities.


CSS/JS aggregation, huge number of files I use css and js aggregation for increase the speed of a drupal 7 website.
Now, when I log in with an user A, four news files (one css and one js) are added in the files website directory. (for each website page)
Then, when I log in with an user B, four news files (one css and one js) are added in the files website directory.
...etc

I'm afraid because the website will have many thousand of users.
So, there will be huge number of css/js files.

When theses files are deleted ? Can I configure that ?

As noted in the post you found:

  They will be deleted automatically 30 days (or whatever your
  drupal_stale_file_threshold variable is set to) after they were
  created via drupal_clear_css_cache() and drupal_clear_js_cache().

If you are going to have many thousands of users worrying about file system performance at this stage is likely getting ahead of yourself. Depending on your hosting setup you are more likely to run into other kinds of performance issues (PHP, database, fewer non-file caches, etc) before the file system becomes the bottleneck. You may indeed need to solve that problem eventually but it is unlikely to be the first challenge you need to overcome.


Add id to image inside views I have created a grid in views in which there are stored webshops (it's for a website on which you can find all kind of webshops). It shows a picture, a title and a bodytext for each webshop. And now I would like to edit the images only for that page in a seperate id.
Only I have no idea how i should add an id for the css of the image, how is this possible in drupal, css or php?

If you add the "NID" field to your view's fields, (as the first entry, for reasons I won't get in to here),  you can then use the "rewrite output" function to attach a unique CSS ID using the NID to your image.


File directory token - image field - node author How to setup file directory where the images are saved to use tokens based on node author ?
I have all setup with current user, but this is not good if moderator or admin needs to make a change with content made by user.

Strange is that for automatic node title i can use node author tokens, but not for image field.

Have a look at this issue that explains why you cannot use node tokens in Views: https://www.drupal.org/node/1788414

  This is a limitation of Drupal core - it does not provide any node
  context for token replacement aside from the global tokens that are
  available. You will need a module like
  http://drupal.org/project/filefield_paths in order to use node tokens
  in the file upload directory tokens.

The File (Field) Paths module provides this functionality:

  The File (Field) Paths module extends the default functionality of
  Drupal's core File module, Image module and many other File upload
  modules, by adding the ability to use entity based tokens in
  destination paths and file names.

  In simple terms, File (Field) Paths allows you to automatically sort
  and rename your uploaded files using token based replacement patterns
  to maintain a nice clean filesystem.

That should allow you to use the node:author token.


Is there an optimal method to grant permissions for a newly added permission defined by hook_permission? I'm attempting to deploy a new permission and granting in a single update.

I have custom.module which defines a new permission with hook_permission:

function custom_booking_permission() {
  return array(
    'custom allow registration' => array(
      'title' => t('Fill out Registration Form'),
      'description' => t('Allows a user to register their online account.'),
    ),
  );
}

And then in the custom.install in hook_update_n:

function custom_booking_update_7002() {
  user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('custom allow registration'));
}

The problem is that when I deploy this code and run drush updb -y in my script, I get this error:

  SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'module' cannot be null                                       [error]

Which as I understand it is because Drupal has yet to recognise the new permission in hook_permission.

I have other aspects to the update script such as enabling modules and reverting features, and then running drush updb later in the script works fine. However I've always believed that drush updb should be as early as possible. Maybe I just need to be more flexible.

Alternatively I was thinking about either an SQL insert to avoid the grant permission validation, or running a drush php-eval later in the deployment script separate from drush updb. Both strike me as undesirable.

The only reason Drupal would not know of the new permission is because it hasn't yet registered your hook. This would only happens after a cache clear.

I would not advise to run a full cache clear before an update (as that might well invoke code that will expect the update to have been run already). Maybe you could get away with clearing the cache of hooks in module_implements. You could call this in your hook_update_N before setting the role:

module_implements('permission', FALSE, TRUE);

But even that feels a bit risky ; it is best not to interfere with the way things run, you might end up with debugging headaches.

Otherwise I don't think there is a perfect solution. Drupal just doesn't have a 'post-update' style hook. You could implement such a hook yourself (maybe using a variable_get/set and hook_init ; or as a drush script as you suggest), however this feels like a complicated way to do what could otherwise be done with a simple SQL query.

If you know your target uses an SQL database, then I think that, while not entirely satisfying, the SQL insert statement is the simplest solution.


Select field descriptive or numeric keys I have created a field of type List (text) with widget Select list.
After editing most of its settings, it came to complete its Allowed values list.
Following the help's text instructions, the values should have this form key|label and here is my question:

Should I use descriptive or numeric keys for the values (and why)?

  The key is the stored value

Does this (keys) selection will have any impact in the future if for example I want to use these values for aggregation (with views or not)?

The key|label format is for scenarios where you want to present a different, user-friendly, label that differs from the underlying, machine-readable, storage. For example, a country select list that you want represent in the 2-character ISO 3166-1 format while showing the official country names to present to the user selecting it.

In the above scenario, regardless of using the key|label format or not, the underlying data will be represented as a string (VARCHAR) since it's a Field (text) field type. If your underlying data needs to be represented as numeric, then you should use the List (Integer) (or other number types) field type as it will be stored as INT within the DB column.


Template files and Machine Names I am trying to create some variables in my template.php file using the form machine names from a content type I created. Then I am creating a node.tpl.php template file that is related to the content type so I can perform the layout I want. I don't think I have the right syntax. Here it is:

$node = $variables['node'];
function keevilcontracting_preprocess_node(&$variables) {

 if($variables['type'] == 'project') {
    kpr($variables);
 $variables['title'] = $node->title;
 $variables['coverPhoto'] = $node->field_cover_photo; // 'field_cover_photo is the machine name of the field in my content type form.
 $variables['projectDesc'] = $node->body;
 $variables['additionalPhotos'] = $node->field_additional_photos;
 }

}

Any suggestions would be great.

Cheers!

You shouldn't have that

$node = $variables['node'];

outside your function.

put it as the first line inside your preprocess function.

$variables doesn't actually exist out there (and if it does it won't be the $variables variable you're expecting in this case).


Detect device using Varnish I have some difficulties finding a correct code (VCL) to configure varnish to detect if the device is a tablet or a mobile or a desktop.

Here is the best module version found today, but still not detecting tablet if not an iPad.

This is very tricky but see this helpful link.

Varnish device detection and redirect to mobile site


Local server doesn't work, directly web on local server go to www I have a local host and website designed by drupal, I downloaded a website to local host but when I want to open local web directly go to www not to local, please can help me?

You probably have a full URL somewhere in your .htaccess file, in the root directory. Search for Rewrite directives.


warning: number_format() expects parameter 1 to be double, string given in I have migrated a site from one host to another and I now get the following warning:

  warning: number_format() expects parameter 1 to be double, string given in /var/www/vhosts/vinylletters.biz/httpdocs/modules/uc_font_attribute/uc_font_attribute.module on line 74.

Line 74 is the following.

$html .= '
'.$fontValue->fontValue.''.str_replace('.ttf','.png',$fontValue->fontValue).''.number_format($fontValue->price,2,'.','').'
';

I am not sure what I need to do to get this line working.

The number_format() function requires a float type variable for its first parameter.

Try casting the parameter like this:

$html .= '
'.$fontValue->fontValue.''.str_replace('.ttf','.png',$fontValue->fontValue).''.number_format((float)($fontValue->price),2,'.','').'
';


Drupal 8 Equivalent of Drupal 7's disabling a module without Uninstalling it I noticed that I can't just "disable" a module in Drupal 8. As disabling it deletes all the config data of that module and completely uninstalls it. There are times I just want to disable a module to see if that is causing issues, but I have no way to keep its config data intact like how D7 can just disable, but not uninstall.

How would one do something like this in D8?

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

The long and the short of it is that you cant. This option is no longer available in Drupal and it was a conscious decision to remove the ability to disable a module because:

  Because upgrades of some contrib module don't actually work (and can't be made to work) if upgrading when they are disabled.
  Because data left behind by a disabled module that is later re-enabled causes integrity issues and cruft.
  Some upgrades left behind data loss due to things like unexpected dependencies, plugins or hooks being unavailable at key times - when
  things were disabled. .. that issue (https://drupal.org/node/1199946) is several hundred arguments long,
  so It's unfair to over-summarize.


How to make hidden field not required? $form['questionfield_form_fieldset'][$i]['answer_type'] = [
        '#type' => 'radios',
        '#title' => $this->t('Select Answer Type'),
        '#options' => array(
          'select' =>t('Drop Down'),
          'radios' =>t('Radio'),
          'rating' =>t('Rating'),
        ),
        '#description' => $this->t('Select the way answer will disply eg. in radio button or in selectbox(Dropdown)'),
        '#default_value' => $config->get($form_count . '.' . $drupal_form_id . '.' . 'answer_type'),
        '#required' => TRUE,
      ];

      $form['questionfield_form_fieldset'][$i]['answer_box_id'] = [
        '#type' => 'textarea',
        '#title' => $this->t('Answer for above question'),
        '#description' => $this->t('Add your answers for above question here.'),
        '#default_value' => $config->get($form_count . '.' . $drupal_form_id . '.' . 'answer_box_id'),
        '#required' => TRUE,
        '#states' => array(
      'visible' => array(
        array(
        array(":input[name='questionfield_form_fieldset[$i][answer_type]']" => array('value' => 'select')),
        'or',
        array(":input[name='questionfield_form_fieldset[$i][answer_type]']" => array('value' => 'radios')),
      ),
        ),
    ),
      ];

I want to make answer_box_id as not required when user click rating radio button .

You need to remove '#required' => TRUE from the render array.

States only control "soft" changes through javascript. They don't (and can't) have any effect on the backend validation; if they could, it would be trivial for anybody to bypass the server-side validation for a field just by setting some CSS styles on it. That would not be a good situation to get into.


Add image field or other fields from node to a custom Block in Drupal 8 I am new to Drupal and I am learning pretty fast.
However I am stuck on an issue.

I need to make a custom Block for my content (node) images.

There is a system-made content block which pulls from the node form of content type "Basic Page". I've added a "Image upload field" to that so I can upload images within my content.

I am able to render the field on the page after adding the content block to the content region, However, I need to show just that image of that node in some other region.

How can I do this?

Use Views module for this. In D8 the views module is part of the core, in D7 you need to install it

1) Go to Structure > view

2) Add a view which shows content of type Basic page. Check on create a block.

3) Select the fields to be shown as image (as you want)

4) Under Advanced (on the right side of the view, click on it to expand)

CONTEXTUAL FILTERS click add, and select ID (D8) or Nid (D7) and then choose "Provide Default Value" and Under type select "Content ID From URL". click on Apply and save the view.

5) In structure >blocks, place the block in the region you want to on the content type you wish (In your case Basic Page).

6) Go to your basic page content  and you will be able to see the image which belongs to that node only in the view block you have placed.


How do you strip HTML from the node summary that appears on taxonomy node listing pages? I've tried using hook_preprocess_node() inside of a if statement for arg(0) == 'taxonomy', but changes to the node aren't carried through to display.

What is the best way to make the teasers appear in plain text (stripped HTML) when listing in the taxonomy node listing page?

Within node--taxonomy.tpl.php, you could isolate the field data for your teaser or any field, depending on how you have that template set up, and apply the php strip_tags to that field data.

For example:

$teaser = render($content['body'][0]);
$textteaser = strip_tags($teaser);

This video is a great starting point for learning about the theming templates if that is new: Theming Fields and Nodes with Templates

One other idea is to isolate the div that wraps each teaser (if possible) and use jQuery to transform the content using the relevant CSS selector using .text() method.


Content approval by roles workflow So I am looking at creating a website in Drupal (In the past I have used PHP and in the past few years, Symfony), however, I can not work out the workflows when it comes to approval for content.

The way the organisation will work is there will be a large number of people that will need to be able to create and edit content pages, but should not be able to publish them. Then one of the admins will look at the page and fix up any code required and make the page a bit neater, and then publish.

The first thing is, I need to know how to make a role where the user can add (not sure if adding will be required yet) and edit a page, but not publish it.

The second thing is when a page is edited and the checkbox for publishing is not selected, it unpublishes the page! That really should not be the case, it should just stay at the current revision and the saved page should just be a newer revision awaiting publishing.

I am running tests on the opensourcecms servers at the moment (with their 24hr testing system), so can not upload my own modules to the server.

I think for your use can you should use workbench
with workbench_moderation

  Workbench Moderation adds arbitrary moderation states to Drupal core's "unpublished" and "published" node states, and affects the behavior of node revisions when nodes are published. Moderation states are tracked per-revision; rather than moderating nodes, Workbench Moderation moderates revisions.


Different home pages based on different conditions? I have two pages:

/home
/pr

Currently, under site configuration, I have /home as the home page. So whenever someone open mysite1.com, it will show the contents at /home. However, multiple domains are parked on this site. I want it in the case of mysite2.com is opened, the /pr page must show, but if mysite1.com is opened, it must show /home like it always does.

At what point would I be able to do this? Where  can I incorporate this logic?

You could do this in settings.php and define $conf['site_frontpage'] from a server variable like $_SERVER['HTTP_HOST']. The same logic would allow you to set your $base_url(D7) or $settings['trusted_host_patterns'](D8) to the correct domain as well.


How to combine views exposed filter with search? My client asked me for a single field, that would work 2 ways:

Autocomplete filter based on taxonomy.
If site visitor inputs something that's not in taxonomy, full text search should be performed on content's body, and appropriate info message shown.

That way if user enters category name, he will get hand picked nodes listed, and if anything else, he will at least get some content.

Separately, it's easy. But how to combine these behaviours in one field?

Finder module will do your requirement exactly, You can select taxonomy term as well as node title, body, fields, ..etc to perform the search.

  There are many ways to put together finder's functionality to get the
  sort of search form you need. There are also many hooks and theme
  functions allowing full customization of finder's output.

It is used for these purposes:

As a search tool to find a group of nodes or users.
As a way to navigate to a specific node or user page that matches criteria.
As an alternative to exposed filters for a Views module display.

See the below screen shot, In the finder field you can choose taxonomy terms as well as node body to perform the search in auto-complete exposed field, even you can perform multiple keyword search separated by comma. Read the Finder documentation for more information..

Once you added the element you can select the finder fields from the list, hold the

Ctrl key to select the taxonomy term as well as Node: Body


add css class to html element based on taxonomy? I would like to add class to the HTML element based on taxonomy. Is it possible to do it from inside template.tpl.php or do I need to create needed templates manually? If so, how will my theme know which template it should pick? Thank you

You can do this by adding a preprocess function to your template file that detects if the current node has terms associated with it and if so, populates a variable for the page.tpl.php according to your logic, ex:

function YOURTHEME_preprocess_page(&$variables) {
  if (!empty($variables['node'])) {
    $node = $variables['node'];
    if (!empty($node->field_tags)) {

      #your taxonomy logic here, if term matches your case then assign it to variable
      $variables["custom_taxonomy_page_class"];

    }
}

Then, in your page.tpl.php file in your theme, you just need to add the above variable where you want it in the HTML tag.

<html xmlns="http://www.w3.org/1999/xhtml" class="$custom_taxonomy_page_class">

If the variable is empty, no class will be output.


How can I make form_alter work with Ajax Comments? I did some manipulation (with JavaScript and CSS) on my comment form. It works good. Then I needed to install the Ajax Comments module because I don't want visitors to go another page while replying a comment.

My customization on the comment form doesn't work after enabling the Ajax Comments module.

This is the custom code that works without Ajax Comments:

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

      if($form_id == 'comment_node_blog_form') {
        $form['comment_body']['#weight'] = -100;
        $form['#attached']['js'][] = drupal_get_path('theme', 'mytheme') . '/js/jquery.validationEngine-en.js';
        $form['#attached']['js'][] = drupal_get_path('theme', 'mytheme') . '/js/jquery.validationEngine.js';
        $form['#attached']['js'][] = drupal_get_path('theme', 'mytheme') . '/js/scripts.js';
      }
    }

And this is the JavaScript code:

(function ($) {
    $(document).ready(function(){
        $("#comment-form").validationEngine();
        $('#comment-form').find('.form-type-textfield').hide();
        $('#edit-comment-body').click(function() {
                $('#comment-form').find('.form-type-textfield').slideDown();
        });
    });
})(jQuery);

I tried the code above with behavior format but it also didn't work.

How can I make this code work with Ajax Comments?

AJAX Comments replaces the core comment form with its own version, so #comment-form is the wrong selector. It'll be something more like #ajax-comments-reply-form-751661-0-0. The numbers break down as [node-id]-[parent-comment-id]-[ajax-iterator]. The parent comment ID comes into play when you're replying to an existing comment.

Because the module uses the core AJAX API, that ID will also change for the new form that appears after a new comment is posted, so using an ID for your jQuery selector isn't a good option.

Without knowing exactly how your markup looks some of this is guess work, but the code to grab a reference to the comment form will look something like this:

var $commentForm = $('#main-body-selector').find('.ajax-comments-form-add');

EDIT:
The Ajax Comments module adds an ajax-comments-form-reply class to all reply forms and adds an ajax-comments-form-add class to all comment add forms.

So, instead of #comment-form you should use ajax-comments-form-add and/or ajax-comments-form-reply to effect the comment form.

(function ($) {
Drupal.behaviors.comment = {
  attach: function (context, settings) {
        $(".ajax-comments-form-reply").validationEngine();
        $('.ajax-comments-form-reply').find('.form-type-textfield').hide();
        $('.text-full').click(function() {
                $('.ajax-comments-form-reply').find('.form-type-textfield').slideDown();
        });

        $(".ajax-comments-form-add").validationEngine();
        $('.ajax-comments-form-add').find('.form-type-textfield').hide();
        $('.text-full').click(function() {
                $('.ajax-comments-form-add').find('.form-type-textfield').slideDown();
        });

  }
};
}(jQuery));


How to check whether \Drupal\Core\Archiver\Zip::extract() succeeded? I called \Drupal\Core\Archiver\Zip::extract() to extract files from an archive. How can I tell whether extraction was successful?

The Drupal Zip class is just a wrapper around the PHP ZipArchive class.

As @tenken already mentioned the wrapper just returns itself:

  /**
   * {@inheritdoc}
   */
  public function extract($path, array $files = []) {
    if ($files) {
      $this->zip->extractTo($path, $files);
    }
    else {
      $this->zip->extractTo($path);
    }

    return $this;
  }

I guess that your best option is to retrieve the ZipArchive object itself via the getArchive() method of the Zip class. On the ZipArchive class call the extractTo() method and check its output (TRUE or FALSE).

I am currently working on a rewrite of the archiver classes to use PharData: https://www.drupal.org/node/2891871. The PharData class throws exceptions on failure. If this issue is done and the patch lands you are able to catch exceptions to check if the archive operations were successful.


Custom widget making field invisible I'm trying to create a custom module for Drupal 7 that makes two widgets available for Text fields. The widgets are showing up in the list of available widgets, but when I select one of them as the widget for a Text field, the field isn't visible on the form (although it is still listed in the Manage Fields section and its settings can be changed as normal). Here's my code so far:

<?php
/**
 * Implements hook_menu().
 */
function autocomplete_jsb_users_menu() {
    $items['jsbu/speaker/autocomplete'] = array(
        'page callback' => 'jsbu_speaker_autocomplete',
        'access callback' => TRUE,
        'weight' => 1,
    );
    $items['jsbu/venue/autocomplete'] = array(
        'page callback' => 'jsbu_venue_autocomplete',
        'access callback' => TRUE,
        'weight' => 2,
    );
    return $items;
}

/**
 * Implements hook_field_widget_info().
 *
 * Two widgets are provided.
 * - A textfield Speaker name autocomplete widget.
 * - A textfield Venue name autocomplete widget.
 */
function autocomplete_jsb_users_field_widget_info() {
    return array(
        'autocomplete_speaker_name' => array(
            'label' => t('Autocomplete Speaker Name'),
            'field types' => array('text'),
        ),
        'autocomplete_venue_name' => array(
            'label' => t('Autocomplete Venue Name'),
            'field types' => array('text'),
        ),
    );
}

/**
 * Implements hook_field_widget_form().
 */
function autocomplete_jsb_users_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
    //load the default text instance
    $element += text_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);

    /*if ($instance['widget']['type'] == 'autocomplete_speaker_name') {
        $element['value']['#autocomplete_path' ] = 'jsbu/speaker/autocomplete';
    } else if($instance['widget']['type'] == 'autocomplete_venue_name') {
        $element['value']['#autocomplete_path' ] = 'jsbu/venue/autocomplete';
    }*/
    return $element;
}

/**
 * Implements the autocomplete_jsbu_speaker() callback.
 */
function jsbu_speaker_autocomplete() {
    $matches = array();

    // Query the database
    $query = db_select('field_data_field_speaker_name', 'sn');

    // Select rows that match the string
    $query
        ->fields('sn', array('field_speaker_name_value'))
        ->orderBy('field_speaker_name_value', 'DESC');

    $result = $query.execute();

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

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

/**
 * Implements the autocomplete_jsbu_venue() callback.
 */
function jsbu_venue_autocomplete() {
    $matches = array();

    // Query the database
    $query = db_select('field_data_field_venue_name', 'vn');

    // Select rows that match the string
    $query
        ->fields('vn', array('field_venue_name_value'))
        ->orderBy('field_venue_name_value', 'DESC');

    $result = $query.execute();

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

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

Any ideas on what I'm doing wrong there/anything else I might need to add? Is the problem that I'm missing a hook?

EDIT: $element just before return:

Array (
    [#entity_type] => node
    [#bundle] => event
    [#field_name] => field_event_speaker
    [#language] => und
    [#field_parents] => Array
        (
        )

    [#columns] => Array
        (
            [0] => value
            [1] => format
        )

    [#title] => Speaker
    [#description] =>
    [#required] =>
    [#delta] => 0
    [value] => Array
        (
            [#autocomplete_path] => jsbu/speaker/autocomplete
        )

)

I think it's because you're missing the type, however, to make things easier and more compatible, why not load the "stock" widget and make modifications?

Try adding this instead of your $element declarations:

$element += text_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);

That should load the default text form, then you can make modifications. You can take a look at the code it uses directly: see line 502 of text.module.

Your simplified code might look something like this:

   //load the default text instance
   $element += text_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);

   if ($instance['widget']['type'] == 'autocomplete_speaker_name') {
      $element['value']['#autocomplete_path' ] = 'jsbu/speaker/autocomplete';
   else if($instance['widget']['type'] == 'autocomplete_venue_name')
      $element['value']['#autocomplete_path' ] = 'jsbu/venue/autocomplete';
    }

   return $element;


Sorting Views by current week The Date module with Views has functionality to filter dates with a granularity by Day, Months, Year, etc. but not for weeks.  So to do this with a Contextual Filter and PHP code to retrieve the current week, I tried this:

This had an output that suggested the current week was the fifth of the year which would be in February as shown here:

Yet the output is correct without any filter as shown here:

With other PHP code to filter the View by days and months, it worked great.  Yet this week filter doesn't seem to know the current week of the year.  How can I either have the Date module filter with a granularity of weeks, or input the correct PHP code to have the list filter by the current week?

I was able to find a solution by using two separate filters.

The first filter will be a relative for the current day.  It should have an operator that is greater than or equal to today.

The second filter will be a relative day as well.  It will have an operator that is less than +7 days.

This will allow you to filter views by the current day plus seven days.


DIsplay Block content after certain time delay I need to show the block content to users after certain delay of page load . Initially the user will see only the article , but after certain time the block content will be revealed . Can it be done ? any pointer is appreciated .

Thanks
Pankaj

Create a block and set it to the region and page you'd like it to appear at
Use CSS to hide the contents of the block
Use JavaScript to override the hiding and display at a specific interval

The CSS would look something like this:

.block-DELTA {
  display: hidden;
}

And then just use JavaScript to display the block after a specified interval.  You could also add some animation to your CSS property to make it fade in.  (That's just one example tutorial on animating, google and you'll find hundreds more)

You can add the CSS and JavaScript to the block in a number of ways.  The quickest and dirtiest is in the block content itself.  I'd strongly recommend storing any code in either a module or theme.  See drupal_add_css() and drupal_add_js() for more information on implementing.


Warning message when patch is applied? I applied a patch and I get a Warinig message.

Then it states that the patch was applied cleanly.

Can I trust this?

This is the complete code:

example@d565:~/www$ git apply -v SA-CORE-2014-005-D7.patch
Checking patch includes/database/database.inc...
warning: includes/database/database.inc has type 100755, expected 100644
Hunk #1 succeeded at 733 (offset -3 lines).
Applied patch includes/database/database.inc cleanly.
example@d565:~/www$

warning: includes/database/database.inc has type 100755, expected 100644

You can trust that the file has been applied successfully, but not that the file was in the expected state to begin with.

755 and 644 refering to numeric notation of unix-system file permissions.

What the warning says is that the patch lists the file as being not executable, but it found the file to be executable.
This had no effect on applying the contents of the patch to the file though.


How to "featurize" customizations to Answers module (or a content type that is part of a module) I'm implementing a discussion feature using the Answers module. I want to create a feature for all the customizations so I can implement and deploy using the git process.

The views and content types that I've customized (answers and questions) are not showing up as options to include in the feature.

Has anyone else worked with this module with git for local, staging/testing and production? How did you push your customizations? Thanks!

Drupal 7.54; Answers 7.x-4.0-rc2

Edit: Answers is a contributed module that comprises of some views and some content types and possible other components.

Edit 2: I've followed the advice in this SE post regarding a similar situation in views, but it doesn't solve my issue with content types or having to basically re-create the module.

For the customized views, I cloned and disabled the original views. Then I was able to pull the view (cloned one) into the feature.

For the content type customizations, I was able to pull in the new fields I created, and customizations to the other fields, by finding the names of the specific customized fields in field bases and strongarm in features.


How do I modify a Drupal Theme? The theme I am using has a slider -- a panel of automatically changing images to display a topic that the user can choose -- but it only shows a few slides.  I want to extend it to a dozen slides.  I did simple text searches to determine which files in the theme are used code files to provide the functionality to the slider.  That was the easy part.  I was able to extend the code from the few slides to 12 slides.

Now comes the more difficult and hidden part.  As I see it, each slide has two parts that are not hard coded.  First, each slide has a caption -- a text description.  Secondly, each slide has a URL associated with it that is where the browser goes if the user clicks on the slide.  These two things are not hard coded in any of the PHP or other files, as far as I can tell.  They can be edited by the admin in the drupal backend admin settings.

So I assumed that these fields are somehow set and retained in the database.  But I did a search on a downloaded copy of the database and I did not find this text.

Please advise.  What additional work do I need to do to complete this task?

I suppose I could just forge ahead.  Obviously this data is being stored somewhere.  Maybe they are stored in the database in an encrypted form for security reasons.  I could do an ftp upload of the site theme files.  But then what?  Do I uninstall the theme and then reinstall it?  Do I just deactivate it and then reactivate it?  How do I make my code changes work?

If I understand your (main) question correctly, you want to show additional images in the slider. In that case you have to narrow down which modules are used to create the slider. Typically a View is used to retrieve all content (stored in your database, normally not encrypted), an overview of all Views can be found at admin/structure/views. In the View there is an option to set the number of items that have to be shown in the Pager section (setting the number of items to show to 12 would in a typical installation be the thing you want to do).

When this is indeed the set up and you don't see the expected change after altering the value, don't forget to clear the caches (drush cr or via admin/config/development/performance).

If your environment is different, please provide additional details: which module is used to create the slider, e.g. Flex Slider, is Views used to provide the data (images provided by the user), etc.


Why semaphore table is not using MEMORY as storage engine? Drupal's table "semaphore" is using MyISAM (Drupal 6). I was wondering why it's not using MEMORY as storage engine?
The only thing that I could think of is that Drupal needs locking/semaphore data after MySQL restart. But the point with semaphore is that it should not have important data...

Am I missing something?

Drupal supports multiple database backends, but both MEMORY and the concept of storage engines as a whole is MySQL specific. Therefore, the Schema API has no support for specifying the storage engine.


How to import taxonomy with hierarchy? We're upgrading our site from D7 to D8, which has vocabulary containing multi-level parent-child hierarchy. The list is too long (around 5K-10K terms) to import manually.

We've tried using migrate in D8 Core and extending it using migrate_plus and migrate_tools module. These works really well when there is no term hierarchy.

How can we get it working for importing term with hierarchy. The value it accepts for parent is term id. If we pass the parent name (as we're importing it for first-time), it creates the term at root level. Are we missing anything? If we can not do this only with these modules,  how can we extend these modules. References would also greatly appreciated.

If you want to import Taxonomy with Hierarchy along with the existing tid then follow the following.
Configure your import configuration some thing like this

id: taxonomy_migration
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags:
 - CSV
migration_group: null
label: 'Taxonomy migration from CSV'
source:
  plugin: csv
  path: test.csv //path of file
  header_row_count: 1
  keys:
    - tid //unique key which is used for mapping while importing other content related with this taxonomy
process:
  parent: //this is for your parent term id
    plugin: migration_lookup
    migration: taxonomy_migration //this is the current migration id which will help you to make parent child on taxonomy
    source: pid //parent id source from your csv file
  name: term
  tid: tid
destination:
  plugin: 'entity:taxonomy_term'
  default_bundle: test_taxonomy //your vocabulary machine name where you want to import
migration_dependencies: null
migration_dependencies: null

now your csv file will be like this

now you can check your taxonomy, result will be like in the image below with existing tid.


Programmatically get menu links filtered by language In Drupal 8, I'm trying to get my menu which has translated menu item filtered by a given language.

So far, I was able to get my menu tree :

    $menu_parameters = $this->menuLinkTree->getCurrentRouteMenuTreeParameters('main');
    $menu_tree = $this->menuLinkTree->load('main', $menu_parameters);
    $manipulators = array(
        // Only show links that are accessible for the current user.
        array('callable' => 'menu.default_tree_manipulators:checkAccess'),
        // Use the default sorting of menu links.
        array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $menu_tree = $this->menuLinkTree->transform($menu_tree, $manipulators);

But I still have "stand alone" links in both language.

I looked into manipulators and parameters, but couldn't see anything related to translation.

Maybe using MenuTreeParameters::addCondition, but i'm missing something here.

Any help would be greatly appreciated.

@pbonnefoi.
I've played a lot around with a filtering of menu items by language while worked on menu block multilingual task.

Here what I got:
Drupal\menu_link_content\Plugin\Menu\MenuLinkContent is responsible for retrieving of menu_link entity, but this class hides from us getEntity() method, using one we could get menu link language ($link->getEntity()->get('langcode'))

So the trick is:

Extend this plugin by a new method getLanguage() and register it. This plugin used in
the menu.tree_storage service, also you need to change link
provider class and plugin class to yours.
Create a new manipulator yourmodule.menu_manipulators:filterByLang,
and use it wherever you want like: ['callable' =>
'yourmodule.menu_manipulators:filterByLang', 'args' => ['langcode'
=> $langcode]]

Result code can be something like:

class MenuMultilingualServiceProvider extends ServiceProviderBase {

  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('menu.tree_storage');
    $definition->setClass('Drupal\yourmodule\Menu\MenuTreeStorageMultilingual');
  }
}

class MenuTreeStorageMultilingual extends MenuTreeStorage {
  protected function doCollectRoutesAndDefinitions(array $tree, array &$definitions) {
    foreach ($definitions as &$definition) {
      if ($definition['provider'] == 'menu_link_content') {
        $definition['class'] = 'Drupal\yourmodule\Plugin\Menu\MenuLinkContentMultilingual';
      }
    }
    return parent::doCollectRoutesAndDefinitions($tree, $definitions);
  }

  protected function loadLinks($menu_name, MenuTreeParameters $parameters) {
    $links = parent::loadLinks($menu_name, $parameters);
    foreach ($links as &$link) {
      if ($link['provider'] == 'menu_link_content') {
        $link['class'] = 'Drupal\yourmodule\Plugin\Menu\MenuLinkContentMultilingual';
      }
    }
    return $links;
  }

}

UPDATE:
Also tuutti created another solution for that using a new menu tree manipulator menu_block_current_language_tree_manipulator::filterLanguages inside a new menu block type.

Here is his sandbox https://www.drupal.org/sandbox/tuutti/2832329

Also welcome to the discussion regarding translatable menu links on the d.o https://www.drupal.org/node/2466553

UPDATE 2:
I've created a module for the end user to bring multilingual features to the menu blocks https://www.drupal.org/sandbox/matsbla/2831709

You can refer to it as an example of all said above.


Views 3, link picture/title to users blog I have a view of active blog users and I want to link the title of each blogger to their blog ie /blog/[uid].

By default, it seems views can link the blogger title to their profile ie (/user/uid) but I want to link the blogger title to their blog (/blog/uid)

Any idea of how I can go about this please?

Thanks,

Figured this out:

Add field uid to views.
Go to picture field in views, click rewrite results and output this as link, and then for link path: /blogs/[uid]

Make sure the field uid is visabally above al lthe other field in the view.


Returning HTML from a controller I have followed the guide at http://befused.com/drupal/first-drupal8-module to create a simple Drupal 8 controller, and it works as described. Instead of printing "Hello World" I would like to create more complex HTML.
I found a guide that appears to step through what I need to do at http://jonathanpatrick.me/blog/safe-markup. I added hook_theme to my flot_d8.module file:

function flot_d8_theme(array $existing, $type, $theme, $path) {
  return array(
    'flot_d8_my_template' => array(
      'template' => 'my-template',
      'variables' => array(
        'variable1' => NULL,
        'variable2' => NULL,
      ),
    ),
  );
}

and created the my-template.html.twig file exactly as shown:

  This is the first variable: {{ variable1 }}.
  This is the second variable: {{ variable2 }}.

I'm guessing my problem is in the way I try to call the theme. My controller code is:

namespace Drupal\flot_d8\Controller;
use Drupal\Core\Controller\ControllerBase;
class Flot_d8 extends ControllerBase {
  public function content() {
    return [
      '#theme' => 'flot_d8_my_template',
      '#variable1' => t("First"),
      '#variable2' => t("Second"),
    ];
  }
}

Is this the correct way to print a
 to the screen? Do I need to register the template file in my info file somewhere?

I removed the template line from hook_theme and renamed the file to flot-d8-my-template. Cleared the cache and it worked.


How to get teaser break to work with WYSIWYG + CKEDITOR? I have Drupal 7.7 + WYSIWYG 7.x-2.1 + CKEDITOR 3.6.1 installed.

My goal is to be able to insert a teaser break into my blog posts (blog post content type - body field), in order to specify what goes into the teaser and what goes into the full node view.

When I click the "Separate the teaser and body of this content" button in the CK EDITOR menu bar, the text <!--break--> is automatically inserted into my body field. However, this break is not having any effect on the text that remains in the teaser view vs. on the full node view. It simply doesn't seem to be working. I tried using TinyMCE and I had the same problem

Can anybody please advise on how can I get this function working?

Thanks!

---More details about my current setup: ----------------

In the CK editor profile for "Filtered HTML" - in the "CLEANUP AND OUTPUT OPTIONS", the following options are enabled:
- Verify HTML
- Convert  tags to styles
- Remove linebreaks

These options are not enabled:
- Preformatted
- Apply source formatting
- Force cleanup on standard paste

Adding <!--> to the set of allowed HTML tags for the Filtered HTML format solved this problem for me. To do so, these are the steps to be performed:

Navigate to admin/config/content/formats/filtered_html.
Within "Filter settings", select the "Limit allowed HTML tags".
Within the field with label "Allowed HTML tags", add the string <!--> (in addition to whatever set of HTML tags you already have).
Save configuration.


Views related nodes with contextual filters multiple-value handling problem I created a related nodes block with views.

Everything seems good but there is one problem that I couldn't find a solution for days.

The views has Content: Has taxonomy term ID (with depth) as contextual filter.

If a node has only one taxonomy term there is no problem and the related views block shows the related nodes tagged with the same taxonomy term.

But if a node has multiple taxonomy terms, the related nodes block shows all the nodes that are tagged with any of the taxonomy terms although I selected the Filter to items that share all terms option.

Is there any way to solve this problem?

The answer was very simple but I missed it, you don't miss it if you are in the same situation:

Tick the Allow multiple values below the MORE part in contextual filter.


How to transfer Userpoints between users? I installed the User Points module (v7.x-1.0) and after going through all of the configuration I cannot seem to find the option for transferring Points between users.

Can someone point out how I find/activate this feature?

Module Userpoints Donation has to be used.


Group content types together I have a view (table style) filtered three content types, added fields i want, but each type has a date field.

I needed to group all's nodes by date so i added a Global: custom text with replacement patterns i get what i need (one date field to three content types).

I grouped my view by this field but the problem is each content type has own table.

how can i group those three content types together in one table for every date value?

OK, I think I'm noticing this difference: when I don't set a field to sort by, my content types seem to be in separate tables too.

But if I set the 'Sort Criteria' to a field that all of the content types have, like 'Post date', desc, then I get all the content types correctly incorporated into one table:

Anyway, hope this helps you!


Mandatory field (A or B) in a content type I have a content type (external_document) that has an entity relation to an "event" and an entity relation to a "project."

I would like to be able to have some validation rule saying: All the documents must be "linked" to either an event or a project.

I am unclear on the following:

How  to do it on D7?
What is the proper name for that in Drupal so I can search it?
Is it the "Drupal" way of doing the content type with 2 entity relations?

You could use the Field validation module to take out some of the legwork.

  This module adds an extra tab to each field instance, allowing you to
  specify validation rules for your field instances.

There's a validation rule built in for

  Require at least one of several fields

which is exactly what you're after.


How to show a link only if a node author has a certain role I have a block with which I'm creating a menu for users

<?php global $user;?>
  <a href="/user/<?php print $user->uid; ?>/ideabooks">MENU1
  <a href="/user/<?php print $user->uid; ?>">MENU2
  <a href="/user/<?php print $user->uid; ?>/ideas">MENU3

This block will only be visible on user profiles. Now I want to add another link only if the profile owner has a certain role.
So I guess I have to be able to get the node author(profile owner) and then check it's role.

How may I do this?

You can use menu_get_object() to easily and cleanly get information on what you looking at, eg, something along these lines:

$mgo=menu_get_object('user');

if ($mgo) { // we are looking at a user

  if (in_array('CERTAIN ROLE', $mgo->roles)) {

    // do whatever

  }

}

and if the user you are looking at, eg, user/###, has a CERTAIN ROLE, then you can do whatever.

Now, from your question, I am going to go out on a limb and assume you are creating this block from the Block UI and using the PHP Filter, so I guess it would look like this:

<?php $mgo=menu_get_object('user') ?>
<?php if ($mgo): ?>
  <?php if (in_array('CERTAIN ROLE', $mgo->roles)): ?>
    <a href="/user/<?php print $mgo->uid; ?>/menu4">MENU4
  <?php endif; ?>
<?php endif; ?>

but I would strongly urge you to consider writing a module for this as the PHP filter opens up soooo many potential holes.

Also, as @olyn has pointed out, $user points to the logged in user, not to the owner of the profile you are looking at, so you will want to look into that in your code as well for your other links, eg, $user->uid is the uid of the currently logged in user; in my code above $mgo->uid is the user id of the profile you are looking at.


Modifying the default user registration page I previously asked this question about modifying the default user registration form. The default form is largely fine, I just want to add some text and some links above and below the form (i.e. instructional advice etc).

One of the answers to my previous question suggested creating a module with the hook form_alter. I did this, however, it seemed all that achieved was adding adding new text fields to the form. I don't want to add new text fields, just some additional text/html before and after the form.

Is there any way to do this with form_alter, and if so, could you detail the code I'd need to do this (such that is does not add another user visible field)?

If there's another way to modify the page directly (not just the form) could you detail it? Keep in mind I want this to work with all themes, so when I change themes my changes do not disappear (which is why I was hoping to be able to do it in a module).

I use this way to custom my user login page, I think u can also custom form and use same validate/submit function like user_register_form  did

$form['#validate'][] = 'user_register_validate';
$form['#submit'][] = 'user_register_submit';


What are the ways/strategies to maintain Drupal sites a over period of 10-15 years? We have started using Drupal as a PHP programming framework (and not just as a CMS). As result, we have many projects running on Drupal (6 or 7).

Typically, after 2-3 years a project gets over and no further development is done on that project. Then, we put that project into a maintenance or dormant mode.

The problem is that at the end of a project, there is hardly any money left for actively maintaining (e.g updating modules/core for security fixes) that project for over a period of say 10 years. And, there is no way that we can ask for maintenance money for a project (this is a sad fact).

So, we were brainstorming what would be the way to maintain Drupal sites securely for say a period of at least 10 years.

Some ideas were:

Convert entire Drupal site into bunch of static pages using some tool (I suspect this might break lot of interactive functionality in Drupal)
Lock down write access to MySQL database
Run dormant Drupal based sites in a Virtual Machine
Block all input fields on a Drupal site including login functionality (i.e make all content publicly accessible)

I also expect that in a period of 10 years following things might happen:

A server's hardware might be upgraded
A new PHP version might be installed
A new MySQL database might be installed
A server's OS might not be supported by a vendor for security updates
Certain Drupal modules may not be supported or may get deprecated by an other module
In the worst case, the required PHP or MySQL versions itself may not be supported by the community

What are the ways/strategies to securely maintain (i.e. keep them running) dormant Drupal sites for a very long period?

Like you mentioned there are many moving parts about Drupal that can require maintenance, so your strategy should be to remove as many dependencies as you can within your requirements.

If it is not a requirement that your Drupal sites continue as dynamic systems where content can be created, updated, or deleted then you should remove MySQL and PHP by generating static files. There is good documentation for creating static archives of a Drupal site at http://drupal.org/node/27882.

Since you mentioned putting the site into a "maintenance or dormant mode" it sounds like a static solution would be the best for you.

If you require the continual functional use of the site you could consider moving the site to a managed solution. Managed hosting providers can take care of the web and database server, but for further management of the Drupal code you could consider a service like http://drupalgardens.com.


How to know add/edit page in hook_form_alter? I want to know whether form is add/edit in hook_form_alter. In Drupal 7 we can get all these in hook_form_alter.

I tried like this in D7:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Check pages(s) , don't use $_GET.
    if (strpos($form['#action'], '/add/') !== FALSE) {
      $page = 'add';
    }
    if (strpos($form['#action'], '/edit') !== FALSE) {
      $page = 'edit';
    }
}

Here I am getting add/edit in D7. Whereas in D8 I am not getting any it in $form['#actions']. And i don't want to use $_GET.
Is there any way to check add/edit page in hook_form_alter.

In D8 you can get the operation of an entity form with the form object:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_state->getFormObject()->getOperation() == 'edit') {
    $page = 'edit';
  }
}


Password-protect page and its dependencies I haved a Views-generated page, listing links to some downloadable files. The page itself is restricted to a certain role, and this obviously works ok, but I would also like to protect all the links listed on the page.

Currently, an authenticated user with a privilege to view the page, can send a working download link to anonymous user, which is not ok.

Of course, I could certainly protect the files directory with htaccess, but I would like to manage the access and session validity from Drupal.

Has anybody solved a similar setup? Are there any modules for that?

Webform protected downloads seems to be an answer.


How do I display all the nodes in an organic group? I'm on d7. Im trying to figure out how to display all the nodes that are in an organic group. I feel like this is a major thing that the OG module should do and don't know why I cant figure it out. I have views installed and have looked at the OG content view, but it doesn't display anything when I test it with the preview filter. Ive seen a video on how to do this with panels, but I don't have panels installed and don't plan on it. Thanks for the help.

Here's how you can do it with views in Drupal 7.  Create a new view of nodes as you normally would, but make sure you set up the appropriate relationship for it that will allow you to filter your nodes based on their group membership:

Add a relationship (under the 'Advanced' section of the view)
Select the 'OG membership: OG membership from Node' field, which is under the 'OG membership' section of the fields

Mark this as a required relationship on the next screen if you don't want to include nodes/content that do not have a group
Only after you've added that relationship will you be able to see the appropriate 'Group id' filter.  Go ahead and add a 'Contextual filter', also under the 'Advanced' section and select 'OG membership: Group ID'.

This filter will now allow you to input the Group Id as a filter to the view through the URL (test it with www.[your site].com/[your view path]/[group id]) or by figuring out which group you're currently in if you set the following screen properly for the contextual filter

You can now test this in the view preview pane by entering in different OG id's and seeing that it should filter the list of nodes to ones only with those Groups set as their audience.

Let us know if this worked for you!!


Customize content page in backend with more filters I need to add more filters like content type, Taxonomy to back end content() in drupal. Hacking the core is not a good method. Is there any alter hooks are available?. Can create a new view page with exposed filters and do a views bulk operation on it?

There's a module for it! :)
You should take a look at Administration Views. This module gives you all you need. Just create views for nodes or users or use the default ones that come with the module. It has a dependency to Views Bulk Operations as it can perform customizable tasks, like mass deleting or changing values.


Batch API callback method is not call Here is my source:

function sc_delete_user_confirm_form_submit($form, &$form_state) {
   //...
      $batch = array(
        'operations' => array(),
        'finished' => 'user_delete_tickets_batch_finished',
        'title' => t('Processing delete user tickets'),
        'init_message' => t('Deleting user tickets is starting.'),
        'progress_message' => t('Processing...'),
        'error_message' => t('Deleting user tickets has encountered an error.'),
      );
      $batch['operations'][] = array('user_delete_tickets_batch_process', array());
      batch_set($batch);
  //...
}

function user_delete_tickets_batch_process(&$context) {
  watchdog('my_module', 'user_delete_tickets_batch_process ENTER!', array(),  WATCHDOG_ERROR);
  //...
}

function user_delete_tickets_batch_finished($success, $results, $operations) {
  watchdog(my_module', 'user_delete_tickets_batch_finished ENTER!', array(), WATCHDOG_ERROR);
  //...
}

I see progress bar but it not call my callback method user_delete_tickets_batch_process (I didn't see log in /admin/reports/dblog), also it not call user_delete_tickets_batch_finished.
What is wrong in this my source.

Try specifing the file where your functions are located.

Even if those functions are in the same file as your #submit callback, the file path may be needed.

$batch = array(
  'operations' => array(),
  'finished' => 'user_delete_tickets_batch_finished',
  'title' => t('Processing delete user tickets'),
  'init_message' => t('Deleting user tickets is starting.'),
  'progress_message' => t('Processing...'),
  'error_message' => t('Deleting user tickets has encountered an error.'),
  'file' => drupal_get_path('module', 'your_module') . '/your_module.module'
);


Why do I have error related to unknown themes during synchronization? When I try do synchronize from my local site to the remote one, I get this bunch of errors which prevent configuration to be imported.

It seems to be related to some themes (alpha_responsive_theme, elegant_theme, mm, nucleus, tb_sirate, zeropoint) but why?
I'm pretty sure I don't have these theme in my configuration: I have these folders in core/themes bartik, classy, engines, seven, stable, stark and onepage_zymphonies_theme which is set to be the default one (seven being the Administration theme).

Any idea why it happens?
And how to get rid of it?
Thanks in advance.

At some point, the config you are using has had those themes enabled.  Either from another site that you got the config set/ database from (e.g. the distro install?) or the themes were install/uninstalled/deleted on the dev machine (testing different themes?).

Since you seem to have the *.settings files for the themes, these were probably installed and then deleted without uninstalling them.  When a theme is uninstalled, this configuration information is removed.

To get rid of them, add back in the themes, re-enable them and then uninstall them.

An alternative is to use "drush cli"  / the log messages to identify the configuration object names.  Then use "drush cdel" to remove them from your dev box.  NOTE: backup your db prior to this!

Or you can find the yaml files in the exported configuration and remove them.  But you will have to do this each time you export to the remote site.

Another possible way is to try the easy uninstall project. Haven't used it but is seems to provide a GUI way to clean up the configuration.

Soapbox Warning

IMHO this is one of the great problems with Drupal 8 using a massive blob of config files.  Developers will test stuff and decide not use it.. and it's impossible to find the cruft in the massive blob...

Features is now available for D8.  It's a pain to set up, but your large blog can become a more manageable set of smaller config sets.


Registration and Login form having different styles I'm trying to style the login and registration form in different styles in my drupal 7 website. By default they share the same styles. Is there any way to change that?

take a look at the themekey module:

  ThemeKey allows you to define simple or sophisticated theme-switching
  rules which allow automatic selection of a theme depending on current
  path, taxonomy terms, language, node-type, and many, many other
  properties. It can also be easily extended to support additional
  properties exposed by other modules.


How to show People menu in Admin for role restricted user? Created role "tech support" for help desk to address user account issues.

Granted this role the following privs:

Administration
  Access administration menu

User
  Administer permissions
  Administer users
  View user profiles
  Change own username
  Cancel own user account
  Select method for cancelling own account

The Administration menu does not display for the user - I see the home icon and nothing else.  I did enable clear cache just to see something will display and it does.

Yet if I go to /admin/people, the user with this role can perform the actions I desire.  My issue is simply displaying the People menu item.

Any thoughts/pointers?  This is a production environment, I need to be able to do this without adding new modules to the system.

I think you need to grant them "Use the administration pages and help"


Behavior for displaying map doesn't run I'm trying to create a pretty straightforward page with a Google map that I need to customize, but the code in the behavior isn't being run for some reason. Here's the code:

/**
 * Implementation of hook_theme
 */
function mymodule_theme() {
  return array(
    'affiliates_map' => array(
      'template' => 'affiliates-map',
      'path' => drupal_get_path('module', 'mymodule') . '/templates',
      'render element' => 'content',
     )
  );
}

/*
 * Page callback for map page.
 */
function mymodule_search_map() {
  drupal_add_css('
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map {
        height: 100%;
      }', array('group' => CSS_DEFAULT, 'type' => 'inline'));

  $path = drupal_get_path('module', 'mymodule');
  $gmap_api_key = variable_get('affiliates_gmap_api_key', '');
  drupal_add_js('//maps.google.com/maps/api/js?v=3&key=' . $gmap_api_key . '&callback=initMap',  array('type' => 'external'));
  drupal_add_js($path . '/js/mymodule.js', array('type' => 'file', 'weight' => 6, 'scope' => 'footer'));

  $output = theme('affiliates_map');

  return $output;
}

Here's my theme template.

<?php
/**
 * @file
 *   This template handles the display of the affiliates map.
 */
?>

Map content goes here

and the js file

(function($) {
  Drupal.behaviors.affiliatesMap = {
    attach: function (context, settings) {
      var map;

      function initMap() {
        map = new google.maps.Map(document.getElementById('naa-map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 14
        });
      }
    }
  };
}(jQuery));

My console is giving me an error about initMap() not being found, and when I put a breakpoint in the behavior in initMap, it doesn't get hit. What am I doing wrong that it's not finding the behavior code? I've mimicked the Location Map module, and it works fine, so I'm not sure where I went wrong.

Thanks.

The issue ended up being my CSS. I was using styles from the sample page that had a height of 100%. Once I added some height and width to my naa-map div, my map showed up fine.


display all products in a single page (without using pager) ubercart I'm trying to display all products on a single page without a pager. Some sites have this functionality where you can click from page to page, or you can choose 'show all'. Or there is a drop down box where you can select how many products you want to view like this: http://www.newegg.com/Store/SubCategory.aspx?SubCategory=32&name=Laptops-Notebooks&Pagesize=100

Does ubercart have anything like this out of the box? I'm using the taxonomy_term views to display my categorized products right now. So for example, for a category:show, you can get there by going to: taxonomy/term/12 which I override to be category/shoe (with pathauto aliases).

You could use the Views module to create a Page display that lists all your products.

Also, I haven't tried it myself, but here's a blog post on Exposing Items Per Page in Drupal Views. A patch has been committed to the 6.x-3.x version of Views that apparently offers a similar "items per page" select box.


Trouble with session ID and Drupal cookies when trying to establish a connection with Service Module and http-post I am trying to complete an http-post between my common lisp application and my Drupal Site running Services and a Rest server.  Currently I have my rest server set up to accept user login, and using Poster (Firefox plugin to create http requests) I am able to connect to my rest server.  Also, using Poster  if I am currently logged in I get a response "406 Not Acceptable: Already logged in as.." and if I am not logged in I get "200 OK" and when I go back to my browser I am logged in to my Drupal site.

Now I have been trying to simulate this same behavior using an http-post from my lisp application and I have been having a lot of trouble.  For a long time I was always getting "200 OK" if I had correct username and password in the body of my post looking something like this:

username=ender2012&password=password&form_id=user_login

but it would not actually login and if I was already logged in I would never receive the 406 response that I expected.  Finally I downloaded HttpFox which showed me the actual post that Poster was sending and I noticed that Poster was sending a Cookie header that looked like this

Cookie: Drupal.toolbar.collapsed=1; CAKEPHP=10e32669174a611c8919eeff471a2a1c; Drupal.tableDrag.showWeight=0; has_js=1; SESSdc0685ed01f285dab628a3700259e6bc=3qqK5XPaLRhEx7o4wAbIq5qK9qHEzRxz5qUnYZsaXG0

Now if I add a Cookie header to my lisp application's post with the Cookie I saw in http-post from Poster and I am logged in, I will get the 406.  So it seems that there is some sort of session information stored in this cookie that I will need to use for my lisp application but I am unsure about how this would all work inside my application.  Could anyone help me understand all of this?

Details:

• I am running Drupal 7

• I am using Services 3.0

• I am using a rest server with session authentication

• I am using application/x-www-form-urlencoded

• I am running this server on MAMP localhost currently

All of the cookie information is set and returned in the response header of the login call.

This might also be of some help which explains how to make authenticated calls via a remote client.
http://drupal.org/node/910598

Also note that if you use a Firefox plugin, it will be able to access the cookie set in Firefox. Thus if you use a different application that cookie will be different, so you will not be able to auth via your custom app and simultaneously see yourself as logged in in Firefox.


How can I prevent users from entering invalid e-mail addresses at registration? Sometimes users mistakenly input the wrong e-mail address upon user registration.  When this happens, they are unable to activate their account, because the password is e-mailed to their e-mail address (or, in my case, I'm actually using Logintoboggan, but they still need to click the link in their e-mail before their account can be activated).

Often in this situation, the user will realize their mistake and simply re-register.  This is ok, but then I have to clean up the accounts that never get activated, which is a pain.  I've noticed that the Drupal 7 registration will accept a bad domain in the e-mail address by default (for example, yahoo.co.jap, which is an invalid TLD).  When I realized this, I thought surely someone has already written a module to cover this use case (making sure users input a valid e-mail address on registration), but I was unable to find it.  Does such a module exist?

Drupal validates the email since Drupal 5; since Drupal 7, valid_email_address() (the function used to validate the email entered during registration, or when editing a user account) calls filter_var().
The code used to validate the email address doesn't check if the domain exists, the username doesn't contain typos, or the domain has an active email server. While it would be possible to check if the domain has an email server by looking at its MX records with checkdnsrr(), it would be more difficult to verify if the username is correct, as most of the SMTP hosts doesn't return a useful value for the VRFY command (which means they always return ERROR, or OK).

Notice that the documentation for getmxrr() contains the following note.

  This function should not be used for the purposes of address verification. Only the mailexchangers found in DNS are returned, however, according to RFC 2821 when no mail exchangers are listed, $hostname itself should be used as the only mail exchanger with a priority of 0.

I would rather do as @Letharion suggested, and implement hook_cron() to get ride of those accounts created by users who didn't type their email correctly. For Drupal 7, I would use the following code.

function mymodule_cron_queue_info() {
  $queues['mymodule_delete_users'] = array(
    'worker callback' => 'user_delete_user',
    'time' => 30,
  );

  return $queues;
}

function mymodule_cron() {
  $query = new EntityFieldQuery();

  $query->entityCondition('entity_type', 'user')
    ->entityCondition('entity_id', 1, '>')
    ->propertyCondition('access', 0)
    ->propertyCondition('created', REQUEST_TIME - MYMODULE_DELAY, '<')
    ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');

  $result = $query->execute();

  if (isset($result['user'])) {
    $queue = DrupalQueue::get('mymodule_delete_users');
    foreach (array_keys($result['user']) as $uid) {
      $queue->createItem($uid);
    }
  }
}

The module should define the constant MYMODULE_DELAY, and set it to an appropriate value.


Is there a clean-URL-reflective version of file_create_url()? I have a site with clean URLs enabled and in a test I've written, I compare the current drupalGetHeader('location') to file_create_url($file->uri). The tests passes on my site, but on the qa.drupal.org testbot (and, presumably, on any site that doesn't have clean URLs enabled) the test fails.

Is there an API function that's more clean-URL-reflective to file_create_url()?

I ended up using

str_replace('/?q=', '/'drupalGetHeader('location'));

So basically I gave up on including the ?q= that appears in the URL and instead stripped it from everything. It seems a little messy but it works for my purpose. Still doesn't really answer the question though.

drupal_parse_url() looked promising at first, but it didn't work because

drupal_parse_url(file_create_url($uri)) returned 'path' = http://example.com/path/to/file

but

drupal_parse_url(drupal_get_headers('location')) returned simply 'path' = /path/to/file


Trademark symbol in the site title? Do I need a module to put the trademark symbol in the site title? If I add &trade; at the end of the title, it just gets output as is.

You can do this by using HTML TITLE module

  Drupal node titles are restrictive and do not support italicized text
  or superscript text (e.g., Book titles, trademark symbols). The HTML
  Title module allows a limited set of HTML markup (em, sub, sup, b, i,
  strong, cite, code, bdi, wbr) to be used in node titles. It filters
  all other markup from titles to prevent XSS vulnerabilities or
  irrational nesting (e.g., links within links).


How do I fix the "Access denied" error in Organic Groups when I am logged in as admin? I am logged into my site as uid=1 (admin) but I cannot edit the /admin/config/group/roles/node/team page ("Team" is an Organic Group content type), due to getting an

  "Access denied - You are not authorized to access this page."

I have cleared the cache, rebuilt the permissions, and tried a number of other tricks to gain access, all to no avail. Any ideas?

If you temporarily disable og_workbench and it's still happening, you have a bigger problem.  Was OG upgraded from 1.x -> 2.x?

I've found myself in this situation a few times during og upgrades. First, check to make sure all the OG Migrations have been run at admin/content/migrate.  There is a migration named OgMigrateRoles that is often 0 of 0.  Even though there is nothing to migrate, it still needs to run.  If you do that and you still don't have access, check admin/config/group/permissions/node/[OG-ENABLED-CONTENT-TYPE]

You should see 3 columns w/ checkboxes for roles... NON-MEMBER, MEMBER, and ADMINISTRATOR MEMBER.  If you see the rows permissions, but no checkboxes or roles your og_role table may be "hosed" for lack of a more technical term.

It is possible to manually repair this table by inserting rows for the 3 default roles for each of your og enabled content types.  Something like...

INSERT INTO og_role (rid, gid, name, group_type, group_bundle) VALUES
(1, 0, 'non-member', 'node', 'group'),
(2, 0, 'member', 'node', 'group'),
(3, 0, 'administrator member', 'node', 'group');

The rid must be unique and 'group' should be replaced by your og enabled content type's machine name.  Trying to manually repair the table isn't recommended and should only be used if you can't re-install... and even then only if you know your way around MySQL and on a test version of the site.

The good news is I've always been able to fix this with enough time and comparing the hosed og to a working OG2 install.


Getting the value submitted from form with FAPI radios in template.php I have a form with radios on it. I do submit on the same page (there's no $form['#action'] assigned in the below code). What I want to do is to get submitted year in template.php so that I can define my logic based on received value.

To check that's all work fine I wanted print_r the contents of form['values'].
I did that in submit function but it didn't work. Actually, I can't print anything from both validate and submit functions.

So my question is how I can get the submitted value to template.php.

I work with the following code in my module:

function my_module_menu() {
  $items['formexample'] = array(
    'title' => 'View the sample form',
    'page callback' => 'mymodule_page',
    'page arguments' => array('frontpage_form'),
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM
  );
  return $items;
}

function mymodule_page() {
  $output = print_r($_POST, true);
  $output .= drupal_get_form('mymodule_form');
  return $output;
}

/**
* Define a form.
*/
function frontpage_form() {
  $form['years'] = array(
    '#title' => t('Please, choose appropriate year'),
    '#type' => 'radios',
    '#options' => array(
      t('2011'),
      t('2012'),
      t('2013')
     ),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  );
  return $form;
}

/**
* Validate the form.
*/
function frontpage_form_validate($form, &$form_state) {
  if ($form_state['values']['user_name'] == 'King Kong') {
    // We notify the form API that this field has failed validation.
    form_set_error('user_name',
    t('King Kong is not allowed to use this form.'));
  }
}

/**
* Handle post-validation form submission.
*/
function frontpage_form_submit($form, &$form_state) {
  $name = $form_state['values']['years'];
  drupal_set_message(t('Thanks for filling out the form, %name',
  array('%name' => $name)));
}

I think the problem is that your #options array for the radios isn't keyed (which it should be). PHP will automatically assign the keys as 0,1,2 etc but 0 is not valid as Drupal ignores such a value which may be causing you a problem, and I guess you're expecting a value of 2011, 2012 or 2013 which currently you won't get.

Drupal does provide a handy function, drupal_map_assoc to create a keyed array from a flat one. This code:

$array = drupal_map_assoc(array(1, 2, 3));

will produce an array of

array (
  1 => 1,
  2 => 2,
  3 => 3
)

So if your form element looks like this:

$form['years'] = array(
  '#title' => t('Please, choose appropriate year'),
  '#type' => 'radios',
  '#options' => drupal_map_assoc(array(2011, 2012, 2013))
);

In your submit function you would grab the selected value with:

$form_state['values']['years'];

I think you might have a slight confusion in your logic, this bit of code:

$name = $form_state['values']['years'];

is fine to grab values from the $form_state array but years is not a name, it's a year. That might also be adding to the confusion.

EDIT

I've just noticed a few other problems in your code that may be causing unexpected results.

The first one is in mymodule_page(). drupal_get_form() returns an array in Drupal 7 so concatenating it to a string (the return from print_r()) will not produce the results you're expecting.

Secondly, you're calling drupal_get_form('mymodule_form'); and your form is actually named frontpage_form().

Lastly, you don't actually need the mymodule_page() function at all...you can change the page callback of your menu item to drupal_get_form() and the form will automatically be built for you on that page. Remember to clear Drupal's cache once you've made this change.

The last thing I'd say is that relying on print_r for debugging can be very tedious. Instead, I'd advise installing the Devel Module which has a wonderful function called dpm(). This will print a nicely formatted representation of any variable to the standard messages area when you call it. It's a must for Drupal development really.

You'd use it like this, for example in your form submit handler:

dpm($form_state['values']);

EDIT 2

Quick dirty way to get the submitted value into template.php:

In your module file

function frontpage_form_submit($form, &$form_state) {
  frontpage_submitted_value($form_state['values']['some_value']);
}

function frontpage_submitted_value($new_value = NULL) {
  $value = &drupal_static(__FUNCTION__, FALSE);

  if ($new_value) {
    $value = $new_value;
  }

  return $value;
}

And then in a function in template.php

if ($submitted_value = frontpage_submitted_value()) {
  $vars['some_val'] = $submitted_value;
}


Can Commerce Kickstart be used to add Drupal Commerce to an existing site? I want to add the Drupal Commerce module to my existing Drupal website. Is there any way I can use the Commerce Kickstart dstribution for an existing Drupal site?

Seems like you're supposed to use Commerce Kickstart when you're starting to build your Drupal site, but I already built mine.

According to the Commerce Kickstart website it says: "Anyone who wants to skip weeks of configuration to build a commerce site on the Drupal Commerce framework".

Is it really that hard to install the Drupal Commerce module without Commerce Kickstart?

I'm not creating a big store, I just want to sell 1 or 2 items.

No, you can not install an installation profile after Drupal has already been installed. What you can do is make a separate installation with Kickstart Commerce and compare configuration when you're stuck.

How hard Commerce is to install depends on you previous Drupal experience. If this is your first time around with Drupal, it will be pretty hard. But if you're already familiar with entities, views and rules, you'll be fine.


Adding sitewide JS file in module I have a module that will provide a dropdown when creating a new block. Selecting either none, option 1 or option 2 will add a corresponding class to that block. That class will be targeted by a small (>4kb) jquery file. The file needs to be able to access every page since blocks can be put anywhere on the site.

I have seen multiple methods of adding JS files to websites, including editing the theme .info file. What is the best way to accomplish what I am trying to do? If the info file is the best way to go, is there a way to programmatically add the JS file to the info file?

You can add the file to a theme's or module's .info file using scripts[]:

scripts[] = js/my-script.js

The path should be relative to your module root.

See also Writing theme .info files and Writing module .info files.


HREFLANG attribute add I am working on a multilingual site. I have to add HREFLANG attribute so that search engines like Google provide the proper response according to the language of the user and the region.

To implement this, I am using Alternate HREFLANG module which basically add HREFLANG attribute like this :

for all the three languages.

But I want to add language as well as region like this:

In the description of Alternate HREFLANG module description, they mentioned that if you want to alter this attribute, you can use  hook_language_switch_links_alter() and hook_html_head_alter() these hooks.

But when I dsm these, I didn't get the HREFLANG attribute.

Can someone help me to achieve this?

I cant see what is in your "...which basically add HREFLANG attribute like this" and "But I want to add language as well as region like this."

I bet you want to replace, let's say, "en" to "en-GB" right? If so, you need to alter Drupal language ISO. Current is ISO 639, language+region is ISO 3166-1 alpha 2.

BTW for your question, you need something like this to locate the hreflang:

function YOUR_THEME_OR_MODULE_NAME_html_head_alter(&$head_elements) {
  drupal_set_message('<pre>' . print_r($head_elements,1) . '</pre>');
}

Clear cache and reload the page.

UPDATE

An easier way is by adding a custom language. E.g. visit admin/config/regional/language/add

Expand Custom language fieldset.
Enter your desired ISO 3166-1 alpha 2 language code to language code & path prefix language code.
Fill the rest (language name in English, native language name & Direction) as usual.


Render array only working with numeric keys I have a FieldFormatter that outputs a DIV, a table and attaches a JS library.

Normally in Drupal (e.g. Form API) it's possible to label the render array keys however you like? Weirdly in this case, only numbering them seems to work.

If it's a typo, I'm not spotting it, and there are no errors in the log.

Are there differences in how FieldFormatter rendering works?

Working numeric keys:

  public function viewElements(FieldItemListInterface $items, $langcode) {

    // various logic ...

    $build = [];

    $build[0] = [
      // placeholder div for the YouTube player
      '#type' => 'container',
      '#attributes' => [
        'id' => ['youtube-timecode-player'],
      ],
    ];

    // various logic ...

    // attach our timecode.js javascript make the video ID available
    $build[0]['#attached']['library'][] = 'mymodule/youtube_timecode';
    $build[0]['#attached']['drupalSettings']['mymodule']['video_id'] = $video_id;

    $build[1] = [
      '#type' => 'table',
      '#caption' => $this->t('Questions'),
      '#header' => [$this->t('Time'), $this->t('Question')],
      '#rows' => $timecodes
    ];

    return $build;
  }

Non-working text keys (no output and no errors):

(I've changed 0 to video and 1 to timecode_list)

public function viewElements(FieldItemListInterface $items, $langcode) {

    // various logic ...

    $build = [];

    $build['video'] = [
        // placeholder div for the YouTube player
        '#type' => 'container',
        '#attributes' => [
            'id' => ['youtube-timecode-player'],
        ],
    ];

    // various logic ...

    // attach our timecode.js javascript make the video ID available
    $build['video']['#attached']['library'][] = 'mymodule/youtube_timecode';
    $build['video']['#attached']['drupalSettings']['mymodule']['video_id'] = $video_id;

    $build['timecode_list'] = [
        '#type' => 'table',
        '#caption' => $this->t('Questions'),
        '#header' => [$this->t('Time'), $this->t('Question')],
        '#rows' => $timecodes
    ];

    return $build;

}

The return value of FormatterInterface::viewElements is defined as:

  Return value

  array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

The theming layer can't handle other arrays for field values, see  How to print all values of a multi-value field, except the first?