How to prevent installing module in already installed module? I have few modules that provide the same functionality in a different way and they would collide if they would be installed simultaneously.

So I want to prevent installation of multiple modules of this "type". I do not want to add hook_requirements into each one of these modules, I'd prefer to have a central logic(in a "central" module, or profile even).

What would be a good approach to this?

How about this?

Create a central module that implements hook_module_preinstall
Follow some naming convention for the modules which should not coexist, or simply gather their names in a list
Use your naming convention or the list of module names in your hook to detect installation of one of these modules. Also, implement the logic for counting the number of such modules that are already enabled in the system.
Conditional on one such module arriving as an argument to hook_module_preinstall and the count of existing enabled modules of this kind being greater than 0, throw a custom Exception in order to block the installation of the said module.
Most importantly, add your central module as a dependency to all of your modules that you wanna control in that way.

Very theoretical answer. :-)
May it be of help to you!


How to automatically modify a field after saving content? I have posted this question on drupal.org (via a comment titled "field modification triggered by saving action"), but I realized that the thread is more than five years old. So I reproduce here the question made there:

field modification triggered by saving action

I need to modify a field, but this change has to be triggered when saving the term and it depends on the value of another field, let me explain ...

term

field 1: filled with options A/B/C
field 2: <info>random_name

I save and if value in

Field 1 is A, then value in Field 2 must change to "Source: random_name"
Field 1 is B, then value in Field 2 must change to "Destination: random_name"
Field 1 is C, then value in Field 2 must change to "Product: random_name"

Note that the label <info> is the one that must change.

You can use the Rules module to get this logic implemented. Have a look at my answer to "How to set the values of some fields depending on the value of a list box?".

The rule shown there uses these fields:

a selection list field with machine name field_optionlist (corresponds to your field 1).
a text field with machine name field_free_format_text (corresponds to your field 2).

If you adapt the machine names in that rule (in Rules export format) to the names from your 2 fields, should be straight forward to further tune (customize) it to also match the values as in your case.

However, to make this to work with only 1 rule (instead of writing 3 rules, ie one for each possible value of field 1, so one for "A", one for "B" and one for "C"), you also need the "Conditional Rules module. That way you could expand the prototype to say dozens of different possible values. For an example using the Rules Conditional module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

Best practice advise: the more you start using the Rules module, the more you should try to group rules together using the Rules Conditional module. Just to keep the entire set of rules manage-able (eg to have related business logic shown on a single Rule UI screen). A good sample of how easy it is to end up with a lot of rules, is what you can see in the Answers module (current 7.x-4.x-rc2 version):

It comes with 12 separated rules (not using the Rules Conditional module).
By using Rules Conditional, those 12 could be reduced to only 4 (possibly even less).


Fully display only most recent post on front page, furl the others Currently my Front page will only show a teaser for all my new posts.

I know that I can go to Structure > Views > Frontpage and change it to show Content | Full which will show the full post of every post on the front page.

What I would like to do though is show the full post of only my most recent post, and then a teaser of all the others.

Is it possible to do this?

You can render a views block within another views page. E.g. you want to show 10 nodes in total, and 1 of them in full mode:

Duplicate the existing view display as a new display of type "block". (Do not duplicate the entire view, only the sub-display by using "Duplicate as block").
In the original page display, in the Pager section, limit the number of items to 1.
In the original page display, in the Format section, set the view mode to full.
In the new block display, in the Pager section, limit the number of nodes to 9 and set the offset to 1.
In the new block display, in the Formatw section, set the view mode to Teaser. While changing the Format make sure to change the settings only "for: this block (override)" and not "for: All displays".
In the orignal page display, in the Footer section, add a "View area" and place the newly created block display. Here also change those settings only "for: this page (override)".


Use ajax to render a view - pagination not working I'm trying to render a view using Ajax, but I can't get the ajax pagination to work. I've found the following code which works, apart from the pagination:

            $.ajax({
                url: '/views/ajax',
                type: 'post',
                data: {
                    view_name: 'stores',
                    view_display_id: 'default',
                    view_args: {},
                },
                dataType: 'json',
                success: function (response) {
                    if (response[1] !== undefined) {
                        $('.store-locator-view-wrap').html(response[1].data);
                        Drupal.attachBehaviors(); // Thought this would do it, but nope
                    }
                }
            });

The links go to /views/ajax?page=1 with the following json:

[{"command":"settings","settings":{"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"rhm_starter","theme_token":"dRce3KwWhWs1ZpnNe6KVUu31mLX8pdVoZ5XixJo8SVI"}},"merge":true}]
::1

The problem here is that the Drupal.settings does not have the proper views key it needs to attach the behaviors if you are loading a view via views/ajax.

There is no good documentation on this, spend alot of time trying to figure it out, but this ended up working. I had to set the views key in the settings manually:

success: function (response) {
    if (response[1] !== undefined) {
        $('.store-locator-view-wrap').html(response[1].data);

        // Set views key based on response data.
        Drupal.settings.views = response[0].settings.views;
        Drupal.attachBehaviors();
    }
}

I also had to make sure the Views js files had been added to my page:

$views_path = drupal_get_path('module', 'views');
drupal_add_js(
    $views_path . '/js/base.js',
    array(
        'type' => 'file',
        'scope' => 'footer',
        'group' => JS_DEFAULT,
    )
);
drupal_add_js(
    $views_path . '/js/ajax_view.js',
    array(
        'type' => 'file',
        'scope' => 'footer',
        'group' => JS_DEFAULT,
    )
);


Cache Exclude functionality in Drupal 8 How can I prevent a specific node - or a list of specific nodes - being cached server-side in Drupal 8?

I have page that pulls a value out of a $_SESSION variable using a PHP text block, and it is being cached, which is obviously not what I want.

I fixed this by doing the following:

I appended a cache buster querystring parameter to the link to the page that needed to be kept out of cache (using the timestamp token + random number token)
Added the 'url.query_args' cache context to the required_cache_contexts in services.yml

It puts a bit more strain on the memory use of the cache than just keeping it out of cache altogether, but the \Drupal::service('page_cache_kill_switch')->trigger(); line did not do anything for me at all.

I think it makes sense for the querystring to be part of the default cache context anyway.


Alter schema on creating a new field I want to create a module that on installing and creating a new field on a content type it should alter the schema of another module.

Im trying to use hook_storage_create_field to react on creating an new field but its not running.

function mymodule_field_storage_create_field($field) {
  exit(var_dump($schema));
  $schema = _field_sql_storage_schema($field);
}

Im I misusing the hook? or there is something faulty in my module?

Update

What Im trying to do is to create a new module that extends the Link module to work like Facebook parser.

So when users add a new link a preview will show a preview like this Redsun parser
The functionality is already made and adapted into Drupal, but still having problem extending link schema to have extra fields for images and body fields.

A new widget is added to link field called "link with parser", and it will fire our extra codes to save and validate the link.

hook_field_storage_create_field and hook_field_create are called when the user creates a new field, i.e. from "Manage Fields", "Add new field".  In my tests, hook_field_create was called as expected, but hook_field_storage_create_field was not called.  I did not look into why this was, because (a) you could use hook_field_create here just as well as hook_field_storage_create, and (b) this isn't really the approach you should be taking to implement the functionality you need.  If you were going to modify the schema for the link field, you would do it once when your module was installed, in hook_install.  Your use case is much more complicated than the standard behavior of the link field, though; you would be better off creating your own field type, and do all of your field storage management in one place.  You might want to look at the source for existing fields that have complex data storage needs, such as the date field.


How do I submit call handler on radio button selection? I use the advanced polls module in Drupal 7. I am trying to alter the behaviour so that the vote is submitted as soon as the radio button is selected (without having to hit Vote).

The module is using an ajax callback:

$form['submit'] = array(
'#type' => 'submit',
'#ajax' => array(
  'callback' => 'advpoll_form_submit',
  'wrapper' => 'advpoll-form-' . $values->nid,
  'name' => 'submit1',
),
'#id' => 'edit-submit-advpoll-' . $values->nid,
'#value' => t('Vote'),

);

How can I invoke this callback with radio buttons?

I am happy for a quick and dirty javascript/jQuery solution as time is a real factor.

I have tried a jQuery solution:

$('input[type="radio"]').change(function() {
  $('#advpoll-form-296').trigger('click');
});

However this is not invoking the action as expected.

I cannot call submit() as I don't want to cause a page reload.

I have managed to get my original code to fire by adding a click event to the ajax array in the .module file.

advpoll.module:

function advpoll_choice_form($form, &$form_state, $values) {

$form['submit'] = array(
'#type' => 'submit',
'#ajax' => array(
  'callback' => 'advpoll_form_submit',
  'wrapper' => 'advpoll-form-' . $values->nid,
  'name' => 'submit1',
  'event' => 'click', //Added click event
),
'#id' => 'edit-submit-advpoll-' . $values->nid,
'#value' => t('Vote'),

);

I am aware I should not override code within the module. How would I go about getting this into a theme hook?

This should do it:

$(function() {
  $('input[type="radio"]').on('change', function() {
    $(this).parents('form').submit();
  });
});

You might want to qualify the selector for $('input[type="radio"]') to the scope of the form you're working with, else if you include this in a JavaScript file that's accessed on many different pages, you'll definitely run into problems!

Demo:  http://plnkr.co/edit/8448bjiywnVtbT3CV6s6?p=info


How to add a field for each taxonomy term or entity reference chosen in Content Type? I have a content type ‘Product’. When the user add a product it is necessary to choose a Store (a taxonomy term or another content type). After stores are chosen, it is necessary to add the directly url to that product in that store. More than on store is selectable and he could add or remove another. There are more data in Store type.

It is something like one to multiple to one for each I think…

Product01   > Store 1 > URL01
            > Store 2 > URL02

Product02   > Store 1  > URL03
            > Store 10 > URL04

My options are:

1) Create a field with multiple values. So if the user choose 3 stores he adds 3 fields to that link.
Problem: It is not directly associate and if he changes orders it will associate de wrong url and chaos will happen.

2) Using Conditionals field (Taxonomy Term)
Problem I could not make it work with multiple selected store and for each new term I need to create a specified field.

3) Entity Reference (Content Type)
Can’t find a way to associate multiple select to adicional fields.

X) Rules?
Too much crazy for me, could not even begin thinking with that…

Any help?

Answer is Field Collection Module (https://drupal.org/project/field_collection). There is another called Multifield, you could try (https://drupal.org/project/multifield).

After installed, edit your content type and add an field with field type Field Collection. Go to Structure>Field Collection and there add fields to the Field Collection created in your content type.

After that it is equal to adding a field with reference term to content type.

What this Video https://www.youtube.com/watch?v=1V1ofpgUw-Y


db_delete does not actually delete I'm trying to delete from the dr_cache_form table,in D7, but somehow the record does not get deleted
                 function mymodule_multistep_form_submit($form, &$form_state) {
//.....

                 $form_id = array();
                 $form_id[0]='form_' . $form_state['values']['form_build_id'];
                 $form_id[1]='form_state_' . $form_state['values']['form_build_id'];
                 dd($form_id,'$form_id=');

             $query = db_select('cache_form', 'cf');
             $query->fields('cf',array('cid'))
            ->condition('cid', $form_id[0], '=');

$result = $query->execute()->fetchAll();
dd($result,'$result=');

                $deleted=db_delete('cache_form')
                //->condition('cid', $form_id, 'IN')
                ->condition('cid', $form_id[0], '=')
                ->execute();
                //dpq($deleted);
//              dd($deleted);
}

So in my drupal_debug.log file I find the entries corresponding to the above lines, but when I go to the database in mysql and select * from dr_cache_form where cid='the form id that was printed in the drupal_deug";
then the row is there, it isn't actually deleted.
Do I need to flush somehow the db_delete... all other database operations are working fine, insert, update, select... just this delete does not want to actual delete the row in the db.
the $delete variable is set to 1 after db_delete
I'm calling it from an multistep form in the last step of the form, thus the cid exists in the dr_cache_form table before db_delete is called, as I can see it via phpmyadmin, and also it gets printed in the drupal_debug whit the $result variable

db_delete works fine, but the problem is that I was trying to delete the cache of the current form from within the code of that form e.g. submit form. Logically this is ok for me because I was trying to delete the cache at the end of my multistep form where the user cannot do anything else but navigate away.
There must be a check somewhere either in db_delete not to allow to delete the cache of the current form.
I tried and I managed to delete from cache_form other entries from the exact same place in the code, just not targeting the current_form cache.
I was aware that I'm deleting the cache of the current form, but I just wanted to test that the db_delete works, and then move on with a more complicated logic where I would not delete the current cache but the previous form from the cache.


Make all the fields in a form not required I know that, when I want to run off the #require property of a field in hook_form_alter(), I just need to set #require property of a specific field to FALSE.

How can I remove the #required property  of all the required fields? I want to make the fields not required when the user has a specific role.

Do you have any idea?

If you're ok with the risks that this might well pose to the integrity of your content you could probably use a simple recursive script like the following in a form alter function:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'myform_name') {
    $form['#after_build'][] = '_MYMODULE_remove_required';
  }
}

function _MYMODULE_remove_required(&$element) {
  $element['#required'] = FALSE;

  foreach (element_children($element) as $key) {
    _MYMODULE_remove_required($element[$key]);
  }
}


How can i put two forms build in one module to two URLs I am very new to drupal and working with D7

I have created two form with a custom module. mysite.com/custom is showing both the forms at the same time

I want each of the form to be shown with 2 different URLs. eg mysite.com/custom1 eg mysite.com/custom2

How is it possible.OR is it not possible at all. am i totally wrong in understanding how the module and forms work?

code

function custom_menu() {
  $items['custom'] = array(
      'title' => t('Custom'),
      //'page callback' => 'drupal_get_form',
      'page callback' => 'custom_page_callback',
      //'page arguments' => array('custom_form'),
      //'access arguments' => array('custom module'),
      'access callback' => TRUE,
  );

  return $items;
}

function custom_page_callback() {
  $build = array();

  // Render your two forms here.
  $build['form_one'] = drupal_get_form('custom_form');
  $build['form_two'] = drupal_get_form('custom_second_form');

  return $build;
}
/**
 * Our custom form.
 */
function custom_form($form, &$form_submit) {
  $form['title'] = array(
      '#title' => t('Give a title'),
      '#type' => 'textfield',
      '#required' => TRUE,
  );
  $form['name'] = array(
      '#name' => t('Give a Name'),
      '#type' => 'textfield',
      '#required' => FALSE,
      '#maxlength' => 25,
      '#size' => 10,
  );
  $form['submit'] = array(
      '#value' => 'Add',
      '#type' => 'submit',
  );
  return $form;
}
/**
 * Our custom form second.
 */
function custom_second_form($form, &$form_submit) {
  $form['title'] = array(
      '#title' => t('Give a title'),
      '#type' => 'textfield',
      '#required' => TRUE,
  );

  $form['submit'] = array(
      '#value' => 'Add',
      '#type' => 'submit',
  );
  return $form;
}

Thanks all

Have to make small change on function custom_menu.

Try this code.

function custom_menu() {
  $items['custom/first'] = array(
      'title' => t('Custom'),
      //'page callback' => 'drupal_get_form',
      'page callback' => 'custom_page_first',
      //'page arguments' => array('custom_form'),
      //'access arguments' => array('custom module'),
      'access callback' => TRUE,
  );
  $items['custom/second'] = array(
      'title' => t('Custom'),
      //'page callback' => 'drupal_get_form',
      'page callback' => 'custom_page_second',
      //'page arguments' => array('custom_form'),
      //'access arguments' => array('custom module'),
      'access callback' => TRUE,
  );

  return $items;
}


Pathauto bulk update for taxonomy terms with unchecked “Generate automatic URL alias” I have the same issue addressed for D7 here:
Bulk Generating URL aliases for taxonomy terms doesn't do anything
or here:
Bulk update for unchecked "Generate automatic URL alias"

And I'm looking for a corresponding workaround for D8, querying the DB directly.

For D7 seems that the following solution works:

UPDATE pathauto_state SET pathauto="1" WHERE entity_type="taxonomy_term";

I did some research for D8:

cannot find any "pathauto_state" table within a D8 database
so I tried to find how and where the “Generate automatic URL alias”
is stored but
    without success (see also for this:
    Where is the "Generate automatic URL alias" setting stored?)

Thank you

As I know there is no simple SQL query to update "Generate automatic URL alias" status for nodes and terms for Drupal 8.
Data contained in table key_value but I don't think it's possible to use it directly.


Heartbeat - user delete comment from node -> delete also from heartbeat stream I'm using Heartbeat to show activity on the site. When user post comment to the node Heartbeat activity stream shows that comment. But when user delete comment it does not delete it from the Heartbeat activity stream.

How to delete comment also from Heartbeat activity stream? This should be done of course automatically when user delete comment from the node.

Same thing for deleting nodes.

In the Rules there was no Heartbeat log delete possibility.

Heartbeat module implemented hook_user_delete() and hook_node_delete() hooks itself. take a look at their implementations.. I think you can implement hook_comment_delete($comment) hook in your module to delete activities from heartbeat_activity table. Here is the documentation.


How do i create an item list where the item has a mixture of links and text If I add the following to my controller, the first item in the list displays correctly, but once I concatinate in text, the links are all escaped.

 $basic_items[] = \Drupal::l('Basic example',Url::fromRoute('flot_examples.basic_usage'));
$basic_items[] = \Drupal::l('Different graph types', Url::fromRoute('flot_examples.series_types')) .
" and " .
\Drupal::l('simple categories/textual data', Url::fromRoute('flot_examples.categories'));

$output['basic'] = [
  '#title' => 'Basic Usage',
  '#theme' => 'item_list',
  '#items' => $basic_items,
];

I know the l() function in deprecated, and I should be using:

$basic_items[] = ['#type' => 'link', '#title' => 'Basic Example', '#url' => Url::fromRoute('flot_examples.basic_usage')];

instead, but I can't figure out how to get that to work either.

A simpler method is to use the t() function:

$basic_items[] = \Drupal::l('Basic example', Url::fromRoute('flot_examples.basic_usage'));
$string = 'Setting various options and annotating a chart';
$options = [
  ':options_page' => Url::fromRoute('flot_examples.basic_options')->toString(),
  ':annotating_page' => Url::fromRoute('flot_examples.annotating')->toString(),
];
$basic_items[] = t($string, $options);

$output['basic'] = [
  '#title' => 'Basic Usage',
  '#theme' => 'item_list',
  '#items' => $basic_items
];


Search index stuck at 0%, mysql error on public search, can't clear error I have just discovered that the  Drupal 7 search on my website is giving 'website encountered an unexpected error. Please try again later.' to users who are not logged in.  (it's fine for logged in users.)

Checking the logs, I can see that when a non-logged in user runs a search it causes a mySQL error, which looked like there was a problem because I'd excluded content type admin_only_help from public search.

OK, I'll include that content type in search.  Nope, still the same error.  OK, re-index the search: nope, won't re-index the search, stalls at 0%.

I tried:

setting content type admin_only_help to be indexed.
unpublishing all nodes of content type admin_only_help
re-indexing the search from the admin panel (it stalls)
running drush search-index from the command line (it stalls)
turning off the Custom Search module
clearing cache (after all of the above).

I'd be very grateful for any further suggestions.

The exact error from my logs is:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have
an error in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'WHERE (c.nid = '873') AND
(c.status = '1') AND (n.type <> 'admin_only_help')' at line 2: SELECT COUNT(*)
AS expression FROM {comment} c INNER JOIN {node} n ON n.nid = .nid WHERE
(c.nid = :db_condition_placeholder_0) AND (c.status =
:db_condition_placeholder_1) AND (n.type <> :db_condition_placeholder_2) ;
Array ( [:db_condition_placeholder_0] => 873 [:db_condition_placeholder_1] =>
1 [:db_condition_placeholder_2] => admin_only_help ) in PagerDefault-
>execute() (line 74 of /home/mysite/public_html/includes/pager.inc).

Edit with update:
I tried completely removing the problem content-type admin_only_help and completely removing the two nodes that belonged to that content type.

Now I have this error:

SQLSTATE[42000]: Syntax error or access violation: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
'WHERE (c.nid = '421') AND (c.status = '1')' at line 2: SELECT COUNT(*) AS expression
FROM {comment} c INNER JOIN {node} n ON n.nid = .nid WHERE (c.nid = :db_condition_placeholder_0)
AND (c.status = :db_condition_placeholder_1) ;
Array ( [:db_condition_placeholder_0] => 421 [:db_condition_placeholder_1] => 1 ) in PagerDefault->execute()
(line 74 of /home/mysite/public_html/includes/pager.inc).

And I still can't re-index my database.

I have traced this particular problem to the Node View Permissions Module.  Disabling this module allowed my search to re-index and be seen by users who are not logged in.

There is a patch available here : https://www.drupal.org/node/2564273


How do I display information about a node's author on the full node and not the teaser view? I have added the following to my node.tpl

<?php if ($display_submitted): ?>
 <?php print $user_picture; ?><?php print $name; ?>
<?php endif; ?>

This displays the authors info on the node itself, but also the teaser. How do I change the code to remove it from the teaser, but still keep it on the node?

Just pop an if ($page): condition around it:

<?php if ($page): ?>

  <?php if ($display_submitted): ?>
    <?php print $user_picture; ?><?php print $name; ?>
  <?php endif; ?>

<?php endif;?>

In the context of node.tpl.php $page is defined on the docs page as a:

  Flag for the full page state.


userpoints reset for drupal 7 I need to reset userpoints for all users to zero now that the site is live. how can I do that? there used to be a userpoints_reset module for drupal 6, but it's not yet ported to drupal 7

thanks.

There is D7 patch if you're savvy enough with that. I wouldn't bother with it unless you anticipate reseting frequently. An easier fix is to just truncate all the tables that store the data:

db_query('TRUNCATE {userpoints}');
db_query('TRUNCATE {userpoints_txn}');
db_query('TRUNCATE {userpoints_total}');


How to enable field_ui "Manage display" for a custom entity? I have written a module that creates a custom Content Entity that has a number of fields including an entity_reference field with a "file" target type. The field_ui module adds location task tabs, alongside my entity settings page, for editing field properties (good!). However, clicking on the field_ui "Manage display" tab for my custom Entity settings crashes Drupal (and not in my code). Has anyone else seen this problem? What "file" plugin is it referring to? This happens in multiple versions of Drupal (8.0.6, 8.1.1, 8.1.7):

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

Drupal\Component\Plugin\Exception\PluginNotFoundException: The "file" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 57 of core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).
Drupal\Core\Plugin\DefaultPluginManager->getDefinition('file')
Drupal\Core\Field\FormatterPluginManager->createInstance('file', Array)
Drupal\Core\Plugin\DefaultLazyPluginCollection->initializePlugin('file')
Drupal\Component\Plugin\LazyPluginCollection->get('file')
Drupal\Component\Plugin\LazyPluginCollection->getIterator()
Drupal\Core\Plugin\DefaultLazyPluginCollection->getConfiguration()
Drupal\Core\Config\Entity\ConfigEntityBase->preSave(Object, 1)
Drupal\Core\Entity\EntityDisplayBase->preSave(Object)
Drupal\Core\Entity\EntityStorageBase->doPreSave(Object)
Drupal\Core\Entity\EntityStorageBase->save(Object)
Drupal\Core\Config\Entity\ConfigEntityStorage->save(Object)
Drupal\Core\Entity\Entity->save()
Drupal\Core\Config\Entity\ConfigEntityBase->save()
Drupal\field_ui\Form\EntityDisplayFormBase->buildFieldRow(Object, Array, Object)
Drupal\field_ui\Form\EntityViewDisplayEditForm->buildFieldRow(Object, Array, Object)
Drupal\field_ui\Form\EntityDisplayFormBase->form(Array, Object)
Drupal\Core\Entity\EntityForm->buildForm(Array, Object)
call_user_func_array(Array, Array)
Drupal\Core\Form\FormBuilder->retrieveForm('entity_view_display_edit_form', Object)
Drupal\Core\Form\FormBuilder->buildForm(Object, Object)
Drupal\Core\Controller\FormController->getContentResult(Object, Object)
call_user_func_array(Array, Array)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}()
call_user_func_array(Object, Array)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1)
Stack\StackedHttpKernel->handle(Object, 1, 1)
Drupal\Core\DrupalKernel->handle(Object)

I'm pretty sure your view display configuration there is invalid, there is no "file" formatter. There are many formatters for file fields but none is called just file, there is file_link, file_uri, file_default and many more, you have to pick the one you want.

Granted, the error handling there could be better. Feel free to open a core issue about that.


Is there any integration of the Entity registration module with modal forms? I'm using the Entity Registration module for events registration. I want to open the registration forms in the ctools modal.

I checked the Modal forms module. But on the module page, I can see that it can only work with login/reset password/user regisration/webform/contact/comment forms.

So there is any possibility to use these both modules? Or should I look for something else?

Few alternative way may helps you.

Entity popup module.

  This module allows you to show an entity in a popup. For flexibility,
  it doesn't provide any popup plugins itself, but it provides a menu
  callback that allows you to load the entity into any popup you desire.

NG Lightbox module:

  Lightbox any Drupal page such as the login page or comment reply.
      Works with forms out of the box, including webforms, node edit forms and more.
      Lightweight, only 1.2kbs in D7. D8 uses cores modal.
      Default responsive theme for the lightbox that can be customised.


When is it necessary to check_url()? When is it necessary to use check_url()? For instance, if I create a login link by putting the code below in the body of a block, which of the 3 check_url() calls are necesssary and which ones are not?

<?php print 'Login';
?>

If you just use l($text, $path, array $options = array()) you can simplify your code and it will take care of check_url for you.


How do I get the MIME type of a file basing on its content and not its extension? I want to get the exact MIME type basing on the file content, not its extension.
I have used PHP methods and the API exposed by a module, but they return the MIME type basing on the file extension.

How do I get the MIME type from the file content?

You can easily get the MIME type of a file using mime_content_type() function.
$mime_type = mime_content_type($path_to_the_file);

I've just tested it on my local machine; placed a test.pdf file in my home folder and renamed it giving it no and an incorrect extension. In both cases I got the right MIME type:

$ ls
test.pdf

$ drush eval 'var_dump(mime_content_type("/home/elin/test.pdf"))'
string(15) "application/pdf"

$ mv test.pdf test
$ drush eval 'var_dump(mime_content_type("/home/elin/test"))'
string(15) "application/pdf"

$ mv test test.jpg
$ drush eval 'var_dump(mime_content_type("/home/elin/test.jpg"))'
string(15) "application/pdf"

$ mv test.jpg test.png
$ drush eval 'var_dump(mime_content_type("/home/elin/test.png"))'
string(15) "application/pdf"


How to insert a custom search fields in a views page I have a view page showing some books and I want to have an advanced search with search criterias at the top of this page. The search box should search inside the books page or books content type.

On your view, all you simply need to do is add a filter criteria and expose it to the user. So you add a filter criteria of your content type, that you will not need to expose since thats the one you want to search on.

If you are searching on the title, you add a filter criteria, select content:title, it takes you to the next selection, select expose to visitors. You can also choose what operator to use and if need be, you can also expose the operator. See screenshot


How to modify the image output for just one content type? We are using a field_image field across multiple content types. For the basic content type (only) we want to lazy load the images as such it requires the following  format. How can this be done for just basic content type?

Current output:

Desired output:

You can do this by defining a "lazy load" image style and using it as the image display.  This style does not have to do any resizing.  It would just be a placeholder flag for a preprocess function like:

function my_theme_preprocess_image(&$variables) {
  if ( $variables['style_name'] == 'lazy_load') {
    $variables['attributes']['data-src'] = $variables['attributes']['src'];
    unset($variables['attributes']['src']);
  }
}

Nice thing is that you can use this style anywhere to get lazy loading images.


View with url aliases I am writing a view that lists all content of a specific type. I would like to, additionally, be able to set paths to content made by a specific user. For example drupal.dd/content will give all content. Then drupal.dd/%/content will show only the content by a specific user where % is the user's name. The issue I have come across is, when I create the path with /%/content it says the first segment of the path cannot be %. I am using a contextual filter to filter by author. How would I go about doing so. I am using Drupal 8.

You should already have a path for this at drupal.dd/content/[author] based on how you have setup the contextual filter. If you are using a contextual filter, they will get appended to the path of the view, and it sounds like your view has a path of "/content".


Ajax add command to open a new URL in a custom module, I created a custom form. On this form, I have an ajax button to open a specific file (.pdf).

Here is my code in a custom submit function :

  $url = 'myfileUrl';
  $response = new AjaxResponse();
  $command = new RedirectCommand($url);
  $response->addCommand($command);

It's ok and the file is opened when I click on the button. But, the page is closed to open the file. How can I specify an attribute "target" to open the file in a new window? If not possible, is there another ajax command to open an external URL?

Thanks.

I found a solution to resolve my problem.
After having readed several posts, i have decided to create a custom Ajax Command to open my files (pdf/csv).

Create a custom command - link

In my custom module, I have built the required files for this and call in my CallBack function this new ajax command ('OpenFileCommand') :

    $ajax_response = new AjaxResponse();
    $command = new OpenFileCommand($file_url);
    $ajax_response->addCommand($command);

Here is the simple code for this command:

use Drupal\Core\Ajax\CommandInterface;

/**
 * Class OpenFileCommand.
 */
class OpenFileCommand implements CommandInterface {

  // Create a new property.
  protected $file_url;

  // Construct the File Url property.
  public function __construct($file_url) {
    $this->file_url = $file_url;
  }

  /**
  * Render custom ajax command.
  *
  * @return ajax command function
  */
  public function render() {
    return [
      'command' => 'OpenFileCommand',
      'file_url' => $this->file_url
    ];
  }

}

Now, I can open a file when I click on a ajax button.

Thanks for all for your help. This solution can help someone...


Prevent "Fit to Window" setting I have the following image and when I click on  it. it will pop out into a colorbox modal, but it currently re-sizes it to fit to the window. How would I just resize it up to only the width of the window and have the user scroll down to see the rest of the image?

I'm using the colorbox module. I know I have to unset the innerHeight to auto or something. But how would you override a javascript snippet without affecting other pages on the site?

You can try with below Jquery snippet.

(function ($) {
var cboxOptions = {
     width: '95%',
     height: '95%',
     maxWidth: '768px',
     maxHeight: '768px',
}

$('#colorbox').colorbox(cboxOptions);

$(window).resize(function(){
   $.colorbox.resize({
     width: window.innerWidth > parseInt(cboxOptions.maxWidth) ? cboxOptions.maxWidth : cboxOptions.width,
         height: window.innerHeight > parseInt(cboxOptions.maxHeight) ? cboxOptions.maxHeight : cboxOptions.height
   });
});


How can I make search with a substring of a word? I would like to search with only part of a word,not the whole word.For example when I search name of people,I would like to search only the first 3 letters of the Last Name,not the whole name.Now if I put on  search only the first 3 letters I take no results.For the moment I am using the search api with apache  solr(and perhaps views).Any suggestions please?

Add ngramfilter to text type definition in schema.xml in solr config directory.

<fieldType name="text" class="solr.TextField" positionIncrementGap="100">
  <analyzer type="index">
    <filter class="solr.EdgeNGramFilterFactory" minGramSize="3" maxGramSize="25" />


Have a child node inherit taxonomy from a parent during /node/add? In Drupal 7, I have two content types:

Parent Events with tags (like "outdoors" or "popular" or "suitable for kids"). "Tags" are taxonomy terms in a vocabulary, connected via an Entity Reference field field_parent_tags (using the Checkboxes widget).

Child Events with the same tags & reference in field_child_tags. Each Child also has a mandatory Entity Reference to a Parent Event, field_parent_event (using the Autocomplete widget).

I'm trying to have new Child Events automatically inherit their parent's tags when they're first created. For example:

There is a Parent Event called "Weddings", which has the tags "suitable for kids" and "popular".
When I make a new Child Event called "Joe & Sarah's Beach Wedding", I'd like it to automatically inherit the tags "suitable for kids" and "popular". Then I'd add the "outdoors" tag to this specific child event, which would apply only to this child and not the parent.
(Another child event might be someone else's wedding, and not suitable for kids, so I'd uncheck that in the child event).

How would I go about doing that? So far, I think I need to implement some variation of hook_form_alter(), possibly overriding its #ajax call so that as soon as the child event's form_parent_event is filled out, its field_child_tags will copy the values from field_parent_tags.
Am I going down the right path? I can't figure out where to put that code, if so. I tried overriding /node/add/childevent using a page--node--add-child-event.tpl.php file, but it seems to have no effect. A little lost :(
Any help would be very much appreciated. Thank you!

I ended up using the Rules module for this. It couldn't do it in AJAX when the parent field was specified, but it could make this happen as soon as the child was first saved, and only if its taxonomies were left blank.

The main rule fires a Ruleset component when a child event is saved, and if the parent event is specified. This Ruleset has two parameters: 1) the parent node and 2) the child node.

Next, the Ruleset component just fires two child rules one after another, one for each set of taxonomy terms:

Finally, each individual child rule checks to see if the child event left its taxonomy blank, and if so, sets it to the parent's. I needed one child rule per taxonomy, so that the empty conditions could be checked individually.

That's it! New child events, upon saving, would get the parent tags if it had none of its own.
The code for the rule:
{ "rules_inherit_parent_event_taxonomies" : {
    "LABEL" : "Inherit Parent Event Taxonomies",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--event" : { "bundle" : "event" } },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "event" : "event" } } } },
      { "NOT data_is_empty" : { "data" : [ "node:field-program" ] } }
    ],
    "DO" : [
      { "component_rules_set_child_taxonomies" : { "parent_node" : [ "node:field-program" ], "child_node" : [ "node" ] } }
    ]
  }
}

And the ruleset component:
{ "rules_set_child_taxonomies" : {
    "LABEL" : "Set Child Taxonomies",
    "PLUGIN" : "rule set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "parent_node" : { "label" : "Parent Node", "type" : "node" },
      "child_node" : { "label" : "Child Node", "type" : "node" }
    },
    "RULES" : [
      { "RULE" : {
          "IF" : [
            { "node_is_of_type" : {
                "node" : [ "parent-node" ],
                "type" : { "value" : { "program" : "program" } }
              }
            },
            { "node_is_of_type" : {
                "node" : [ "child-node" ],
                "type" : { "value" : { "event" : "event" } }
              }
            },
            { "data_is_empty" : { "data" : [ "child-node:field-topic" ] } }
          ],
          "DO" : [
            { "data_set" : {
                "data" : [ "child-node:field-topic" ],
                "value" : [ "parent-node:field-topic" ]
              }
            }
          ],
          "LABEL" : "Inherit parent\u0027s topics if child has none"
        }
      },
      { "RULE" : {
          "IF" : [
            { "node_is_of_type" : {
                "node" : [ "parent-node" ],
                "type" : { "value" : { "program" : "program" } }
              }
            },
            { "node_is_of_type" : {
                "node" : [ "child-node" ],
                "type" : { "value" : { "event" : "event" } }
              }
            },
            { "data_is_empty" : { "data" : [ "child-node:field-audience" ] } }
          ],
          "DO" : [
            { "data_set" : {
                "data" : [ "child-node:field-audience" ],
                "value" : [ "parent-node:field-audience" ]
              }
            }
          ],
          "LABEL" : "Inherit parent\u0027s audiences if child has none"
        }
      }
    ]
  }
}


How can I exclude API keys, passwords, and so on from configuration management? I am using Drupal 8 and drush cex to commit my configuration to my repository.

However, I want to keep passwords and API keys out of the repository.  How do I do that? (selectively exclude sensitive information from configuration management).

For example, I'm using the SMTP module, but I noticed that in addition to the SMTP server and sender's name, etc., it also exports the API key to code, which should not be exposed.  I want to manage module configuration with configuration management, but I don't want to commit the key.

You can't exclude specific keys easily from being exported.

However, you simply can not store the real keys there in the first place, and rely on local overrides through settings.php only, e.g.

$config['yourmodule.settings']['smtp']['api_key'] = '24ztsgfet';

And in the UI, you just store "dummy" or any other string. Note that there's currently no indication that a value is overridden in the backend, it will however display only the value that's actually stored in config, not overrides.


Omega footer navigation I'm making a footer menu. The base-theme I use is Omega. Now I'm looking for the best way to add a CSS value to each menu-item, so Omega places them next to eachother.

Basicaly, what I would like to do is adding "grid-3" to the parent menu items...
In the example you can see class="nolink" (from the module special_menu_items), I also want to add the class "grid-3".

Web Design

Drupal Design

Graphic Design

Logo Design

SEO Services

Google Adwords

Great Keywords

Link Submission

SEO Link Building

You have to use hook_menu_link_HOOK

For example if your menu is the main menu you could use this example code in your template.php to add class to tag li.

function YOUTHEME_menu_link__main_menu(array $variables) {

  $element = $variables['element'];
  $sub_menu = '';
  /* add classes to balise li */
  $element['#attributes']['class'][] = 'grid-3';
  /*$element['#attributes']['class'][] = 'depth-' . $element['#original_link']['depth'];*/
  $element['#attributes']['class'][] = 'menu-' . $element['#original_link']['mlid'];

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  $title = $element['#title'];

  $element['#localized_options']['attributes']['id'] = $title ;

  $output = l($lien, $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . "</li>\n";

}

To add the class only to the parent menu, you should use a condition to see if the menu item has children. Or make a condition to see if the tag li has the class depth-1 and then add the class grid-3.

The module Menu attributes seems to do the job too.


how to send variable from .php file to .js file? I hope someone is able to help me.
The problem is the following one:
1)I have module in which a assign the variable in order to send to the template file php.tpl

<?php
...
$testvar="Hello from alex!";
$variables['testvar'] = $testvar;
...
?>

This variable can be shown in the php.tpl file like

<?php print $testvar?>

2)I have separated .js file
How can i get access to this varuiable inside .js file?

I know how it'll be if .js file is inside .php.tpl:

<?php
$testvar="Hello from alex!";
?>
<script type="text/javascript">
var myVar = '<?php print $testvar?>';
</script>

The problem is how to do the same if these two files .js and .php.tpl are separated?

You should use drupal_add_js() in your module, there is no need to output the variable in your .tpl.php:

drupal_add_js(array('YOURMODULE' => array('testvar' => $testvar)), array('type' => 'setting'));

And in your JavaScript, you can the access the value in Drupal.settings.YOURMODULE.testvar:

alert(Drupal.settings.YOURMODULE.testvar);

Direct usage of global variables (as suggested in your code sample) is a discouraged practice in JavaScript as it clutter the global namespace. Also, if your code is triggered on page load, check the "Behaviors" section in Managing JavaScript in Drupal 7 documention (the whole page is worth reading).


Possible to save form "field by field" as soon as a user changes a field instead of pushing a save button at the end of the form? Instead of pushing a save button, I would like to save user input as sooon as a field is changed. Similar to how mobile apps works. Is this possible in Drupal?

There is the Autosave module for node edit forms for exactly this use case.


"focusout" jQuery event I am using Drupal 6 and, therefore, jQuery 1.2.6.

When a user clicks inside my text, there is a pop-up that comes up with a few more options in it. I would like this pop up to disappear when the focus is moved to anywhere outside.   This answer on SO comes very close but the focusout event isn't available to me in jQuery 1.2.6.

Has anyone else encountered this issue? How did you work around it?
I would rather not use the jquery update module, as I don't own the site and don't want to be responsible if the update breaks something else.

Add a .mouseleave() event to the popup div

Taking the example code from the SO question you mentioned, see the working version at http://jsfiddle.net/Laxman13/Mw8VD/6/


How can a div at the top of the page coexist with Adminstration Menu? I want to place the Page execution times at the top of the page. I first tried it in a block as mentioned in this question, but the code for the block executes before the page is fully rendered, resulting in the wrong time.

Devel places the Page execution time is place in a div class .dev-query and I tried placing it at the top of the page.

The problem is it gets obscured by Admin menu and after reading a few solutions such as this one on stackoverflow 1 and stackoverflow 2 and I wonder if someone has been there and done that in relation with Admin menu

One way of doing that with the CSS is as below:

.dev-query {
    position: fixed;
    top: 33px;
    width: 100%;
    left: 30px;
    color: #000;
    z-index: 100;
}

I have tried that and it seems to be working for me.

Another way of doing this with the JS I have mentioned here is somewhat like below:


What do the js-text-full and text-full in the StringTextAreaWidget class do? I am planning to create a field type to use as hidden captcha: a field that is hidden to users using a browser with enabled CSS, used to verify if the user registration is not done by a human being. I though to derive its widget from the StringTextAreaWidget class, but I noticed that StringTextareaWidget::formElement() uses two CSS classes: js-text-full and text-full.

What do those CSS classes do?

I would like the widget to be very similar to the textarea used to enter a long string, except that a CSS class I add would make it invisible. I would not want that the existing CSS classes would interfere in some way.

Alternatively, is there another class I should use? I see there is a TextareaWidget class, but it seems for text with an input format associated, while I would need just plain text, without any input format associated.

These are classes that Drupal sets for its own css and js. For javascript it is always with the prefix "js". At first sight this seems to be redundant. The reason is, if someone wants to override the css class, it doesn't effect the js behavior and vice versa.

If you want to address the field through your own css, you can always target the field name "edit-mytextfield". If you use a class with the name of a text format, there is a chance, that you target other fields you don't want.


How to attach a field to an entity programmatically? Is it possible to attach a field to an entity programmatically?

I want to create a new entity, say vehicle, which has radio buttons defined for the brand of the vehicle. I would like this field to not be able to be deleted or modified via the UI.

Yes, it is possible, the function is field_create_instance().
If the field was not created before, you will need to create it with field_create_field() first.


Updates break jquery modules I could need some help! (Newbie)
After updating a couple of modules on my local site, the jquery modules are behaving really weird or stopped working at all (Masonry, Chosen and Sidr). Masonry and Chosen don't work at all, Sidr just works on those pages where Masonry isn't on. Infinite Scroll stopped working, too and is replaced by the regular pagination. There are no error messages displayed or in the drupal report.
What should I do now?
(the site is running Drupal 7.28 on Acquia Dev Desktop php 5.2.38)

Caches may be stale. Clear and re-test. Even disable your JS aggregation/minify, then have Drupal regenerate the aggregated JS (after testing with it off to see if that fixed the issue).
If you also use the jquery_update module, you may need to update your jQuery library.
Sometimes replacing the modules with their DEV versions help fix the issue, because sometimes there's small bugs that get fixed in DEV first before a new stable update is tagged and released.


Usage of i18n and multi-site? I beg you to make it clear for me, can i share tables in multisite installation with different databases and which ones?

If i am to use i18n on multisite, what is the best way to do that. Thanks a lot in advance.

As i understood you almost cant use common tables on multi-site installation - i`ve been checking them one by one. First i configured all of sites - only the main site (from which tables were shared) could switch languages and translate nodes. On the others there were no switcher showing and translated nodes were not linking.

Maybe you can some, but still you got to have everything identical (starting from content types and endind with nodes)

Maybe i am wrong.


I am trying to pull ldap server information from the ldap_servers table in drupal I have a user search module in drupal that creates contact cards base on LDAP user information.  Everything works fine, I just need to make it more flexible, so that if the same module is used in a different drupal install, it can just set the same ldap server that is set in drupal.  Currently it is hard-coded.

first, I tried using this to get the server info:

  $ldapServer = db_query("SELECT address FROM ldap_servers WHERE `binddn` = 'cn=Directory Manager'");
  print_r( $ldapServer);

This is what the query returned:

  DatabaseStatementBase Object ( [dbh] => DatabaseConnection_mysql
  Object ( [needsCleanup:protected] => [target:protected] => default
  [key:protected] => default [logger:protected] =>
  [transactionLayers:protected] => Array ( ) [driverClasses:protected]
  => Array ( [MergeQuery] => MergeQuery [SelectQuery] => SelectQuery [UpdateQuery] => UpdateQuery [InsertQuery] => InsertQuery_mysql )
  [statementClass:protected] => DatabaseStatementBase
  [transactionSupport:protected] => 1
  [transactionalDDLSupport:protected] => [temporaryNameIndex:protected]
  => 0 [connectionOptions:protected] => Array ( [database] => tlsconnectapp [username] => drupal [password] => drupal [host] =>
  localhost [port] => [driver] => mysql [prefix] => Array ( [default] =>
  ) ) [schema:protected] => [prefixes:protected] => Array ( [default] =>
  ) [prefixSearch:protected] => Array ( [0] => { [1] => } )
  [prefixReplace:protected] => Array ( [0] => [1] => ) ) [queryString]
  => SELECT address FROM ldap_servers WHERE binddn = 'cn=Directory Manager' )

I'm sure I did something wrong, but I'm not sure what this means, and the server isn't in there.

Please read on Working with Result Sets documentation. You have not issued the query yet to your database, you've only built a SELECT statement.

I also recommend installing the Devel module as you can get much more readable debug information from dpq() for queries or dpm() for Objects you want to inspect.


Aquia Desktop - How to import a MySql database that is too big I am using Aquia Dev Desktop. I have a MySql database dump that is too big to upload into Aquia Dev Desktop. What are my options? I am using a Mac, so would appreciate Mac based options

Steps I have tried:

I think the problem is the cache table. If I could empty (not delete) this table, I should be able to upload it into Acquia Dev Desktop.

1) Downloading MySQLWork Bench to delete the cache table.
MySQl Work Bench has a Data Import option. However, it requires the password of the Acquia Dev Desktop, which I don't have.

2) Downloading Sequel-Pro to delete the cache table
Again this requires the username/password of the database.

configure Mysql my.ini

change the value of myisam_sort_buffer_size from 8M to whatever your sql size is.

I will say if your file size is 100 change the value to myisam_sort_buffer_size = 156M.

Restart your mysql.
using terminal navigate to mysql bin directory
run the command: mysql -u username -p yourdatabasename <yourmysqldatabasefile

enter the password for the user, if there is no password the user than just press enter.


How can i create theme's block width should be configured from dynamically I want to develop a drupal theme, where

  The theme should be develop in a way that the number of the columns of
  the theme and the width of the columns can be configured from the
  Admin area.

Can anyone guide me how to approach in theme development ?

You could use a theme thats already done this...

http://drupal.org/project/adaptivetheme

http://drupal.org/project/omega/


How to redirect to frontpage from a controller Right now I'm doing this ugly thing to get the url of the my set frontpage (skipping validations and making sure it exists since I'm not sure if I'll even use this approach)

$url = $this->config('system.site')->get('page')['front'];
return new RedirectResponse($url);

This works but seems ugly, bloated and wrong.

Update:

As pointed out in the comments, this may be a matter of personal taste, therefore the question would be deemed subjective and it can be closed. It surely isn't a duplicate, I'm not asking how to redirect in general, it's a specific redirection, perhaps I could've worded it differently.

Use the route <front> and when you are in a controller use the injected method redirect():

return $this->redirect('<front>');


How to add tracking scripts from external sites? We want to use several lead tracking snippets of code on various pages.

<script type="text/javascript">llfrmid=123456</script>
<script type="text/javascript" src="https://formalyzer.com/formalyze_init.js"></script>
<script type="text/javascript" src="https://formalyzer.com/formalyze_call_secure.js"></script>

...I can use drupal_add_js() but it seems to want to wrap the first line in --CDATA-- and I'm unclear if that makes a difference.

I came across this post: How to add script to <head>?. Is that accepted answer still recommended for D7? ie. just concatenating text to the header with drupal_get_html_head() Or is there a way to use drupal_add_js so it does not wrap the text in --CDATA--?

TIA

You can add the JavaScript on the theme level. You added on template.php or any other template that you wish to appear the javascript.

An example is a little bit tricky because is all depend on how the theme is was created. But I can provide an example base on my theme.

I'm using a sub-theme base on Boostrap so on my page.tpl.php I would add the JS on the bottom. So your goal would be to find the footer region and add the JS below that.

<?php

?>
<header id="navbar" role="banner" class="<?php print $navbar_classes; ?>">

      <?php if ($logo): ?>
      <a class="logo navbar-btn pull-left" href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>">
        <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

      <?php endif; ?>

      <?php if (!empty($site_name)): ?>
      <a class="name navbar-brand" href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>"><?php print $site_name; ?>
      <?php endif; ?>

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        Toggle navigation

      </button>

    <?php if (!empty($primary_nav) || !empty($secondary_nav) || !empty($page['navigation'])): ?>

          <?php if (!empty($primary_nav)): ?>
            <?php print render($primary_nav); ?>
          <?php endif; ?>
          <?php if (!empty($secondary_nav)): ?>
            <?php print render($secondary_nav); ?>
          <?php endif; ?>
          <?php if (!empty($page['navigation'])): ?>
            <?php print render($page['navigation']); ?>
          <?php endif; ?>

    <?php endif; ?>

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

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

<?php endif; ?>

    <?php if (!empty($site_slogan)): ?>

<?php print $site_slogan; ?>

    <?php endif; ?>

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

    <?php if (!empty($page['sidebar_first'])): ?>

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

    <?php endif; ?>

    <section<?php print $content_column_class; ?>>
      <?php if (!empty($page['highlighted'])): ?>

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

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

      <?php print render($title_prefix); ?>
      <?php if (!empty($title)): ?>

<?php print $title; ?>

      <?php endif; ?>
      <?php print render($title_suffix); ?>
      <?php print $messages; ?>
      <?php if (!empty($tabs)): ?>
        <?php print render($tabs); ?>
      <?php endif; ?>
      <?php if (!empty($page['help'])): ?>
        <?php print render($page['help']); ?>
      <?php endif; ?>
      <?php if (!empty($action_links)): ?>

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

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

    <?php if (!empty($page['sidebar_second'])): ?>

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

    <?php endif; ?>

  <?php print render($page['footer']); ?>
    /**
        Load Custom JS
    **/


How to find the values that have changed in a form submission? How can I tell what values have changed in a validate hook of a form submission?

What I have done is to see if the value in $form_state['values'] is different from the #default_value in $form, like so:

if ( $form_state['values']['variable'] <> $form['variable']['#default_value'] ) { ... }


in views, how to get the replacement pattern of the URL of the link field using the Link module, i have created a view of content fields:

Link
Title
Body

And i want the Title to be a clickable link to the URL of the Link field.
In D7 the links field provided for a replacement pattern for the URL as raw value but in D8 that is not available.
How can I make the Title field a clickable link with the Link URL?

The raw replacement pattern isn't available, but you can customize a new hidden field to be the replacement equivalent:

Add a new link field

Check the Exclude from display, URL only, Show URL as plain text options to have your field be available.

Add a new title field

Uncheck Link to the Content
Use {{ title }} in the rewrite options to render title field with a link to your link field URL


What do blocked IP addresses see? I have been getting a lot of failed attacks targeting my server in the last few months. I have been using the Drupal IP block to block IPs that where sniffing for vulnerabilities. I would like to know if this is only for drupal or is it adding it to the OS as well. Also once I block an IP address what do the attackers see? Do they get a 404? Do they get a banned message? or nothing at all? If this is not also adding to the server OS IP block is there a module that will?

They see a blank 403 page with this message specifying that their IP address has been banned:

The block is done at the application level. Drupal inserts a record into the blocked_ips table which is referenced upon bootstrapping; if a match is found the above page is shown.

I've not heard a module that does this at the OS level. Considering the variety of environments it would have to accommodate, and the potential harm of giving an application OS-level blocking (e.g. Drupal blocking you could lock you out of your own server), it's likely it doesn't exist.


How to programmatically change settings of input filters and activate them? I'm looking for a way to programmatically change the settings of an input filter and activate it in Drupal 7. Let's take the Footnotes module as an example: It adds a new input filter that can be activated on input formats. I can navigate to admin/config/content/formats/2 to edit my "Full HTML" input format and there activate the Footnote filter and configure it. But how can I achieve that programmatically?

My first guess was to load the input format using filter_format_load(), change some values and then do a filter_format_save(). But in the object that I get from filter_format_load(), there are no input filters, i.e. $format->filters doesn't exist.

I can get all available filters using filter_list_format() and I believe I could change some values there. But then again, I can't find a way to save those settings.

If you read the API page for the functions you mentioned in your question, you can easily see that there is a bug(or a feature) that it does not load populate $filter->filters indeed.

For a workaround, you could do something like this, with the help of filter_list_format()

$format_id = 'full_html';
$filter_id = 'your_filter';

First, load the format object

$format = filter_format_load($format_id);

Now, since we do not have the $filter->filters populated, we do so by loading the currently enabled filters.

$filters = filter_list_format($format_id);
foreach ($filters as $filter_id => $filter_opts) { //Convert to an array, which is expected by the save function.
  $filters[$filter_id] = (array) $filter_opts;
}

You can now make changes in the filter that you are interested in.

$filters[$filter_id]['status'] = TRUE; //Enable.
$filters[$filter_id]['settings']['something'] = 'foobar';

Inject filters to the format we have already loaded.

$format->filters = $filters;

Save!!

filter_format_save($format);


How to add as exposed filter a product attribute in Commerce's orders view? I have a drupal 8 commerce website.
The Orders page is a view that comes with commerce where all the orders are listed.
Is it possible to add/create ( on the website or programatically ) an exposed filter based on a PRODUCT ATTRIBUTE to show all the orders containing a value of that product attribute?

For example: for a product attribute called ORIGIN, I would like an exposed filter in the orders view that would allow me to choose between 2 values: Los Angeles or San Francisco.

Some orders will show up in both because they will have different products with different ORIGIN value product attributes.

I tried to modify the orders view but I couldnt find any product attributes nor a relationship to products. I tried to add a relationship to order item but that didn't help expose any of the product attribute fields.

Product's attributes are set through the product variation. You need to add the Variations through a relationship and you will have attributes available there.

After that your attributes can be added as exposed filters.

Sorry I don´t have any English sites available but pay close attention to captures.


Alter Views arguments from URL I'd like to alter Views arguments which is currently Term name. Is there any way to use term name slug instead of complete Term name and use this slug as views argument? If not what hook should I use to convert these parameters from URL (as taxonomy term slug) to full name Taxonomy term which can be used as views argument. I tried to use hook_views_query_alter and hook_views_pre_view, but it's too late for any changes.

It is a build in function in drupal views. When you add a contextual filter there would a section called more. You can put the case to lower case and check "Transform spaces to dashes in URL"


Where do I import a panels variant? In the Panels UI, when you are editing a variant, you have the option to Export the variant, and the tooltip says "Export the variant into code to import into another page."

This is exactly what I would like to do, but where do I paste the code to import it?  When I choose Add variant, I don't see an option to import, and I don't see an import option in the Page Manager UI (admin/structure/pages) either.

If you are not the super admin (user id = 1) on your drupal site.

You need to give the permission for "Use CTools importer" to be able to import a variant.


After PHP upgrade Drush Fails After ugrading PHP 5.3 to 5.4.10, drush fails with the following error for most of commands:
Command watchdog-show needs a higher bootstrap level to run - you will need to invoke drush from a more         [error]
functional Drupal environment to run this command
...

I reinstalled Drush(Drush 5.8 does not work on  Mac OSx 10.7.5, so downgraded to 5.0.0), but it did not solve the problem.

Is Drush compatible with php 5.4.10.? Why would i get these errors and how to troubleshoot?

Thank You

As mentioned here drush is not yet completely compatible with PHP 5.4

And regarding the error message you will need to invoke drush from a more [error] functional Drupal environment to run this command , in general cases it means that you are running drush from a location which is not associate to a drupal instance. To be on a safer side go location-of-your-drupal-instance/sites/all/modules and run the command.


Help with function in template.php Drupal 7.

Can anyone spot what could be wrong with this function?  I'm just trying to pull a taxonomy term or its parent.  The taxonomy is called "pubissue."

In template.php:

 function ain_core_getpubname() {

// Load the node from unaliased url
if ((arg(0) == 'node') && is_numeric(arg(1))) {
$node = node_load(arg(1));}

// first find out if it's level two or not
$query = "SELECT t1.tid, t1.parent FROM taxonomy_term_hierarchy t1 JOIN field_revision_field_pubissue t2 ON t1.tid = t2.field_pubissue_tid WHERE t2.entity_id = ".$node->nid;

    $result = mysql_query($query);
    print_r(mysql_fetch_assoc($result));

        $mytid = $row["tid"];
        $myparent = $row["parent"];

    if ($myparent == 0) {

        // No parent, top level
        $query = "SELECT t1.name FROM taxonomy_term_data t1 WHERE tid = ".$mytid;

        $result = mysql_query($query);
        $row = mysql_fetch_assoc($result);
            $pubname = $row["name"];
    }

    else {

        $query = "SELECT t1.name FROM taxonomy_term_data t1 WHERE tid = ".$myparent;

        $result = mysql_query($query);
        $row = mysql_fetch_assoc($result);
            $pubname = $row["name"];

        }

print $pubname;

}

Then in my node.tpl.php file:

    <div class="<?php print $node->type; ?>-pubname"><?php ain_core_getpubname() ?>

OK, so going with the suggestion below:

function ain_core_getpubname() {

// Load the node from unaliased url
if ((arg(0) == 'node') && is_numeric(arg(1))) {
$node = node_load(arg(1));}

// first find out if it's level two or not
$query = "SELECT t1.tid, t1.parent FROM taxonomy_term_hierarchy t1 JOIN field_revision_field_pubissue t2 ON t1.tid = t2.field_pubissue_tid WHERE t2.entity_id = ".$node->nid;

    $result = db_query($query);
    $row = db_fetch_array($result);

        $mytid = $row->tid;
        $myparent = $row->parent;

    if ($myparent == 0) {

        // No parent, top level
        $pubname = db_query("SELECT t1.name FROM taxonomy_term_data t1 WHERE tid = ".$mytid)->fetchField();
    }

    else {

        $pubname = db_query("SELECT t1.name FROM taxonomy_term_data t1 WHERE tid = ".$myparent)->fetchField();

        }

print $pubname;

Still not working.  Will continue to troubleshoot, I think I am on the right track.  Thanks again.

Your queries should look something like this:

$query = "SELECT t1.tid, t1.parent FROM {taxonomy_term_hierarchy} t1 JOIN {field_revision_field_pubissue} t2 ON t1.tid = t2.field_pubissue_tid WHERE t2.entity_id = :nid";
$result = db_query($query,array(':nid' => $node->nid));
// Result is returned as a iterable object that returns a stdClass object on each iteration (@see http://api.drupal.org/api/drupal/includes--database--database.inc/function/db_query/7#comment-7019)

After all I would suggest you check out the drupal taxonomy api. Using something like taxonomy_get_tree() could be much better.

EDIT:

Using the taxonomy api I would say what you want to do would be something like:

$parents = taxonomy_get_parents($tid);
if(!empty($parents)) {
    // use whatever you need from your $parents
}
else {
    $term = taxonomy_term_load($tid);
    // use whatever you need from the term (No parent, top level)
}

EDIT 2: fixed code example...


How to update a Drupal 6 website to latest release with drush? I want to update my Drupal 6 website (version 6.36) to the latest realease (6.38).

When i'm using the shell-command "drush update drupal", i'm getting following result:

Drupal                     6.35      6.35      Installed version not supported

How can i do an update to the latest release with drush?

As near as I can tell, drupal.org just removed all of the release xml for all contrib modules, and every version of Drupal 6.x core except for the latest release.

See the Drupal 6.x release xml for reference; all versions except 6.38 have been removed. Ah, look, the Views 6.x release xml contains content again!  Just a short while ago, it was gone.

Without the full release XML for Drupal 6 core, Drush cannot your existing versions; if it has no information about the current release, it gives up.  It is possible that this situation was accidental, and is being updated (c.f. the views release XML, which was recently restored).  Maybe this will start working again later.


How do I alter the login form? I have used custom_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id); I get the form ID of other forms, but I don't get the login form $form_id inside the hook.

Try clearing cache and then visiting login page again, that should show Form ID. It will be hidden again when you refresh login page.

use \Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function [MODULE_NAME]_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  echo $form_id;
  switch ($form_id) {
    case 'user_login_form':
      // Do your code here to alter login form.
      break;
  }
}


Add country, state dropdown to user registrtaion i am creating a user registration form. In this i want to add fields for country, state, area and the fields are dependent on each other i.e. state depends on country and area depends on state. Is there any module in drupal or any way to integrate it with user registration form.

I think you can achieve that by using the Conditional Fields module

  Define dependencies between fields based on their states and values.

check out  A Drupal Dropdown List of Countries, States, Cities for more info


How to redirect an anonymous user to the login form after a 403 error? I want to redirect an anonymous user to the login form if such user encounters a 403 error.

I have created event subscriber and this is my code, but I end up on loop on the current page.

/**
   * Redirect anonymous user to login page if he encounters 404 or 403
   * response.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $response
   *   The created response object that will be returned.
   * @param string $event
   *   The string representation of the event.
   * @param \Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher $event_dispatcher
   *   Event dispatcher that lazily loads listeners and subscribers from the dependency injection
   *   container.
   */
  public function checkLoginNeeded(GetResponseEvent $response, $event, ContainerAwareEventDispatcher $event_dispatcher) {
    $routeMatch = RouteMatch::createFromRequest($response->getRequest());
    $route_name = $routeMatch->getRouteName();
    $is_anonymous = \Drupal::currentUser()->isAnonymous();
    $is_not_login = $route_name != 'user.login';

    if ($is_anonymous && $route_name == 'system.403' && $is_not_login) {
      $query = $response->getRequest()->query->all();
//      $query['destination'] = $routeMatch->getRouteObject()->getPath();
      $query['destination'] = \Drupal::url('<current>');
      $login_uri = \Drupal::url('user.login', [], ['query' => $query]);
      $returnResponse = new RedirectResponse($login_uri, Response::HTTP_FOUND);
      $response->setResponse($returnResponse);
    }
  }

I think this is related to the fact that the response already contains destination(current uri) and system.404 and system.403 have some high priority that prevent me to override this.

I've seen that this question was never answered how to do this programmatically. The code actually does work, when placed in an Exception Subscriber:

/src/EventSubscriber/RedirectOn403Subscriber.php:

<?php

namespace Drupal\mymodule\EventSubscriber;

use Drupal\Core\EventSubscriber\HttpExceptionSubscriberBase;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;

class RedirectOn403Subscriber extends HttpExceptionSubscriberBase {

  protected $currentUser;

  public function __construct(AccountInterface $current_user) {
    $this->currentUser = $current_user;
  }

  protected function getHandledFormats() {
    return ['html'];
  }

  public function on403(GetResponseForExceptionEvent $event) {
    $request = $event->getRequest();
    $is_anonymous = $this->currentUser->isAnonymous();
    $route_name = $request->attributes->get('_route');
    $is_not_login = $route_name != 'user.login';
    if ($is_anonymous && $is_not_login) {
      $query = $request->query->all();
      $query['destination'] = Url::fromRoute('<current>')->toString();
      $login_uri = Url::fromRoute('user.login', [], ['query' => $query])->toString();
      $returnResponse = new RedirectResponse($login_uri);
      $event->setResponse($returnResponse);
    }
  }

}

mymodule.services.yml:

services:
  mymodule.exception403.subscriber:
    class: Drupal\mymodule\EventSubscriber\RedirectOn403Subscriber
    tags:
      - { name: event_subscriber }
    arguments: ['@current_user']


generate multiple custom blocks from a single api call I have created a custom module that generates a single custom block based on content retrieved from a remote API. The content is currently displayed in a single contiguous block above the main content.

It works great, however, I am now being asked to split up the custom block content on the page. Essentially, I need to move some of the content into a sidebar and some into a smaller block at the top of the page.

The simple way to do this I guess is to create 2-3 custom blocks through the plugin system and then place them in the desired regions I create on the page templates. The problem with this is that each block would be calling out to the remote api so I would go from a single API call to 3 or even more on the same page. The remote API we are using just returns the entire set of content so I would be loading the same thing 3 or more times.

What I would really like to be able to do is keep my existing block class (in whatever form) and pass that same single API call to 3 seperate templates that can be placed as three separate blocks.

How do I do this?

Alternatively, is is there some way to generate the API call through a function in the .theme file in my theme (abandoning my custom module completely) and then just pass the variables directly to the page rather than going through the block system? I could also live with that though i am not sure how to do it.

What I would really like to be able to do is keep my existing block
  class (in whatever form) and pass that same single API call to 3
  seperate templates that can be placed as three separate blocks. How do
  I do this?

This is possible. Add a configuration option to the block class in blockForm() and then use this option in build() to change the content and template. Then place the block three times and choose for each instance a different option. To avoid calling the remote API three times in one request use drupal_static().

  Alternatively, is is there some way to generate the API call through a
  function in the .theme file in my theme (abandoning my custom module
  completely) and then just pass the variables directly to the page
  rather than going through the block system?

This is no problem. You can put three variables in mytheme_preprocess_page() and use them directly in page.html.twig.

Think about caching. You can cache the remote API call with \Drupal::cache('data')->set() with a certain expire time. In a block this is not necessary, you can set a cache max-age and as long the block stays in the cache the remote API is not called.


How to enable highlighted search functionality? I want to enable search functionality such that:

I have one word say "school" in my website and if I put "sc" word in search box, then search result should give "school" word with "sc" word highlighted.
I have one word say "school" in my website and if I put "oo" word in search box, then search result should give "school" word with "oo" word highlighted.

How can I solve this problem?

You can use the Highlight module:

  Highlight the keywords from referrer search engine
  Highlight the keywords from local search

If you need more information you can read this posts:

Highlight searched keyword using exposed filter views?
Add Keyword Highlighting using Search API in Drupal 7


Drupal commerce user based percentage discount I need to have different order total discount rates in % for each customers. The default discount is 10% for all users and it need to be override for certain users too. i.e administrator can set the different discounts such as 12% for user1 and 15% discount for user2 etc on a specific interval (between valid from and to dates). Is it possible using rules or custom module?

Please help.

Yes, Rajeesh, anything is possible with Rules. : P

In this case, I'd recommend something like a discount percentage field on user profiles that defaults to 10% and is only visible to administrators who can then override the field value on a user-by-user basis. Your product pricing rule can then look for this field to have a value on the order's user (i.e. use commerce-line-item:commerce-order:owner as the token, not the site:current-user) and then apply it as a discount using the appropriate line item action.


Implementing different user registration I have looked elsewhere for the problem I faced, but I cannot get any clue on solving the problem. Consider, based on the type of user, I want to implement different user registration page. In current D8 version, I could add fields at admin/config/people/accounts/fields. Let's say a teacher has fields like
Fname, Lname, ID, Contact, and School Name whereas student has fields like Fname, Lname, Course, and Age.

If I add those mentioned fields in the user table, I won't be able to differentiate whether that is teacher or student. In that case, how do I make two different registrations, one for teacher another for student, and store them as Drupal users so that I can apply functions such as \Drupal::currentUser->isAuthenticated() on them?

I would argue that you only need one type of user, but want multiple types of profiles. It sounds like you are looking for the profile module. From the module description:

  Why use profiles instead of user account fields?

  With profile, user account settings and user profiles are conceptually
  different things, e.g. with the “Profile” module enabled users get two
  separate menu links “My account” and “My profile”.
  Profile allows for
  creating multiple profile types, which may be assigned to roles via
  permissions (e.g. a general profile + a customer profile)
  Profile supports private profile fields, which are only shown to the user owning the profile and to administrators.

It also supports multiple registration forms to allow users to register and create their profile in one form.

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


Change view title programmatically I couldnt find an answer to this question in Drupal 8.

I've created a simple custom module:

mymodule.info.yml

name: 'mymodule_name'
description: 'basic module for custom implementations'
package: 'custom'
type: module
version: '8.x-1.0'
core: '8.x'

mymodule.module

function mymodule_views_post_execute(\Drupal\views\ViewExecutable $view) {
    $view->setTitle('Foo');

}
function mymodule_views_pre_render(\Drupal\views\ViewExecutable $view) {
    $view->setTitle('Foo');
}

I tried this hook implementations separately, not at smae time. Both changes the view title, but my custom theme doesnt work.

I also tried in my custom theme the following code:

function mytheme_preprocess_views_view(&$variables) {
    $view = $variables['view'];
    $view->build_info["title"] = "Foo";
}

It prints "Foo" inside view content, it doesnt override view title.

Any idea?

You probably want to change the global title used for the title block. This is retrieved from the route. The route for a view is built from the view configuration when you save a view  (or clear the cache). The title in the route is static. If you want to change it, modify it in the view configuration. You can do this in ui or in code.

If you want to make this dynamically, you can replace the static _title in the view route with a title controller _title_callback to provide a different title on every request.


How to access a variable in the ready event within charts_google.js without hacking the chart module? I need to be able to respond to the ready event within the Chart module.

I have Homebox installed and one of the blocks used in it is a google chart. The homebox resize action takes place before the chart has finished rendering and is misalligned.

I need to call the homebox resize action from the chart ready event. Currently I have added this code to the charts_google.js file, which works fine but I need to move it out of the chart module into my custom module.

function myReadyHandler(){ // added this
  Drupal.homebox.equalizeColumnsHeights();
}

function renderCharts() {
 ...
 google.visualization.events.addListener(wrap, 'ready', myReadyHandler); // added this
 ...
}

The variables in question is wrap. How can I get access to this variable in my own module without hacking charts_google.js?

Consider looking at issues #1196712 and 1715638, which seem to be like variations of your request.


Hook form alter for select list I tried to convert a text field filter for title into a select list filtered by content type using hook form alter:

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

  if($form_id == 'views_exposed_form'){

      // load nodes filtered by content type - news
      $nodes = node_load_multiple(array(), array('type' => 'news'));

      // Build an array
      $dropdown_array = array('' => '--Any--');
      foreach ($nodes as $node) {
         $key = $node->title;
         $value = $node->title;

         $dropdown_array[$key] = $value;
      }

      // Alter form
      $form['title'] = array(
         '#type' => 'select',
         '#default_value' => '1',
         '#options' => $dropdown_array,
      );

   }//endif

}

The code above works well. Now I wonder is there a better, shorter, more efficient or proper API to implement ? I'm a newbie in drupal programming. Learning to code in a more drupal way. Please advise. Thanks.

If you know that this list won't grow more than few dozens of nodes (you have to make some tests with more items) I'd just avoid loading complete nodes - it's unnecessary if you need only the title.
This call might become a significant database hit (=> page will load slower and will slow down other visitors of the site) when you add more nodes to the site.
When you call node_load(), Drupal builds the complete node object, meaning it looks for all additional fields you added, settings and calls corresponding node hooks from other modules. Avoid calling it for small details whenever you can.

Here's what you could use instead:

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

  if($form_id == 'views_exposed_form'){

      $nodes = db_select('node', 'n')
        ->fields('n', array('title'))
        ->condition('type', 'news')
        ->orderBy('n.title', 'ASC')
        ->execute();
      $dropdown_array = array('' => t('-- Any --'));
      foreach ($nodes as $node) {
        $dropdown_array[$node->title] = $node->title;
      }

      // Alter form
      $form['title'] = array(
         '#type' => 'select',
         '#default_value' => '1',
         '#options' => $dropdown_array,
      );

   }//endif

}

Check out also Chosen module for Drupal - it will allow you to have a much nicer select form element than the default one. It's pretty straightforward to install.
You can see a demo here.


Displaying two Content Types in a single view I have searched on this topic and have seen a number of answers, but they all seem rather complex for what (I think) is something straight-forward.

Our not-for-profit holds a monthly meeting. There are two primary program elements at the meeting: Presentation and Panel. A meeting will always have exactly one Panel and between zero and two Presentations.

I have created Content Types for Presentation and Panel. Presentation has the fields: Title, Date, Presenter, and Description. Panel has the fields: Title, Date, and Description. I would like to create a view which outputs the following:
Date
Panel->Title
Panel->Description
Presentation->Title
Presentation->Presenter
Presentation->Description

Where the Presentation block is hidden if there are none and repeated if there are two.

I believe the Filter Criteria are set correctly -  Content: Type (in Panel, Presentation)

Under Format->Setting, I grouped by Date.

The problem is that I cannot control the output - the fields all appear, but I cannot order them as desired nor can I format them as desired. The reason, I think, is that the field have the same name in the two Content Types, thus I do not seem to be able to address either directly.

I did try a PHP control to try to see what was happening. I basically created variables for each of the five outputs I want and printed them. Each date resulted in two calls to the print statements: the first print shows nothing for the Panel variables and has the proper values for the Presentation variables, whereas the second print shows nothing for the Presentation variables and has the proper values for the Panel variables. (What puzzles me is that I was only expecting a single print due to the grouping...)

I would appreciate your providing me with some guidance.

Thank you.

In response to Molot:

There are several ways to skin this cat. I believe that the approach I took is the easiest, though there is one remaining issue (more below).

Steps:

Add the References module (other options include using the Entity Reference module and one other similar module)
On Admin->Modules, under Fields, enable References and Node Reference, and click Save Configuration.
For the 'parent' entity type (in my example above, Panel) add a new field of type Node Reference. In the settings for this field, select the content type(s) that can be referenced (for my example above, I chose Presenter).
In the patent entity type, chose Manage Display. For the Referenced Node, you can choose 'Rendered Node' as the Format of the child node (and you can define this to be the default view, the Teaser view, etc.)
For each entity of the parent type, in the newly created reference field, start typing the title of the field to be referenced, then click the proper one.

As noted above, I am still having one problem - see Configuring View output with multiple related nodes for details.

I hope you find this helpful.


How can I convert a node title to a lowercase string with hyphens? I need to convert the title of a node, for example, from this

  John Doe

to

  john-doe

Is there Drupal function for it? (Easier to use than using preg_preplace etc.)

If you're just looking for a way to convert the title into a URL friendly machine name, then the following regex will do what you need:

$machine_name = preg_replace('@[^a-z0-9-]+@','-', strtolower($title));


hide collapsible fieldsets on node edit I understand how to edit a specific content type with form_alter

my_module_form_node_form_alter(&$form, $form_state) {

  $type = $form['#node']->type;

  if ($type == 'my_content_type') {

  }
}

I would like to hide all collapsible fieldsets EXCEPT scheduling. How do I only target these other fieldsets to hide?

http://screencast.com/t/ozHu5esPGc

Dull ax approach would be to cycle through your $form looking for fieldsets and unsetting (now setting #access to FALSE) all but the one you want to keep, eg, something along the lines of...

// drupal_set_message('<pre>' . print_r($form, TRUE) . '</pre>');
foreach($form as $key => $field) {
  if ($key != 'field_FIELDNAME' && is_array($field)  && $field['#type']=='fieldset' && $field['#collapsible']) {
    // unset($form[$key]);          // ADDITION/EDIT: '#access' below is a better/working approach
    $form[$key]['#access'] = FALSE; // than unset if required fields are in the fieldset :)
  }
}

...with the drupal_set_message() helping to get the field_FIELDNAME for your scheduling fieldset.

Just realize that without further logic, you would never be able to edit any fields inside these fieldsets again.

Another option might be to check out the nodeformcols module that makes lengthy node forms a bit nicer and does contain this functionality out of the box for both fields as well as fieldsets.


How to migrate users from old drupal d6 site to new drupal 7 site? I need to migrate users from drupal 6(old site) to drupal 7(new site) alongwith User Profile from Profile module

I am looking at documentation given in migrate module as follows:

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

  On Subsequent pages at After adding new migrations, or making changes
  to the arguments of previously-registered migrations, if you want them
  to be recognized by Migrate, you need to:

  Clear the Drupal cache, so any new classes are added to the Drupal
  cache registry. Perform the registration, either with drush
  migrate-register or by visiting admin/content/migrate/configure and
  clicking the "Register statically-defined classes" button.

I have created migrate_xyz.info ,migrate_xyz.module and migrate_xyz.migrate.inc files
As mentioned above when I move to admin/content/migrate/configure i get a blank screen

Is this the right way to go for migrating users from drupal 6 to drupal 7?
Or should I use some other module like migrate_d2d

Check this article . It describes how to use migrate module and it's API.
Code from this article:

First of all we need to create module by adding folder with name my_migration adding my_migration.info and my_migration.module files. So lets start, code below will have a lot of comments:

//my_migration.info file

name = "User Migrate"
 description = "Migration of data from Drupal 6 to Drupal 7"
 package = "Custom Migrate"
 core = 7.x
 dependencies[] = migrate
 dependencies[] = migrate_extras
 dependencies[] = field
 dependencies[] = file
 dependencies[] = text
 dependencies[] = path
 dependencies[] = taxonomy

 files[] = includes/users.inc

//my_migration.module file
// this file can be empty but we will define some constants
<!--?php /*
 * Define some constants to use in class
 */
define("SOURCE_DATABASE", 'd6_latest'); // Put drupal 6 db name you should also add settings to settings.php
define("CONNECT_NAME", 'migrate');// name of connection to drupal 6 db in settings.php
define('SOURCE_TERM_GARDEN_CAT', 3); // When we will migrate terms we will use it.
define('SOURCE_URL', 'http://path_to_drupal6.site');
define('MIGRATE67_SITE_DIRECTORY', 'public://');

//my_migrate_migrate.inc you should name this file as module_name_migrate.inc
// if not your migration won't be autoloaded.
<?php

/**
 * Implements hook_migrate_api().
 */
function my_migrate_migrate_api() {
  $api = array(
    'api' =?--> 2,
    'migrations' => array(
      'MfUserMigrate' => array('class_name' => 'MfUserMigrate'),
    ),
  );

  return $api;
}

//my_migration/users.inc

<!--?php /**
 * User migration class to migrate users.
 */
class UserMigrate extends Migration {
  public function __construct() {
    parent::__construct(MigrateGroup::getInstance('UserMigrate'));
    // Select fields from the Drupal 6 user table.
    $query = Database::getConnection('default', CONNECT_NAME)
      -?-->select('users', 'u')
      ->fields('u', array('uid', 'name', 'pass', 'mail', 'created', 'access',
        'login', 'status', 'picture', 'init'));
    // This is supposed to get roles not sure how.
    $source_fields = array(
      'uid' => t('User ID'),
      'roles' => t('The set of roles assigned to a user.'),
    );
    // Set source and destination.
    $this->source = new MigrateSourceSQL($query, $source_fields);
    $this->destination = new MigrateDestinationUser(array('md5_passwords' => TRUE));
    // Set up database maping.
    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'uid' => array(
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
          'description' => 'D6 Unique User ID',
          'alias' => 'u',
        )
      ),
      MigrateDestinationUser::getKeySchema()
    );
    // Add simple field mappings
    $this->addFieldMapping('is_new')
      ->defaultValue(TRUE);
    $this->addFieldMapping('uid', 'id_to_preserve');
    $this->addFieldMapping('name', 'name')->dedupe('users', 'name');
    $this->addFieldMapping('pass', 'pass');
    $this->addFieldMapping('mail', 'mail')->dedupe('users', 'mail');
    $this->addFieldMapping('language')->defaultValue('');
    $this->addFieldMapping('theme')->defaultValue('');
    $this->addFieldMapping('signature')->defaultValue('');
    $this->addFieldMapping('signature_format')->defaultValue('filtered_html');
    $this->addFieldMapping('created', 'created');
    $this->addFieldMapping('access', 'access');
    $this->addFieldMapping('login', 'login');
    $this->addFieldMapping('status', 'status');
    $this->addFieldMapping('picture')->defaultValue(0);
    $this->addFieldMapping('init', 'init');
    $this->addFieldMapping('timezone')->defaultValue(NULL);
    $this->addFieldMapping('roles', 'roles');
  }
  // Set up Roles.
  // massage the user roles before saving
  public function prepareRow($current_row) {
    $source_id = $current_row->uid;
    $query = Database::getConnection('default', CONNECT_NAME)
      ->select('users_roles', 'r')
      ->fields('r', array('uid', 'rid'))
      ->havingCondition('r.uid', $source_id, '=');
    $results = $query->execute();
    // add the anonymous role for everyone
    $roles = array('1' => '1');
    foreach ($results as $row) {
      // adjust the old to new role id's
      // Editors (rid 7) need role id 4
      if ($row->rid == 7) {
        $roles['4'] = '4';
      }
      elseif ($row->rid == 4) {
        // producer from 4 to 5
        $roles['5'] = '5';
      }
      elseif ($row->rid == 5) {
        // blogger from 5 to 6
        $roles['6'] = '6';
      }
      elseif ($row->rid == 8) {
        // freelancer 8 to 7
        $roles['7'] = '7';
      }
      else {
        // Collaboraters are role id 5 in both old and new dbs
        $roles[$row->rid] = $row->rid;
      }
    }
    $current_row->roles = $roles;
    return TRUE;
  }
} // close the ourUserMigration class