Drupal 7 Rules: Compare Group Reference Field and fire Rule if data changed I am using a content type called "question" which has an organic group reference field (og_group_ref).

I want to trigger an action with Rules, when the field "og_group_ref" is changed on node update.

So I have created the following rule:

{ "rules_notify_question_author" : {
"LABEL" : "Question has moved - notify user",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_update--question" : { "bundle" : "question" } },
"IF" : [
  { "AND" : [
      { "NOT data_is" : {
          "data" : [ "node-unchanged:og-group-ref" ],
          "value" : [ "node:og-group-ref" ]
        }
      }
    ]
  },
  { "NOT data_is_empty" : { "data" : [ "node:og-group-ref" ] } }
],
"DO" : [
  { "mail" : {
      "to" : "[node:author:mail]",
      "subject" : "Some handy subject",
      "message" : "E-Mail to author",
      "from" : "[site:mail]",
      "language" : [ "" ]
    }
  },
  { "drupal_message" : { "message" : "Message text" } } } }
]

The idea is that the author of a question gets notified, when the questions was moved to another group. The logic should be like this:

  EVENT: On Node question Update

  CONDITION: node_unchanged:og-group-ref != node:og-group-ref AND node:og-group-ref != EMPTY

  ACTION: Send Mail an show a message

My problem is, that the rule fires when the content of the field og_group_ref was changed and when it was NOT changed.

I printed the compared values in the drupal message. The values are correct. But I do not know, why the rule is triggered although the field "og_group_ref" did not change.

Has anyone an idea?

I solved the problem by creating an own condition for rules using the API of the rules module.

function hook_rules_condition_info() {
  return array(
    'rules_condition_text_compare' => array(
      'label' => t('Textual comparison'),
      'parameter' => array(
        'text1' => array(
          'label' => t('Text 1'),
          'type' => 'text',
        ),
        'text2' => array(
          'label' => t('Text 2'),
          'type' => 'text',
        ),
      ),
      'group' => t('Rules'),
    ),
  );
}

See hook_rules_condition_info for more details.


How to change the button name after click on it using ajax I am a newbie in drupal. I created a form that perform ajax action. How can I change the button name after click by using ajax.

function auktion_fav_form($form, &$form_state, $auktion_id) {
  form['add_to_fav'] = array(
    '#type' => 'submit',
    '#id' => 'submit',
    '#value' => t($value),
    '#ajax' => array(
      'callback' => 'auktion_fav_submit',
      'wrapper' => 'submit',
      'method' => 'replace',
      'effect' => 'fade',
    )
  );
  return $form;
}
function auktion_fav_form_submit($form, &$form_state) {
  $form['add_to_fav']['#value'] = "remove from favourite;
  return $form['add_to_fav'];
}

In hook form alter define your submit value . Below is small piece of code .

   $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Calculate'),
     '#prefix' => '
',
     '#suffix' => '
',
    '#ajax' => array(
        'callback' => 'example_ajax_form_callback',
        'wrapper' => 'div-example',
         'method' => 'replace',
      ),
     );

function example_ajax_form_callback($form, &$form_state) {
  $form['submit']['#value'] = 'New value';
    return $form['submit'];
  }


How to retrieve datetime from database in Drupal? How do I retrieve a DateTime column from my MySQL database using Drupal Database API + PHP. The DateTime format is in YYYY-MM-DD HH:MM:SS(2013-02-20 23:59:59). I want to retrieve all the rows in the database that match a specific date, and then store the hour inside an array.

For example, I want to grab all the data from January 1, 2013. I then only want to store hours 00:00 to 23:59 inside my array, not the entire date.

I do not want to use any modules to accomplish this.. because I need to code it inside my custom module.

Thanks for your help!

Current Code:

$query = db_select('Project', 'p');
$query->fields('p', array('submissions', 'date_time'));
$query->condition('p.user_id', $user->uid);
$results = $query->execute()->fetchAll();
foreach($results as $r) {
    $rows[] = array(strtotime(date("H:i:s", $r->date_time))*1000, $r->submissions);
}

I plan to display the data on my Flot line graph.

If you want the benefits of a SelectQuery, but with the more fine-grained control over the SQL, you can always use the where() method to inject (sanitised) raw SQL into the WHERE clause. e.g

$query = db_select('Project', 'p');
$query->fields('p', array('submissions', 'date_time'));
$query->condition('p.user_id', $user->uid);

// Fetch only records where date_time is greater than 30 days ago
$query->where('date_time > DATE_ADD(NOW(), INTERVAL -30 DAY)');

$results = $query->execute()->fetchAll();
foreach($results as $r) {
  $rows[] = array(strtotime(date("Y-m-d", $r->date_time))*1000, $r->numberOfPackages);
}

I don't know of any 'structured' way to get those sort of advanced conditions into a SelectQuery object so resorting to plain ol' SQL is necessary sometimes.


Remote Entity Create with Node Reference I am writing an Android app which is creating Drupal nodes remotely.  I am creating these nodes via a straight php form.  But now I need to create Nodes which are node_references of the main node.  Usually in order to do this you will need the entity ID of the main node before you can create a node reference.

Creating the second node as a reference should be easy as it is just an extra field with a reference value in it.  The problem is, once the App creates the main node, I need the entity ID to be returned to the App so that the value can be used to create the other referenced node.

How do I get the entity ID back as a return value after node creation?

or... am I thinking about this all wrong  :)

If you are using the entity api to create and save your entity its fairly easy:

// Create the node and wrap it in entity metadata wrapper
$node_create = entity_create('node', array('type' => 'my_content_type'):
$node_wrapper = entity_metadata_wrapper('node', $node_create);

$node_wrapper->title->value("My Title"); // Set the title
$node_wrapper->save(); // Node is now saved
$node_nid = $node_wrapper->getIdentifier(); // We now have the nid

// Doing the same thing here except adding the reference
$node_create2 = entity_create('node', array('type' => 'my_other_content_type'):
$node_wrapper2 = entity_metadata_wrapper('node', $node_create2);

$node_wrapper2->title->value("My referenced title");
$node_wrapper2->field_node_reference->value($node_nid);

$node_wrapper2->save();


Multiple field, but each one as individule I need an image field with only 2 field limit.
I need to call first one front and second one back and be separated.(no problem I can do that with hook_form_alter)

My problem is that in drupal 7, in adding the content, it doesn't show the second field upload button until you upload the first one.
You have to add the first file, than click on "add another" to be able to upload second file and after uploading both if you delete the first one, the second one goes to first one place, which I don't want that to happen!

I know I can make two separate fields call one front image and one back, but I want to know if there is an approach to do this with only one field. (save a database table)

Thank You

Just use the single image field, add field description text for the user in regards to clicking to "add another" item when uploading the two images.

On updating, the user can adjust the weight of the images and drag/drop the front/back images into order.

Alternatively, you could look at using two fields, or a module like field_collection


Remove title from hook_entity_view I need to remove title from rendered custom entity.

unset($entity->title) is not good because i still need to use its value in this rendered entity to use in markup.

css display:none is not good idea on my point of view as well.

hook_entity_view(), and hook_entity_view_alter() are not the hooks you should use to avoid an entity title is rendered, as the entity title is not generally passed to the $build parameter passed to those hooks.

This is the content of the $build parameter for three different entity Drupal defines.

Node

Comment

Taxonomy term

Furthermore, the purpose of hook_entity_view() is adding content to $entity->content, not altering $entity. The description given in the documentation page for the hook is the following:

  The module may add elements to $entity->content prior to rendering. The structure of $entity->content is a renderable array as expected by drupal_render().

To avoid the title is rendered for an entity, you should use a preprocess function for the template file used by the entity, and unset a variable used from the template file for the title. For example, for a node, a module could use the following code.

function mymodule_preprocess_node(&$variables) {
  $variables['title'] = '';
}

Similar code would work for comments, but in that case the function would be mymodule_preprocess_comment().
For taxonomy terms, there isn't a title but there is the term name, which is printed from the template file using the following code.

<?php if (!$page): ?>

<a href="<?php print $term_url; ?>"><?php print $term_name; ?>

<?php endif; ?>

Setting $term_url, and $term_name to an empty string would cause the following HTML output to be printed.


Certain roles creating users I am spinning up a site that will have 18 different organizations interacting together.  Each organization has a president with access to specific forms and parts of the site.  I would like them to be able to create/add users from their own organization.

Where I am stuck is that each president should only be able to edit/remove users from his own organization (aka that he created).  Do I need to create 18 different roles for each president and 18 different roles for members from their organizations, or is there a more convenient way of managing this.

I have reviewed the following modules without success:
Protect_critical_users, role_delegation, administerusersbyrole

Thanks.

You need not to create different roles for each user but one user role will serve the purpose with help of SUBUSER module.
Though it's in alpha stage for D7 but it has served me well for a project where I am handling organization as users.
You will need to give proper permission though, I hope you can play with that.


Counterup JS to work According to Counter JsInclude

(I've defined the library in the theme.libraries.yml and attached the library in the theme.info.yml and it shows in the header)

statcounter:
 version: 8.x-1.0
js:
 scripts/jquery.counterup.min.js: { minified: true }
dependencies:
 - core/jquery

HTML

1,234,567.00
$1.99
12345

(Have added this in a block in the front page and the markup is displayed)

jQuery

$('.counter').counterUp(); **or with extra parameters**
$('.counter').counterUp({
delay: 10,
time: 1000
});

(Have placed the jquery in a separate custom js; and defined it in the theme, the js is loaded and no errors till now)

   custom:
    version: 8.x-1.0
   js:
    scripts/custom.js: {}

I want to attach the last bit of jquery to the theme and make the counter work...Any ideas how to get it to work? Thanks.

Make sure all files are present !

The drupal way for custom js in your theme is a behavoir, so your js file should look like this:

    (function ($) {
      Drupal.behaviors.myThemeBehavior = {
        attach: function (context, settings) {
           $(context).find('.counter').once('myThemeCounter').counterUp({
             delay: 10,
             time: 1000
           });
        }
      };
    })(jQuery);

This will ensure the script is executed after the DOM is loaded and only will run once.


Auto posting to Facebook page I am using the Drupal for Facebook module on both a D6 and D7 site to post to a FB page (not a group or a personal account/wall) via streams.

It is working fine except I would like the 'Post to Facebook' checkbox be automatically checked only when the node is created, but not on subsequent edits.  My users won't check this box on their own (and I may not even want them to see it).

I've tried using Rules, but there seems to be no FB posting action there.

I'm assuming it can be done via hook_form_alter, but have had no luck with that.  The Element ID for the checkbox is... fb_stream[fb_stream_do_post]

Any thoughts???

Thanks,

Eric

Thanks everyone.

What I was able to do was build a Rule with Form Events that sets the 'Post to Facebook' checkbox (and one for Twitter) if the current page URL matches the node edit URL.  This way only the creation of a node, and not subsequent edits, are posted to FB...

I was initially going to do a hook_form_alter, but once the initial Rules test worked I figured I would go with it.

Rule Export >>

{ "rules_form_alter_post_to_fb" : {
    "LABEL" : "Form Alter - Article Post to FB and Twitter",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_forms" ],
    "ON" : { "rules_forms_article_node_form_form_built" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "http:\/\/www.example.com\/node\/add\/article"
        }
      }
    ],
    "DO" : [
      { "rules_forms_set_default" : {
          "form" : [ "form" ],
          "element" : "checkbox:fb_stream:fb_stream_do_post",
          "value" : 1
        }
      },
      { "rules_forms_set_default" : { "form" : [ "form" ], "element" : "checkbox:twitter:post", "value" : 1 } }
    ]
  }
}


How do I render a field twice with two different field formatters? So there was already the same question for D7 (How do I render a field on a node twice with two different field formatters?) but now i wanted to know how to do this in d8.

Maybe this helps a little bit, but i could not get it working.
Rendering arbitrary field values without a parent entity in Drupal 8

So in drupal 7 you could use:

$output = field_view_field('node', $node, 'field_foo', array('type' => 'some_formatter', 'settings' => array(...), $langcode));

to render a field with a specific formatter. The drupal 8 the equivalent is:

$output = $node->field_foo->view(array('type' => 'some_formatter', 'settings' => array(...)));

source: Change record

Now to render the fields I would create a preprocess for a node

function HOOK_preprocess_node(&$variables) {
  $variables['my_field_formatter1'] = $node->field_foo->view(array('type' => 'some_formatter', 'settings' => array(...)));
  $variables['my_field_formatter2'] = $node->field_foo->view(array('type' => 'some_formatter', 'settings' => array(...)));
}

and then print my_field_formatter1 and my_field_formatter2 in your twig template for the node.


How to add properties to ConfigurableLanguage config entity? I need to add some properties to the ConfigurableLanguage. I need to have them editable when editing or adding a language and when getting language object from language manager service.

I can handle altering forms, but what about storing those properties and having them available with Language objects?

I was tempted to extend ConfigurableLangue and use hook_entity_type_build() to replace ConfigurableLangue class with my own implementation. However I'm not sure if works for config entities too (I've used this method with content entities). Nevertheless I've noticed scattered around core few calls to static ConfigurableLanguage::createFromLangcode() which returns instance of ConfigurableLanguage class. So extending ConfigurableLangue won't solve my problems.

Even if it might be late for the OP, here is the way to achieve this.

As language is stored as ConfigEntity, you can use ThirdPartySettingInterface.

Here is an example entity types are not correctly define in the link. which I based my own implementation on.

Steps to follow to achieve adding properties on language entity are a set of pretty common drupal development actions :

// Step 1 : Altering the configuration form ( language_admin_edit_form ) in this case.

/**
 * Implements hook_form_FORM_ID_alter().
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function {our_module_name}_form_language_admin_edit_form_alter(
    &$form,
    \Drupal\Core\Form\FormStateInterface $form_state,
    $form_id) {

  //Step 2. We can retrieve the ConfigEntity the form is working on

  /** @var {\Drupal\language\Entity\ConfigurableLanguage} $language */
  $language = $form_state->getFormObject()->getEntity();

  //Step 3. Add our custom property(ies)
  $form['{name_of_our_property_1}'] = array(
    '#type' => 'checkbox',
    '#title' => t('Our custom property 1'),

    //Ok this is already a step ahead but, for the default_value
    //we can get the stored value in thirdPartySetting property of the ConfigEntity
    '#default_value' => $language->getThirdPartySetting('{our_module_name}', '{name_of_our_property_1}'),
  );

  //Step 4. We will need to hook before the entity is saved as config,
  //in order to retrieve the property values on form,
  //and adding thoses in the ConfigEntity thirdPartySetting property.
  $form['#entity_builders'][] = '{our_module_language_entity_builder_function_name}';
}

This will add form input with previously saved values on thirdPartySetting and add our custom entity builder. So lets define our custom entity builder :

/**
 * Our custom entity builder
 * @param $entity_type
 * @param \Drupal\language\Entity\ConfigurableLanguage $language
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 */
function {our_module_language_entity_builder_function_name}(
    $entity_type,
    \Drupal\language\Entity\ConfigurableLanguage $language,
    &$form,
    \Drupal\Core\Form\FormStateInterface $form_state){

    //If our property can be found from form_state values
    if ($form_state->getValue('{name_of_our_property_1}')) {
        //We can update the linked property on thirdPartySetting
        $language->setThirdPartySetting(
            '{our_module_name}',
            '{name_of_our_property_1}',
            $form_state->getValue('{name_of_our_property_1}')
        );
    }else{
        //User surely wanted to remove the previous value,
        //so remove it from thirdPartySetting property too
        $language->unsetThirdPartySetting('{our_module_name}', '{name_of_our_property_1}');
    }
}

Ok, now the edit form shows our property, our custom entity builder save it.
Last step ahead, using our custom value somewhere else of the language edit form.

//So we have a language, it doesn't matter how you get it.
//Here is from the currentLanguage property

/** @var {\Drupal\Core\Language\LanguageInterface} $language */
$language = \Drupal::languageManager()->getCurrentLanguage();

//The language itself doesn't own the thirdPartySetting,
//So we need to use its matching ConfigEntity

//Getting the ConfigurableLanguageManager
/** {\Drupal\language\ConfigurableLanguageManager} $configManager */
$configManager = \Drupal::entityTypeManager()->getStorage('configurable_language');

//now load the matching ConfigEntity of Language
/** @var ConfigurableLanguage $config */
$languageConfigEntity= $configManager->load($language->getId());

//Do what you want of your property
$ourPropertyValue = $languageConfigEntity->getThirdPartySetting('{our_module_name}', '{name_of_our_property_1}');

//Alternatively we could get an array of all our module thirdPartySetting properties
$allOurProps = $languageConfigEntity->getThirdPartySettings('{our_module_name}');

//And it's done.


Drupal Custom Login Page Using Zen Sub-theme I have a custom Login Page in my website

I am using Zen for my themes.

I already have the Login page using the naming convention (e.g xxx--xxxx--tpl.php) but I can't display my form in this page.

here is my cpde

page--user_block--login.tpl.php:

ONREVUE LOGIN

 /****This is where I want to display the form ***/

Register|Forgot Password?

My Template.php code

function Alphasys_theme(&$existing, $type, $theme, $path) {
$hooks = zen_theme($existing, $type, $theme, $path);
 // Add your theme hooks like this:
/*
  $hooks['hook_name_here'] = array( // Details go here );
*/

$hooks['user_login_block'] = array(
  'arguments' => array('form' => NULL),
       'template' => 'page--user_block--login',
);

 // @TODO: Needs detailed comments. Patches welcome!
 return $hooks;
  }

  function Alphasys_preprocess_user_login_block(&$vars) {
  // Modify the text of the submit button
 $vars['form']['submit']['#value'] = t('Login Now!');

  $vars['form_markup'] = drupal_render($vars['form']);
}

I don't know what's the problem with the Code but it seems I can't make to work...

I already tried to put

<?php echo $form_mackup ?>

in my page--user_block--login but doesn't work.. I already tried to clear the cache..
but it is not working either..

Please help me...Responses are much appreciated..Thanks

I think your problem is that you're confusing the login block with the login page in the preprocess function and tpl names

try

function Alphasys_preprocess_user_login(&$variables) {
  //a capitalized theme name?
  $variables['rendered'] = drupal_render($variables['form']);
}

then change the

$hooks['user_login_block']

to

$hooks['user_login']

and drop in your print statement into the tpl

<?php print $rendered ?>

and you should be good to go


Why I can't use the same code from Drupal 7 in Drupal 8 to generate a button with FAPI? Following the question Generating <button type="submit"> with the form API for Drupal 7 I tried to implement the same thing in Drupal 8.

I need the following output:

<button type="submit" class="clearfix">Login</button>

So I tried to use this code:

$form['submit'] = array(
  '#prefix' => "<button type ='submit'>",
  '#suffix' => "</button>",
  '#type' => 'markup',
  '#markup' => "" . t('Login') . "",
);

But I obtain this:

Login

But if I use this code:

$form['submit'] = array(
  '#prefix' => "",
  '#suffix' => "",
  '#type' => 'markup',
  '#markup' => "" . t('Login') . "",
);

I obtain this:

Login

So the <button> tag is eliminated but the  tag not. Very strange for me, the Button is not rendered.

Thanks to @Kevin I used the leymannx answer an with this code I solve the problem:

$form['submit'] = [
  '#type' => 'inline_template',
  '#template' => '<button type="submit" class="glyphicon glyphicon-search"></button>',
];

But, why I can't use the same code in Drupal 7 and Drupal 8 to generate a button with FAPI?

The reason why it is not working in Drupal 8 as in Drupal 7 is, that prefix and suffix are passed to xssFilterAdminIfUnsafe() function in doRender() function. Thus preventing all tags except the tags specified in $adminTags.

Excerpt from doRender:

  // We store the resulting output in $elements['#markup'], to be consistent
  // with how render cached output gets stored. This ensures that placeholder
  // replacement logic gets the same data to work with, no matter if #cache is
  // disabled, #cache is enabled, there is a cache hit or miss.
  $prefix = isset($elements['#prefix']) ? $this->xssFilterAdminIfUnsafe($elements['#prefix']) : '';
  $suffix = isset($elements['#suffix']) ? $this->xssFilterAdminIfUnsafe($elements['#suffix']) : '';

  $elements['#markup'] = Markup::create($prefix . $elements['#children'] . $suffix);

You can use '#allowed_tags' property to enable specific tags. So this should work:

  $form['submit'] = array(
  '#type' => 'markup',
  '#markup' => "<button type ='submit'><span>" . t('Login') . "</span></button>",
  '#allowed_tags' => ['button', 'span'],
  );

But '#allowed_tags' property will not work for '#prefix' and '#suffix'.


Working with a checkbox and EntityFieldQuery So I have a custom field which is a checkbox and is called 'field_hide_panel'.

The on value is '1' and the off value is '0'. But bare in mind, this field was added later so there are a lot of rows in my database which will not have any field_hide_panel value.

When this checkbox is selected it should be omitted from the results of my query.

I have this line to try to achieve this:

$query->fieldCondition('field_hide_panel','value', '1', '!=');

The problem is, I'm not getting anything returned. I think this is because most of my nodes don't have a 'field_hide_panel' value at all but I still want these returned as my logic says these should still show because field_hide_panel does not equal 1.

Is there any way around this without me having to go through hundreds of nodes and re-save them so they get '0' as the field_hide_panel?

You can add tag to your query and use hook_query_TAG_alter() to add additional conditions. Here's an example:

function mymodule_get_nodes() {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->addTag('node_is_not_tagged');
  return $query->execute();
}

/**
 * Implements hook_query_TAG_alter().
 */
function mymodule_query_node_is_not_tagged_alter(QueryAlterableInterface $query) {
  $query->leftJoin('field_data_field_hide_panel', 'hp', 'node.nid = hp.entity_id AND hp.entity_type = :entity_type');
  $or = db_or()
    ->condition('hp.field_hide_panel', 0)
    ->isNull('hp.field_hide_panel');
  $query->condition($or);
}

Link to relative issue: https://www.drupal.org/node/1157006


Can I redirect the user to some other page if the result of a view is empty? How do I redirect the user to some other page, when the view returns empty result?

In your views No results behavior Choose ' Global: Text area ' choose php filter and add the following code.

<?php
 drupal_goto('node/1'); //path to redirect
?>


How to make sure the footer is always at the bottom? As an important note I do NOT mean position: fixed;!!!

When the body is smaller and does not take the full height of the browser size, the footer just likes to chill in the middle of the page. If you look in the photo I shared you can see more clearly what I mean. I've tried things like body{height: 100%;} to no avail. Even attempted this: https://css-tricks.com/snippets/css/sticky-footer/ and it seemed to just break it more (especially on the front page where this isn't a problem. Is there possibly a way to make sure the body size is at least the size of the browser always?

You can make use of the calc() expression, and use min-height instead of height. Say your footer height is 100px:

body{
  min-height : 100%;
  min-height: -moz-calc(100% - 100px); /* Firefox */
  min-height: -webkit-calc(100% - 100px); /* Chrome, Safari */
  min-height: calc(100% - 100px); /* IE9+ browsers */
}
footer{
  height: 100px;
}

Get more info about calc() here


How to add an ascending row number (using some token) in front of each row in Views? I can't figure out how to make a soccer league table that would look like this: http://prntscr.com/8va7h7

This is how the table looks now: http://prntscr.com/8va8eu

Everything works but I don't know how to show the team position on the table. Is there a way to make this work using tokens so they count the number of rows?

In your View add a new Field, Filter by Global and select:

  Global: View result counter

  Displays the actual position of the view result

Click the Apply button and if you want change the output select Rewrite the output of this field in the Rewrite results section, and in the Replacement patterns section you will see the [counter] token as:

  [counter] == Global: View result counter


Is there any theme record count? Is there any theme record count? Like: "Showing 1 to 10 of 186 records".

So that the user sees the number of pages and total number of records of a query (EntityFieldQuery).

Something made my drupal like theme pager, that we use like this:

//...
$query = new EntityFieldQuery();
//...
$query->pager(10);
//...
$content .= theme('pager');
//...

No, but you can easily make one yourself by implementing hook_theme().


Webform submissions and og_group_ref We are building a web site that relies heavily on organic groups.
We provide in the front page a webform to allow non-authenticated people to submit a request of membership to one of the main groups (there are subgroups also).

What I need is the webform to work as it does out of the box, but as soon as a submission is sent, subscribe it to a group. Inside the group, a user which belongs to a certain role will accept/reject the membership request.

So far, I have learned that if you add the feature 'is group content' to the webform content type, it affects to the webform but not to the submissions (i.e. unauthenticated users can't reach the webform since the group in the og_group_ref is configured as 'private' (and it has to be this way).

TLDR: I need the submissions of a webform to be able to be assigned the og_group_ref attribute as they are submited. Is it possible?

TIA

Interesting question/challenge (+1 from me ...). What you described about the "is group content" makes those webforms indeed unreachable for anybody who is not part of that group (so that's a "works as designed" ...

However, how about using the Rules module to complete your puzzle? Haven't looked at all the details (yet), to see if it can actually be done (I'm pretty sure it can ...), but I'm thinking of using a rule that looks more or less like this:

Event: when Webform is submitted

Condition: If membership for group is requested in the submitted form

Action: Send eMail to an authorized user to accept / reject the request


How can I dynamically load options into a select list? I'm creating form using drupal_get_form and I'm using the following code for creating a select list:

$form['select-user-group'] = array(
  '#type' => 'select',
  '#title' => t('Select a group'),
  '#options' => array(
    '' => t('-- Select a user group --'),
  ),
  '#ajax' => array(
  'event' => 'load',
  'callback' => 'selectuser_ajax_callback',
  'method' => 'replace',
);

and then I'm trying to define a function like following to dynamically add options to the select list:

function selectuser_ajax_callback() {

  db_set_active('drupal');

  $result = db_query("select * from {content_type_usergroup}");
  $record = db_fetch_object($result);

  $str = '<select>';
  while ($obj = db_fetch_object($result)) {
    $str .= '<option value=' + $obj->vid + '>' + $obj->field_p_group_name_value + '</option>';
  }
  $str .= '</select>';

  echo $str;
}

But it's not working. How to make this function work properly to populate the select list '#options?

For just populating select list options, you don't need to go through an Ajax approach! Simply write a separate function and write your database query inside it and then just call that function in '#options' of your $form['select-user-group'].

For example for displaying all node types in a select list you can use the following function:

function get_node_type_info() {

  $wizard_plugins = node_type_get_types();

  $options = array();

  foreach ($wizard_plugins as $key => $wizard) {
    // Don't forget the $ before wizard
    $options[$key] = $wizard->name;
  }

  return $options;
}

And then use this function to populate the '#options' like so:

$form['display_options'] = array(
  '#type' => 'select',
  '#title' => t('Component Type'),
  '#options' => get_node_type_info(),
);


Views Infinite Scroll Set default page with position There is a view page with views_infinite_scroll paging.
This page is being used for list products.

Everything is working as I needed, but the problem is:

Suppose I'm on 5th page(Note: with scroll pagination) and I click on product to go to it's detail page, the detail page have a link to return back to the product listing page. So, when user clicks on "Back to previous Page" link on product detail page, it should display the 5th page with exact page view position.

Please help how should we achieve this?

Thanks In Advance

I know this answer seems to be (might be) a bad solution but it works. Use the code window.history.back() for "Back to previous Page" link like follows

<input type="button" value="Back to previous Page" onclick="window.history.back()" />

                             OR

<a href="#" onclick="window.history.back()"> Back to previous Page </a>

As far as I know this is browsers default behavior. So it works.

I've tested it and working on latest version of all major browsers.

Hope it helps.


Print Link field in View template I have a 'Link' field that is entered in plain text by user. I am trying to display the raw value of this field in my views template. I did dsm($fields); in the views template.

For the field, the raw data shows as a node id, not the url the user entered. The content attribute shows the url but it is wrapped in html. This is also the case when using ->content or ->raw in my views template.

I need to only print the plain url text the user entered in the template. How can I do this?

Here are the results for content and raw value:

if you're using the Link module, you can choose how the link is displayed, including plain text

  The link module can be count to the top 50 modules in Drupal
  installations and provides a standard custom content field for links.
  With this module links can be added easily to any content types and
  profiles and include advanced validating and different ways of storing
  internal or external links and URLs. It also supports additional link
  text title, site wide tokens for titles and title attributes, target
  attributes, css class attribution, static repeating values, input
  conversion, and many more.


hook_schema install, but not uninstall I can't figure how it is possible that the table I define in a hook_schema is created when I enable my module, but it isn't deleted when I uninstall the module (after disabling).

Drupal 7 documentation sais that the table should be automatically created and deleted when these events occours.

Here is the relevant part of the code inside my_module.install:

function my_module_schema(){
    $schema = array();
    $schema["my_module_table_xyz"] = array(
            ...
    );
    return $schema;
}

I don't know if it could be related to the difference between the modue name and the table name... or from the code present in the hook_uninstall... or something else...

Considering I also define a node type, the hook_uninstall should delete it (see following code), then system should automatically uninstall previously defined schema.

function my_module_uninstall(){
    ...
    node_delete_multiple(...);
    // delete custom fields
    node_type_delete(...);
    field_purge_batch(...);
}

What do you think about?
Thanks

NOTE: I use Drush to disable, uninstall and reinstall the module and I get the error Table my_module_table_xyz already exist.

Update: I just verified that the same code in a clean Drupal installation works as expected (table defined in hook_schema have been successfully removed).

In the "problematic" Drupal installation I also tried to explicit run drupal_uninstall_schema("my_module_table_xyz") at the end of the hook_uninstall (and I inserted a log instruction just after that line, to verify it runs without breaking), but nothing change. The table is stille there!

Any idea/hypothesis about will be really appreciated.

I had the same issue and finally I just manually did it in hook_uninstall(), I could find no other recourse.

function mymodule_uninstall() {
  $table_name = 'mytable';
  if (db_table_exists($table_name)) {
    db_drop_table($table_name);
  }
}

Hope this saves someone else some time.


Make PDF,XLSX,DOCX,PPTX output for drupal REST server When I tried to configure drupal service admin/structure/services/list/MyServiceName/server, I only see the following response content types.

Is it possible to provide pdf, docx, pptx, xlsx etc. as response format?

Yes it's definitely possible, but you'll need to write a formatter class for each type of file as the bundled REST server only has support for XML, JSON, JSONP, serialized PHP, bencode, and optionally YAML.

To start, you need to implement hook_rest_server_response_formatters_alter to let the REST server know about your new type, e.g.:

function MYMODULE_rest_server_response_formatters_alter(&$formatters) {
  $formatters['pdf'] = array(
    'mime types' => array('application/pdf'),
    'formatter class' => 'MyModuleServicesPDFFormatter',
  );
}

Then add your formatter class, which needs to implement ServicesFormatterInterface and provide the render method:

class MyModuleServicesPDFFormatter implements ServicesFormatterInterface {
  public function render($data) {
    return some_function_to_convert_data_to_pdf_string($data);
  }
}

Then make sure that class is auto-loaded by putting this in your module's .info file:

files[] = relative/path/to/MyModuleServicesPDFFormatter.php

Repeat the process for all of the new formatters you wish to provide, clear the cache when you're done.


Default user image in user account menu! I am trying to add a default image to render in the user account menu when the user does not have an image.

CODE:

function nestle_preprocess_menu(&$variables) {
  if($variables['menu_name'] == "account") {
    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    $name = $variables['user']->getUsername();
    $picture = file_create_url($file->getFileUri());
    $picture = $user->user_picture->view('large');
    $variables['items']['user.page']['title'] = $name;
    $variables['items']['user.page']['picture'] = $picture;
  }
}

What I did so far, is that I changed the "account" menu link to name of the logged in user and I added the picture of the user in the variables array so that I can render it using twig, The problem is I want to check when the $picture variable is empty ( ie: user has no photo ) it should render a default image from a URL.

PS: I am using Drupal 8, and this code is in the .theme file

You can check if a user picture exists this way:

if (!$user->user_picture->isEmpty()) {
  $picture = file_create_url($file->getFileUri());
  $picture = $user->user_picture->view('large');
} else {
  $picture_field = \Drupal\field\Entity\FieldConfig::loadByName('user', 'user', 'user_picture');
  $default_image = $picture_field->getSetting('default_image');
  $file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
  $picture = $file->getFileUri();
}


How to alter the path of login page? I want to alter the path of login page, /user/login, to /ulogin.  How can I accomplish this?

You can use module Rename Admin Paths

  This module allows you to:

  rename path like '/admin/...' to '/something/...' rename path like
  '/user/..' to '/something else/..' It can be effective against
  registration spam bots or malicious people.

  This small module just implements hook_outbound_alter and
  hook_inbound_alter to rename paths. A settings form allows to choose
  replacement term for "admin" and "user".


How can I get a user by email address using a service? I have a custom service that I created to do some stuff with users.  I want to be able to GET and DELETE users by email address because I may not know the uid.

I have the service set up now. It works through Postman, but through the actual client, it returns a 406 error because of the .com in the email.

How do I pass the email to the service if not through the URL?

This is the definition of the service.

'retrieve' => array(
    'help' => 'Retrieve a user',
    'file' => array(
        'type' => 'inc',
        'module' => 'user_service',
        'name' => 'user_service',
    ),
    'callback' => '_my_user_resource_retrieve',
    'access callback' => '_my_user_resource_access',
    'access arguments' => array('view'),
    'access arguments append' => true,
    'args' => array(
        array(
            'name' => 'email',
            'type' => 'int',
            'description' => 'The email of the user to retrieve.',
            'source' => array('param' => 'email'),
            'optional' => false,
        ),
    ),
),

The callback function is the following.

function _my_user_resource_retrieve($mail) {
  return user_load_by_mail($mail);
}

Apparently Params are only for index functions. So you need to implement an index function, something like this from the user_resources.inc file in the Services module:

'index' => array(
    'help' => 'List all users',
    'file' => array('type' => 'inc', 'module' => 'services', 'name' => 'resources/user_resource'),
      'callback' => '_user_resource_index',
      'args' => array(
        array(
          'name' => 'page',
          'optional' => TRUE,
          'type' => 'int',
          'description' => 'The zero-based index of the page to get, defaults to 0.',
          'default value' => 0,
          'source' => array('param' => 'page'),
        ),
        array(
          'name' => 'fields',
          'optional' => TRUE,
          'type' => 'string',
          'description' => 'The fields to get.',
          'default value' => '*',
          'source' => array('param' => 'fields'),
        ),
        array(
          'name' => 'parameters',
          'optional' => TRUE,
          'type' => 'array',
          'description' => 'Parameters',
          'default value' => array(),
          'source' => array('param' => 'parameters'),
        ),
        array(
          'name' => 'pagesize',
          'optional' => TRUE,
          'type' => 'int',
          'description' => 'Number of records to get per page.',
          'default value' => variable_get('services_user_index_page_size', 20),
          'source' => array('param' => 'pagesize'),
        ),
        array(
          'name' => 'options',
          'optional' => TRUE,
          'type' => 'array',
          'description' => 'Additional query options.',
          'default value' => array(
            'orderby' => array(
              'created' => 'DESC'
            )
          ),
          'source' => array('param' => 'options'),
        ),
      ),
      'access arguments' => array('access user profiles'),
      'access arguments append' => FALSE,
    ),
  ),


How can I include Guzzle as a library in a distribution? I'm working on Open Atrium 2 and we'd like to include Guzzle with the initial install so that we can build some integration features on top of it.

Usually, including a library just means adding the library to the drush make file, but Guzzle is more complicated because:

it has a few dependencies.
it's meant to be installed by Composer or Pear, not by direct download.
it's not on the packaging whitelist on Drupal.org, but I can request that it be added since the license doesn't conflict.

So how can I make this happen? Is there a pre-bundled-and-ready-to-use package somewhere that includes all dependencies, in which case I can just request that that be whitelisted for Drupal.org and use that? Or is installing Guzzle tricker than just including a bunch of files that can be placed in sites/all/libraries?

Any ideas?

I disabled composer system wide on my machine and create a make file and it works fine installing Drupal 7 core plus the following modules: composer, composer_autoload & guzzle.

This is the content of platform.make

$Id$

; API

api = 2

; Core

core = 7.x

; Drupal project.

projects[drupal][type] = core
projects[drupal][version] = 7.x
projects[drupal][download][type] = git
projects[drupal][download][branch] = 7.x

; Modules

projects[composer] = 1.x-dev
projects[] = composer_autoload
projects[] = guzzle


hook_views_pre_render - how to print field x after each loop I have a grouped view that displaces content containing multiple entity references. I have a field that generates multiple times, because of those entity references. I've looked into modifying views-view-group.html.twig with no luck. Now I'm trying to figure out how to use hook_views_pre_render to accomplish this.

(If it comes up... no, using 'Views Field View' didn't work)

I currently have results like this:

Group Title
 - Item one
   -- entity-ref1
   -- Field-x
   -- entity-ref2
   -- Field-x

I want this:

Group Title
 - Item one
  -- entity-ref-item1
  -- entity-ref-item2
  -- Field x

I've already got the hook set up in a module. I'm just trying to figure out how to use it to rearrange fields and output Field x - After the rest of each entry has output. I haven't found anything.

UPDATE: I tried this solution for removing duplicates - BUT.. it's removing the multiple entity references along with the multiple Field X. I just one Field X pared down to one:

    function webinar_rearrange_views_pre_render(\Drupal\views\ViewExecutable $view) {
      if ($view->id() == 'webinars') {
        $filtered_nids = array();

        foreach ($view->result as $key => $row) {
          if (in_array($row->nid, $filtered_nids)) {
            unset($view->result[$key]); // remove the duplicate
          } else {
            $filtered_nids[] = $row->nid;
          }
        }
      }
    }

This isn't the answer I was looking for, but it solves the issue until a better method is found.

Basically, the problem is that a specific field - a custom text 'find out more' field was showing three times (for example) when a row had three authors (entity ref. fields)

Since the 'find out more' field was the last item in each row, I overrode the "views-view-unformatted" twig template and, inside of the 'for' loop I added an extra bit, to change the class of the last item. Then, with CSS, I could hide the fields with 'views-row' class, and display 'views-row-last'

Here's what I added to that twig file:

    {% if loop.last %}
        {%
        set row_classes = [
          default_row_class ? 'views-row-last',
        ]
       %}

    {% endif %}


Combine subdomains into one domain I have main website ABC.com with 5 subdomains on Drupal 6.2

The problems I'm facing are bellow:1 - It is difficult for user content to migrate across the subdomains.
Detail: There are tabs on the top of USER PROFILE page for "My Content" and "My Images".
I was hoping that title links for all pages written by that user from all of the subdomains could be listed in that area
And also that all images from all subdomains uploaded by that user could go under "my images".

2 - Every time a change is made to the structure of the (site, taxonomy, blocks, configurations etc) the change has to be made on all 5 subdomains.currently we are doning indevidually.
Detail: Ideally, most of the administrative tasks should be implemented in a single change.
Things like content types, meta tag and post settings, taxonomy.
The structure of pages under site building, site configuration, user permissions.
All the things that make a site consistent in its look and function.

MAIN WEBSITE - ABC.com
SUB DOMAIN 1 - one.ABC.com
SUB DOMAIN 2 - two.ABC.com
SUB DOMAIN 3 - three.ABC.com
SUB DOMAIN 4 - four.ABC.com
SUB DOMAIN 5 - five.ABC.com

Database Structure:
There is only 1 database for MAIN site plus all 5 Subdomain with total 700+ tables.
MIAN website ie(ABC.com) tables doesnt' have any db_prefix.
ABC.com tables as follow:
- access
- accesslog
- actions
- users
    .
    .
- vocabulary
- watchdog

All sub domains have a db_prefix of subdomain with their table names like:
- one_access
- one_accesslog
- one_actions
- one_users
    .
    .
- one_vocabulary
- one_watchdog
- two_access
- two_accesslog
- two_actions
- two_users
    .
    .
- two_vocabulary
- two_watchdog

Any help would be appreciated.

Cheers
zafar

The Domain Access module was created for exactly the sort of use-case you're describing.

  The Domain Access project is a suite of modules that provide tools for
  running a group of affiliated sites from one Drupal installation and a
  single shared database. The module allows you to share users, content,
  and configurations across a group of sites such as:

  example.com
  one.example.com
  two.example.com
  my.example.com
  thisexample.com <-- can use any domain string
  example.com:3000 <-- treats non-standard ports as unique

It'll take a fair amount of work to convert 6 individual sites into a single Domain Access site, but if that's the workflow you're looking for, I don't think you'll find an easier or more complete existing solution.


Set Custom value in checkbox I have an array...

    $my_array = array(1 => 'Value One', 2 => 'Value Two',3 => 'Value Three');

In Form API, I want to create checkbox for each value.

    foreach($my_array as $key => $value) {
      $form['custom_field'] = array(
        '#type' => 'checkbox',
        '#title' => $value,
        '#default_value' => variable_get('custom_field'),
      );
    }

by default is stores in value, '0' or '1'.
It should actuly be saving the $key as value.

I know this can be done simply using 'type' as 'checkboxes' but actuly I need to goroup it each time each check box with a text field.

    foreach($my_array as $key => $value) {
      $form['custom_field'.$key] = array(
          '#type' => 'checkbox',
          '#title' => $value,
          '#default_value' => variable_get('custom_field'),
        );
        $form['custom_field'.$key] = array(
          '#type' => 'textfield',
          '#title' => 'Limit',
          '#size' => 10,
          '#maxlength' => 10,
          '#default_value' => variable_get('limit_variable'),
          '#required' => TRUE,
        );
      }

`
Any help?

You can try adding '#return_value':

foreach($my_array as $key => $value) {
      $form['custom_field'] = array(
        '#type' => 'checkbox',
        '#return_value' => $key,
        '#title' => $value,
        '#default_value' => variable_get('custom_field'),
      );
    }


Change HTML output of a view I have a view which displays products. The fields shown are altered via hook, and I want to add <div> and <h3>, when I find an appropriate field value. (I tried with adding style to the field in the UI, but the logic is somehow convoluted, so I would need to hard-code it.)

I need to encapsulate a complete row inside a <div> when some field has some value. I have tried with views-view-fields.tpl.php and views-view-unformatted.tpl.php, but they seem not to "talk to each other", so I am failing miserably. Maybe should I approach by using views_view_result() and building the HTML myself?

To theme/design the complete row, you need to use Style output template file.

Click on Theme: Information in your view, in pop-up see the last file in Style output section. Copy the name and create file with same name and save this file at sites/all/themes/YOURTHEME/templates.

Then click on Style output, copy the code and paste into the newly created file. In this file, you can add your own HTML display the result.

Hope this helps.

Thanks


How to hide the content of nodes/ completely, and still maintain use within Drupal? So, to start off, I've seen:

How do I hide nodes that shouldn't be directly accessed from users and search engines?
How to prevent access to Views-only content?
How can I restrict view pemissions to a node related child nodes?

All the answers to those questions make the proposal to make the node unpublished, which was the solution that looked cleanest to me, given that I was making some content types to be viewed exclusively with slideshows, i.e., having www.mysite.com/node/40 showing a list of all the raw images that make up my slideshow in a block elsewhere was not something I wanted. I only want the images viewable within the context of a slideshow.

However, when I followed these answers and made the content of the node unpublished, the content was inaccessible to the slideshow View: It was now blank to anonymous viewers. Is there something I missed in how to make a node unpublished, but still allow its contents to be accessed through Views, as a block?

I'm looking to do this without using the htaccess, hooks, or javascript options I've seen mentioned in the links above.

I can't imagine that having a list of content accessible nakedly under nodes/123 is actually an intentional feature.

One other qualification that makes this a tricky problem---there are ways of preventing access to node/123, but they can also hinder your own ability to create or edit nodes!

There are two Drupal modules that offer this functionality:

Rabbit Hole
Internal Nodes


Get data form into hook_node_insert / hook_node_update How to recover data from my form 'node' from the hook 'node_insert' or 'node_update'. Because I created a textfield and I can't see from the "$node" variable

The $node object will be populated with the data from the form, the way for form is defined.

You can do something like this

hook_form($node, &$form_state) {
  $form = array();

  $form['my_value'] = array(
    '#type' => 'textfield',
    'title' => t('Some title'),
    '#default_value' => isset($node->my_value) ? $node->my_value : '',
  );

  ....

  return $form;
}

Then get the value on the node object.

hook_insert($node) {
  $my_value = $node->my_value;
}


drupal 7.34 cannot rearrange form component and others I have a fresh installation drupal 7.34 the install module ctools views and webformm. I cannot rearrange the form component. Both weight and the + symbol appear. Normally in the previous version I can switch using weight or drag the component to rearrange. How can I rearrange the form components. This problem also in other similar list, such as menu.

Very lucky....,
I found the answer to solve the problem (related to missing misc/jquery.cookie.js) from  this discussion https://www.drupal.org/node/1052372

To solve that: Configuration > Development, enable Aggregrate Javasript file

Now it just works perfectly as in the previous versions. Thanks Drupal developers.


Webform Module or hook_form_alter() - What is right for me? I'm delving into my first custom Content Node Submission Form creation and looking at my first ever hook_form_alter() attempted efforts.
However, I'm confused over whether the WebForm module will do the job for me to allow user submission of new Node Content as I need to change the display of the said Node fields displayed. The way I read the WebForm documentation it's for emailed webforms and questionnaires, not really what I want but to submit new Node Content to the database, but others online say it can be used otherwise.

Would someone care to clarify before I waste another 2 hours effort?

Thanks in advance.

Webforms generally are best as contact/survey forms or some variant of them.

For an application like this, in my opinion it is just easier to implement your own form and do your own validation and submission. The validate handler could evaluate if the data is valid, and then the submit handler could create a new Node, set values, and save it.

Technically, you could do that submit Node creation handler with Webform, but it isn't as practical to me. Plus, if you haven't learned the Form API, this is a good opportunity to do so!

If this is Drupal 7, you could also take a look at Entity Forms and Rules, but again in my experience, getting to the goal is just faster with your own form or two and coding in what you want.


How to replace metatag description using views argument? I'm having trouble while trying to use views arguments for replacing metatags description.

In the view title you can easily add the view argument for example "Blog posts in category %1" so the "%1" is the first argument and it's replaced in the view title, but it does not work for metatags.

For example I want the description of the metatag to say "Blog posts about %1 in example blog"

Is there any way so that view argument works for metatags?

I found that in the available tokens for the metatags while configuring the view, I can access the url arguments with this token [view:url:args]


Flexslider carousel using template.php Views with flexslider takes lot of times in rendering items/images.

Situation is that I have more than 5 flexslider carousels on the front page.
So I changed to go without view with flexslider.

I am trying to use flexslider carousel using template file.
Due to flexslider.css, I am not able to see .slides>li .

See following lines:

.flexslider .slides > li {
    display: none;
}

Even not able to see any slider movement there. Somehow I tried according to https://stackoverflow.com/questions/7539542/trying-to-get-flexslider-jquery-slider-to-work-with-drupal

Can anybody help me to create flexslider without view or manage display?
I want to create using tpl files.

The common and very accepted way is to use a module and do everything from the UI:

I used Flexslider and it's a great module - If I remember correctly, you can use it's field display-option directly, without using Views. An "Instant" slider alternative could be the module "Content glider", but I'm not sure if it's responsive (the word responsive doesn't come up in the modules' page) so Better try the Flexslider field set first.

For better performance in slider image-replacement (and in general) you could try turning on Caching and Aggregation, and use modules like AvgAgg, Boost, and some others, it's a whole subject.


Drupal #ajax callback executing twice I am creating a custom paginator in Drupal 7.

The paginator is working fine, the only problem is that every time I click to the next page button, increases the step in 2 (For example I can see pages 0,2,4,6,etc...)and that's because the submit button is executed twice and increases the number of the page by two.

As you can see in the callback I use AJAX to replace two different sections on the page, and that might be the cause.

Any idea?

Submit function:

function club_paginator_form_submit($form, &$form_state) {
$values = $form_state['values'];

if ($form_state['triggering_element']['#value'] == '>')
{
    $form_state['values']['current_page'] = intval($form_state['values']['current_page'])+1;
}
else
{
    $form_state['values']['current_page'] = intval($form_state['values']['current_page'])-1;
}

$form_state['rebuild'] = TRUE;

}

Forms:
(...)

$form['next'] = array(
    '#name' => 'paginator-next',
    '#type' => 'submit',
    '#value' => t('>'),
    '#weight' => 5,
    "#ajax" => array(
        "callback" => "ajax_club_paginator_next",
        "effect" => "fade",
    ),
    '#prefix' => '
'.$page.'
',
    '#attributes' => array('class' => array('button')),
    '#submit' => array('club_paginator_form_submit'),
);

(...)

Callback:

function ajax_club_paginator_next($form, &$form_state)
{
    $page = intval($form_state['values']['current_page']);

    $html = '';
    $html .= '
';
    $html .= draw_clubes_page($page);
    $html .= '
';

    $paginator = '
';
    $form = drupal_get_form('club_paginator_form', $page);
    $paginator .= drupal_render($form);
    $paginator .= '
';

    return array(
        '#type' => 'ajax',
        '#commands' => array(
            ajax_command_replace("#club-paginator-content-replace", $html),
            ajax_command_replace("#paginator", $paginator)
        )
    );
}

I Finally found the error...

drupal_get_form was calling the submission again, I was creating a new form like the one I was substituing, but I was also updating the old.

Instead of creating a new form, I just used the $form variable instead of drupal_get_form.

Please find the new logic below!

function ajax_club_paginator_next($form, &$form_state)
{
    $page = intval($form_state['values']['current_page']);

    $html = '';
    $html .= '
';
    $html .= draw_clubes_page($page);
    $html .= '
';

    $paginator = '
';

    //Not Needed!
    //$form = drupal_get_form('club_paginator_form', $page);

    $paginator .= drupal_render($form);
    $paginator .= '
';

    return array(
        '#type' => 'ajax',
        '#commands' => array(
            ajax_command_replace("#club-paginator-content-replace", $html),
            ajax_command_replace("#paginator", $paginator)
        )
    );
}


How can I display all levels in Simple hierarchical select I created select hierarchy ( taxonomy with 3 level), but in default it shows only one level , how can I display all 3 level in default page? : -Any- + -Any- + -Any-

I do not want it to automatically generate other fields.I want to display by default all the select input

I had the same problem and found the answer was to create a custom module and not use SHS. Here's how I did it with Drupal 8 ... and some info on how done with D7: https://drupal.stackexchange.com/a/269296/18513


How to translate a node in a custom block? I know that the question has been asked several time but I didn't find how to get the translation of a node entity.

Here is the code :

    $countries = \Drupal::entityTypeManager()
        ->getStorage('node')
        ->loadByProperties($properties);

    return [
      '#theme' => 'country_selector_block',
      '#langcode' => $lang->getId(),
      '#countries' => $countries,
    ];

And in the twig template I put :

{% for country in countries %}
    <option value="{{ country.field_code.value }}">{{ country.title.value|t }}</option>
{% endfor %}

=> but it return the country name in the default language

Can you explain how to handle that ?

You need to pass the loaded nodes/countries through the following so that Drupal marks the best available translation as active, then do not use t() in the template. That is a security risk, you must never pass user input to t().

$country = \Drupal::service('entity.repository')->getTranslationFromContext($country).

Do that in a loop on $countries for example, or use array_walk()/array_map().


Using VBO to change users passwords I need a method of changing users passwords which doesn't require email, as such the best solution I can come up with is providing "manager" roles the ability to reset passwords. However we do not want to provide these users with "administer users" permission.

I am thinking the best way of doing this is a view which displays "my team" (uses a user reference on that managers direct reports.) and uses views bulk operations however I can not find anywhere documentation on how to reset users passwords.

Ideally the VBO action would allow managers to select members on their team and reset passwords to a string, then update the user in person.

Userplus has an action which changes a users password, I was able to use the below:

/**
 * Implementation of hook_action_info().
 */
function userplus_actions_action_info() {
  $actions = array(
    'userplus_change_password_action' => array(
      'type' => 'user',
      'description' => t('Change user\'s password'),
      'configurable' => TRUE,
      'hooks' => array(),
    ),
  );
  return $actions;
}

/**
 * Action to change a user's password
 */
function userplus_change_password_action_form($context) {
  _user_password_dynamic_validation();
  $form['pass'] = array(
    '#title' => t('New password'),
    '#type' => 'password_confirm',
    '#description' => t('Provide a password for the selected users in both fields.'),
    '#required' => TRUE,
    '#size' => 25,
  );

  return $form;
}

function userplus_change_password_action_submit($form, $form_state) {
  return array('pass' => $form_state['values']['pass']);
}

function userplus_change_password_action(&$user, $context) {
  user_save($user, array('pass' => $context['pass']));
}


How to change the teaser for the front page articles In my site : http://www.indiacustomercare.com  front page(which is not displaying correctly) I want to show 200 words in teaser for each article.
I've changed it in Post Settings but does not work.

What could be the reason?

You need to Edit and Save again the articles to take effect.

I know can be painful if you have hundreds of nodes. If you google about it you will find scripts to do it like this
http://befused.com/drupal/script-update-drupal-teasers

Or use the module retease http://drupal.org/project/retease

I advice you to take a database dump before testing these solutions, just in case.


What is the right way to force a session start? I'm currently porting SimpleFBConnect module to Drupal 8. This module uses Facebook PHP SDK which expects that we have established a session before the user is redirected to Facebook for authentication.

By reading SessionManager API, I assumed that SessionManager::start would start the session. However, this does not seem to be the case. The same thing applies to SessionManager::save (description says that this function will "Force the session to be saved and closed.").

The only way how I was able to force a session start was to call SessionManager::regenerate.

Is this the correct way to force session start in Drupal 8?

Debug code, which will show that SessionManager::start will not start the session.

class TestController extends ControllerBase {
  public function test() {
    $session_manager = Drupal::service('session_manager');
    $session_manager->start();

    if ($session_manager->isStarted()) {
      $msg = 'Sesssion started';
    }
    else {
      $msg = 'Sesssion not started';
    }

    return array(
      '#markup' => $msg
    );
  }
}

Okay, found the answer from this change record: https://www.drupal.org/node/2228871

The session can be force-started like this:

// Force session start if we don't already have a session.
$session = \Drupal::service('session');
if (!$session->isStarted()) {
  $session->migrate();
}


User suddenly logged in as another user I face new problem in my site, we have reports from users that when they are surfing our site with their account, suddenly logged in as another user and continue surfing site as it.

I searched all modules for below patterns to find where global $user changed by mistake but found nothing.

$user->uid =
$user =
->uid =

Is there any suggestion about this issue?

I am sure that there is developer mistake here, we have something like  you guested,a global $user information  overwrite by developer code,I suggest you found when this happened,when a comment submit?when a specified form submit and .... ?
I think in custom module your developer first  write global $user; and in continue define $user variable,I suggest you search for global $user then look at afterwards codes.


Moving a number of fields into a table on D7 node form I have a form with three field groups, arranged as horizontal tabs.

On one of these tabs, I have twelve fields. For eight of these fields, I would like to arrange them inside of a table.

These fields are date popup fields.

Each of the fields has its label removed; I'm just trying to have a table where the field labels are in the header and the actual  tags are inside the table rows.

I'm using the code below to remove the labels (it was difficult to figure out, so if anyone can use it)

However, I'm not yet sure how to then place the resulting fields into a table format.

My first thought was a theme function for the entire form, but how would I insert the table into one of the tabs? drupal_render() would not work for that.

Will I just have to go through each item individually?

Thanks for your help.

<?php
function MYMODULE_form_recruitment_process_node_form_alter(&$form, &$form_state, $form_id) {
    $date_fields = array(
        'field_special_1',
        'field_special_2',
        'field_special_3',
        'field_special_4',
        'field_special_5',
        'field_special_6',
        'field_special_7',
        'field_special_8',
        'field_special_9',
        'field_special_10',
    );

    foreach ($date_fields as $field_name) {
        $form[$field_name][LANGUAGE_NONE][0]['#title_display'] = 'invisible';
    }
}

function MYMODULE_element_info_alter(&$type) {
    if (isset($type['date_popup'])) {
        $type['date_popup']['#process'][] = 'MYMODULE_date_popup_process';
    }
}

function MYMODULE_date_popup_process($element, $form_state, $complete_form) {
    // Get the field name and create an array of fields we want to change.
    $field_name = $element['#field']['field_name'];
    $valid_fields = array(
        'field_special_1',
        'field_special_2',
        'field_special_3',
        'field_special_4',
        'field_special_5',
        'field_special_6',
        'field_special_7',
        'field_special_8',
        'field_special_9',
        'field_special_10',
    );

    // If it's not the field we want, return it unchanged.
    if (!in_array($field_name, $valid_fields)) {
        return $element;
    }

    $element['date']['#description'] = "";
    $element['date']['#title_display'] = 'invisible';
    $element['time']['#descsription'] = "";
    $element['time']['#title_display'] = 'invisible';

    return $element;
}

There is an API that will allow you to alter the output of the field group or write your own field group handler. https://www.drupal.org/node/1017962

Using this you could write a custom field group handler that loops through the fields and outputs the data using theme_table(). This would allow for you to grab the field label and add it to the header array, and then add the fields to the the data array.

After creating your custom field group you can nest the field group under the horizontal tab and nest your fields under the custom group.


Boost module's "Cache every page except the listed pages" option I use Boost 7.x.
I couldn't use "Cache every page except the listed pages" option.
If i leave the textarea (of exclusion of some pages) everything works well.

In "/admin/config/system/boost" it is written like this:

  Specify pages by using their paths. Enter one path per line. The '*' character is a wildcard. Example paths are blog for the blog page and blog/* for every personal blog. <front> is the front page.

When I add the allowing lines, Boost breaks to cache files.

content/my-alias-1
content/my-alias-2

Am I using the wrong format for writing those lines?

I know this question is moldy old bread, but I wanted to answer for future searchers.

If a page has been cached by boost and then you exclude it, the cache will need to expire or be manually cleared before the exception will be used.

This is probably why you were still seeing the cached page when you added an excluded page.


Multiple regions in a zone with different widths I am using Omega / Delta / Context on my local environment and created a sub-theme with omega-tools. I want to add more regions to the footer section. I want the regions to be similar to that of Postscript One-to-Postscript Fourth.

Im not sure if ill be able to explain well in words, hence i have taken screen-shots of what i intend to do and what am i doing to get it and the output. http://pho.to/2qA1P (Sorry for the external link, i don't have enough reputation yet to share more images)

How do i want the layout:
I want the regions Footer Links One, Footer Links Two, Footer Links Three, Footer Links Four to appear between: Footer First and Footer Second.
In this order:

    Footer Zone        Column Count: 12 Cols
    Footer First       Width : 12 Cols
    Footer Links One   Width : 3 Cols
    Footer Links Two   Width : 3 Cols
    Footer Links Three Width : 3 Cols
    Footer Links Four  Width : 3 Cols
    Footer Second      Width : 12 Cols
    Footer Zone

and i have accordingly changed the region Weights and Widths in above regions, under Zone Configuration.

However, in the actual result the Footer Links regions are not displayed within Footer First and Footer Second regions.

Strangely, when i created a Delta and applied it to a Path with Context, i get the output exactly as i intended.

Please help me on how to fix this.

Alternatively, i was thinking to get Footer Link regions under a separate Zone and place 2 new zones above and below this zone with regions Footer First and Footer Second. Not sure if this is the correct way.

Kindly help. Thanks.

This issue has been resolved.

What i did to resolve the issue:

I had to setup the Zone in the sub-theme settings first. So i went to the sub-theme settings and assigned Weights from 0-5 for Regions Footer First uptil Footer Second.

Once this was done, the changes were reflecting properly.


How to determine taxonomy vocabularies related to a specific content type in Drupal 8? could anyone help me please, how to get the vocabularies to a given content type? For example in older Drupal cores there was a taxonomy_get_vocabuleries($type) function(https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/function/taxonomy_get_vocabularies/6), but I didn't find anythink similar solution in D8.

Thanks a lot!

In Drupal 6, this was configured per vocabulary, which had settings for which node type they should be displayed.

Since Drupal 7 already, this is handled through fields, a term reference field from a node type to a given vocabulary. The UI doesn't allow it, but a term reference field can also allow terms of multiple vocabularies.

So, if you want to know, you need to load term reference fields of that node type and then filter them by their allowed values setting. That said, the concept of "vocabulary of a given node type" simply doesn't really exist anymore, as there are other ways too, you can for example use an generic entity reference field too for term relationships. (In fact, there was an attempt to replace the term reference field completely in 8.x, but that was not successful so far).

Untested, but you need something like this:

$vids = array();
foreach (\Drupal::entityManager()->getFieldDefinitions('node', $node_type) as $field_definition) {
  if ($field_definition->getType() == 'taxonomy_term_reference') {
    foreach ($field_definition->getSetting('allowed_values') as $allowed_values) {
      $vids[] = $allowed_values['vocabulary'];
    }
  }
}

You can figure out most of this if you look at TaxonomyTermReferenceItem and how it is defining and using it's own settings, for example in getSettableOptions().


How can I center a views slideshow? I have setup a views slideshow, but is anyone able to help me with centering the images in the middle of the slideshow? Some images are not very wide and they are aligned to the left of the slideshow. I would like all images to be in the center to make it look better.

The site I'm working on is here

I have tried adding the following codes to my css but none of them work:

.views-field-field-image-fid img { border-style:solid; border-width:1px; display:block; margin-left: auto; margin-right: auto; position:relative; text-align:center; }

and

.views-field-field-slideshow-image {
     display:block;
     margin-left:auto;
     margin-right:auto;
}

I still cant seem to get it working, I've tried a few other css selectors that I found online as well. Im new to drupal views and quite new to Drupal.

Thank you.

You need to use image styles to get all the images the same size.

From the admin menu, Configuration > Media > Image styles.

Create a new image style, with a scale and crop attribute to the exact dimensions for your slideshow. Name it "slideshow-image".

Then go back to the slideshow settings on your views slideshow, and select "slideshow-image" as image style.

Now every image will be the same width and height, regardless of the dimensions you upload them in.


Display POA in Ubercart 3 / D7 for products of zero dollars I'm building an ecommerce site where some products are price negotiable and want a way to add POA instead of a listing a price when a product is displayed.

I'm kinda surprised at how hard this is to do.. I have a snippet that works for Ubercart 1 in Drupal 5, but it looks like the hooks have changed in Ubercart 3 and I can't find a pricing hook:

    <?php
function zen_uc_product_display_price($price) {
  $output = '
';
    if ($price!=0) {
      $output .= uc_currency_format($price);
    } else {
      $output .= t('P.O.A');
    }
  $output .= '
';
  return $output;
}
function

zen_uc_product_sell_price($price, $teaser) {
  if ($teaser) {
    $output = '';
        if ($price!=0) {
            $output .= uc_currency_format($price);
        } else {
            $output .= t('P.O.A');
        }
    $output .= '';
  }
  else {
    $output = '
';
        if ($price!=0) {
            $output .= t('Price: !price', array('!price' => uc_currency_format($price)));
        } else {
            $output .= t('Price: P.O.A');
        }
    $output .= '
';
  }
  return $output;
}
?>

I've managed to hook the add to cart function and direct it to a webform with the following snippet:

<?php

function fmc_uc_product_add_to_cart( $variables ) {
$sell_price = $variables['form']['node']['#value']->price;
if ($sell_price <= 0) {
return '<form action="http://www.example.com/" method="post"><input type="hidden" name="product" value="' . drupal_get_title() . '" /><input type="submit" class="form-submit" value="' . t('POA') . '" /></form>';
}
else {
return fmc_uc_product_add_to_cart($variables);
}
}

But I'm having no luck with the pricing function, if anyones got a code snippet I can run in my template.php file that'd be the ideal solution, but any ideas / advice is hugely appreciated. Is there a way this can be broken out inside a node--product.tpl.php file maybe?

I have not tried this out but I would think you could override theme_uc_price() in your template.php something like this:

function THEMENAME_uc_price($variables) {
  if ($variables['price']) {
    $output = '' . uc_currency_format($variables['price']) . '';
    if (!empty($variables['suffixes'])) {
      $output .= '' . implode(' ', $variables['suffixes']) . '';
    }
  }
  else {
    $output = t('P.O.A');
  }
  return $output;
}


Create language locales in D8 I am attempting to create/enable the UI to allow users to create translations in D8, and I need to create locales (e.g. en-us, en-gb, en-ca for English, es-mx, es-es for Spanish, etc). I've gone through the directions I've been able to find, and I am not seeing where to add specific locales after adding the base languages (at admin/config/regional/language). Or in the Translate tab on content items. Where do I go to enable specific locales?

To use locales separately, each has to be added as a custom language.

/admin/config/regional/language/add
Choose Custom language.
Enter the locale that you want as the Language code.
Enter the Language name.


How to pass cookie value into Drupal View We want to create some logic using JS that creates a cookie and set the node's taxonomy term id (preferred) or taxonomy term name as the cookie value. Then we want to use the cookie value to filter a View so that when a user visits a page, the view that is shown is filter based on the cookie value.

How can I pass a cookie value into the View?

/******************** Update - 9/23/2015 **************************/

I ended up using a mixture of a list block, javascript, and a custom module that on full node view, the taxonomy term id is stored into the browser's locale storage. I am no longer using a filter view based on cookie. Also, the custom module stores the taxonomy term ids into the block.

On May 26th 2011 a new EU originated law came into effect that requires website owners to make significant changes to their sites and may fundamentally change the whole web browsing and shopping experience for everybody.This Cookie Law is amended privacy legislation that requires websites to obtain informed consent from visitors before they can store or retrieve any information on a computer or any other web connected device.

Cookie Control does just that, presenting users with clear information on whether cookies are present, linking to your privacy policy (where you should have specific information about what cookies are in use), and advising users on how to adjust browser settings and what cookies mean for them.


Views: Is it possible to Group "exposed" filters in a  and add css to it? In Drupal 7, I have a Views which contained "content: ID", "Content: Type", "Content: Title", "Content: Organization", Conent: City", "Content: State" and "Date: Date(node)". They are all exposed. How can I group them into 3  groups(the group in rearrange only give the feature to add "and" or "or" group), so I can add CSS and make them as an expandable list. Is it possible?

Exposed filters appear in a form so you have to use hook_form_alter
as well as hook_theme to theme any form.

Using hook_form_alter assign a new theme to that particulat form.
hook_theme is usead for register a new theme.

For more information about form theming visit here


Making both Site name & Site slogan to be one single link in mini-panels I use the Mini Panels module and have created an header with both Page elements "Site name" & "Site slogan".

The Site name (H1) is a clickable link that leads to the home page, but the site slogan (H2) is just a text that links nowhere.

Can I make both of them a single link to the homepage (but still keep them different elements with different CSS, etc)?

I see three options that I think you could do.

Update the content in the theme layer which you can try to check in this page and it's other related pages. https://www.drupal.org/node/1678810
Use panel pane hooks to add additional settings for the Site Slogan panel pane.
Create a custom panel pane


Strange debug prints appear in the system log I have two Drupal 7 sites on an Apache server that are printing strange debug messages in a system log. The sites are set in their vhost config to use error logs within each local site folder, like the following.

/var/www/site1.com/log/errorlog
/var/www/site1.com/html/[drupal installation]
/var/www/site2.com/log/error.log
/var/www/site2.com/html/[drupal installation]

These error logs are fine and happy, but I am seeing a large number of entries in /var/log/messages. These debug lines look like the following.

  Feb  5 08:51:56 server012 drupal:
  http://site1.com|1391619116|form_debug|5.10.83.11|http://site1.com/eform/submit/apply-for-a-program?pid=127||0||Array#012(#012
  [#parents] => Array#012        (#012        )#012#012    [#entity] =>
  Entityform Object#012        (#012            [uid] => #012
  [entityType:protected] => entityform#012
  [entityInfo:protected] => Array#012                (#012
  [label] => Entityform#012                    [entity class] =>
  Entityform#012                    [controller class] =>
  EntityformController#012                    [base table] =>
  entityform#012                    [fieldable] => 1#012
  [entity keys] => Array#012                        (#012
  [id] => entityform_id#012                            [bundle] =>
  type#012                            [revision] => #012
  )#012#012                    [bundles] => Array#012
  (#012                            [apply_for_a_program] => Array#012
  (#012                                    [label] => Apply for a thing
  or Ask a Question#012                                    [admin] =>
  Array#012                                        (#012
  [path] => admin/structure/entityform_types/manage/%entityform_type#012
  [real path] =>
  admin/structure/entityform_types/manage/apply_for_a_program#012
  [bundle argument] => 4#012
  [access arguments] => Array#012
  (#012                                                    [0] =>
  administer fields attached to entityform entities#012
  )#012#012                                            [original access
  arguments] => Array#012
  (#012

  Feb  5 08:51:48 server012 drupal: http://site2.com|1391619108|content|90.8.28.253|http://site2.com/fr/node/2/edit|http://site2.com/fr/node/2/edit|44|voir|page: updated Qui sommes nous?.

I've just been informed that /var/log/messages is linux "syslog".

Why is Drupal printing to syslog?
Is this normal behavior?
Is there a setting to enable/disable syslog output?

That is what the Syslog module that comes with Drupal does. It is not enabled by default, but enabling it will cause what you are noticing.
The module doesn't have its own settings to disable logging the messages into the system logs; to stop that, just disable the module. Since you are not going to use it anymore, you can then uninstall it. (Don't delete its files, since they are copied every time you update Drupal.)


Newsletter content aggregation I'm using the Simplenews module for creating newsletter and I would like to know if it's possible to aggregate different newsletter content into only one for the same subscriber.
For example, one person subscribes to 3 different newsletters on the same website and receives only one newsletter containing the 3 content of those three newsletters.

No, you can't do that with the current version of simplenews.

Some alternatives:

Use Mailchimp integration and create segments, groups, then use conditional merge tags (http://kb.mailchimp.com/article/all-the-merge-tags-cheatsheet#Conditional)
You could hack the simplenews module, but that is more shaky... Using the simplenews scheduler and the simplenews content selection module you could patch up a solution.
The newsletter module might be the best platform to do this as they are active and you might find people who want to collaborate. Also the architecture is more generic.

For the moment I will use #1, but in the future I will probably have to implement a neater solution with #3.


Calling another function using drupal_get_form How can I call a function using drupal_get_form when a submit button is clicked. My situation is that i have a custom module where there is only a submit button. So when that submit button is clicked I want to call a particular function. How can I achieve it through drupal_get_form.

$form['#submit'][] = 'myform_form_submit';

You can call your function as above. Or

function myform_form_submit($form, &$form_state) {
  //execute your function here
}


How to limit drupal cron CPU usage? when cron is running, apache PID peaks, and blocking the server response. is it possible to limit the cron CPU usage and leave some headroom for HTTP requests?

You can use this module elysia_cron  Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

Elysia cron is usually used in large sites that needs performance optimization.


No access stats for user after registration Just noticed a new user who joined today has in access stats, "never". How can that be recording never when they have logged in? drupal 7.19 core profiles.

Usually a state "never" means that the user has registered but they have never logged in with their username/password


Print Term ID in block on Term page? I have a block that displays on term pages. I need to print the term ID in this block.

I can see the term in the url (if I turn off pathauto) is something like this: mysite.com/bslb22/taxonomy/term/3

So is there some php that can get the ID from the url? Thanks

Use this:

// Make sure we are on the term page
if (arg(0) == 'taxonomy' && arg(1) == 'term' && arg(2)) {
  print arg(2);
}


Where is the parent/child relationship between nodes stored in the database? I am migrating a site from one CMS to Drupal and I'm working on migrating link structures over correctly. This is something I am going to have to automate because there are over 3,500 nodes of content that I am migrating over.

I can't seem to find in Drupal 8's database schema where the relationship between parent and children nodes are stored. I have been looking for something like a 'pid' or a 'cid' column (parent id and child id, respectively), but I can't seem to find a column like that in the schema.

I know you can make nodes children of other nodes, so I know it has to store this information somewhere. If someone could tell me what table and column this information gets stored in I would greatly appreciate that.

Drupal 8 Database Schema

The simple answer is, there is none.

Nodes in Drupal does not have a hierarchy, it's other things on top of it that allow you to do that, depending on the use case:

Menu links: You can have menu trees and each points to a node, but the nodes themself don't really about that. Some parts might look like it does, e.g. breadcrumb but that is simply based on the path.

Book module: This allows to create a book (basically a hierarchic structure of nodes), but this only makes sense for specific cases, e.g. structured documentation that has chapters and so on.

References: In many cases, nodes are just connected between each other with reference fields, which you could make look like a hierarchy.

Taxonomy: You can have Terms with a hierarchy and reference those from nodes, but again by default that doesn't give you anything hierarchy-like unless you start to combine with with path aliases or so.

=> Content in Drupal is very different from how most other sites handle it and you can't just convert it 1:1.


Using Contextual filter in Filtering attached view Suppose I have these two node types, with the following fields:
Port
Name
Description
Voyage
Name
Port1
Port2
Port3
I used References to link the port fields in Voyage to the node ID of the Port nodes.
Now, in the page of any port node, I need to attach a display of voyages names that has calls to that port. How can I achieve that in Views with EVA?
Or to put it logically: "SELECT Name FROM Voyage WHERE (port1 = (urlid) or port2 = (urlid) or port3 = (urlid));" urlid is the ID of the port we are getting through the argument (contextual filter).
I have used contextual filter, but there seems to be no way to use OR in contextual filters...

The contextual filters belong to the first filter group so if you click the little arrow besides the Filter "add" then choose "and / or" then you can switch the operator of the first group to OR.


Can't place context-controlled block below user picture on user profile page I have a views block of user content that I want to display on the user profile page below a custom generated block of user information created in code via a theme function (using the $build['user_picture'] element in hook_entity_view_alter().  If I place the block into the appropriate region using the blocks admin page and configure the block to only appear at user/*, it works fine. However, if I place the block using Context module with the User Profile condition, it places the block above all other content, and there seems to be nothing I can do to drop the block below the user_picture element.  The weight for the user picture element is set to -10 by default, but even if I make it lower, nothing changes is.

Is there a way to control the placement of the block via Context so it is below the user_picture element? I can see no way via the UI - either for Context or user profile configuration - or code. Do I have to override user-profile.tpl.php and manually split everything out? I need to use Context to be able to control which user profiles the block is on, so if I can't re-order, then I have to find another mechanism (probably Panels) to control this placement.

Thanks.

The weight for the user picture element is set to -10 by default, but
  even if I make it lower, nothing changes is.

The default weight for system content is 0, so display below that you would want a weight of 1 or more for your block in Context > Reaction > Block (if I'm understanding your issue correctly).


Programmatically build module permission list I'm defining a few new roles in the install hook of my module and one of them is an "admin light" role, which will need some, but not all of the admin account permissions.

I need to pragmatically build a list of available permissions from a pre-defined list of modules (User, Node, Toolbar, etc) and assign them to the role. Without having to hard code all of the permission strings.

In Drupal 7 I could do something like:

$modules = array( 'user', 'node', 'toolbar' );
foreach( $modules as $module) {
 $permission_hook = $module . '_permisson';
 if( module_exists( $module ) && function_exists( $permission_hook ) ) {
  user_role_grant_permissions( $rid, array_keys( $permission_hook() ) );
 }
}

I'm struggling to find an solution as neat for Drupal 8 seeing as hook_permssion has been removed in favor of $module.permission.yml. Is there something I'm missing?

EDIT: Final Solution:
This is the final implementation, just in case anyone else need to do this:

  // Define our new roles
  $roles = array(
    array(
      'id' => 'mymodule_client',
      'label' => 'Client',
      'mymodule_permissions' => array(
        'view project status reports',
      ),
    ),
    array(
      'id' => 'mymodule_agent',
      'label' => 'Agent',
      'mymodule_permissions' => array(
        'view projects',
        'view project status reports',
      ),
    ),
    array(
      'id' => 'mymodule_agent_manager',
      'label' => 'Agent Manager',
      'mymodule_permissions' => array(
        'view projects',
        'administer projects',
        'view project status reports',
      ),
    ),
    array(
      'id' => 'mymodule_employee',
      'label' => 'Employee',
      'mymodule_permissions' => array(
        'view projects',
        'administer projects',
        'view project status reports',
        'view project financial reports',
      ),
      // Assign all permissions for the listed modules to this role
      'provider_permissions' => array(
        'user', 'node', 'toolbar'
      ),
    ),
  );

  // At the default level all roles should have the same permissions as authenticated users
  $permissions = Role::load( Role::AUTHENTICATED_ID )->getPermissions();
  // Get permissions for all modules and add them to an array keyed by the module
  $provider_permissions = array();
  foreach( \Drupal::service('user.permissions')->getPermissions() as $key => $permission ) {
    $provider_permissions[ $permission['provider'] ][] = $key;
  }
  // Lets loop our new permissions and create them
  foreach( $roles as $role_values ) {
    // Merge our modules bespoke permissions with the authenticated role permissions
    $permissions = array_merge( $permissions, $role_values['mymodule_permissions'] );
    // Remove our module permissions before we create the role
    unset( $role_values['mymodule_permissions'] );
    // If the role needs access to other module permissions merge them in
    if( isset( $role_values['provider_permissions'] ) && is_array( $role_values['provider_permissions'] ) ) {
      foreach( $role_values['provider_permissions'] as $module ) {
        if( array_key_exists( $module, $provider_permissions ) ) {
          $permissions = array_merge( $permissions, $provider_permissions[ $module ] );
        }
      }
      // Remove the module_permissions before we build the role
      unset( $role_values['provider_permissions'] );
    }
    // Create the role
    $role = Role::create( $role_values );
    // Assign all the required permissions
    foreach( $permissions as $permission ) {
      $role->grantPermission( $permission );
    }
    // Save the role
    $role->save();
  }

This code uses the authenticated role as a base, then adds our module permissions (defined per role), and then adds any other modules permissions to roles that require them.

You can list all available permissions with PermissionHandler:

$permissions = \Drupal::service('user.permissions')->getPermissions();

You'll find the module name in the provider property of the permissions:

$permissions_by_provider = [];
foreach ($permissions as $key => $permission) {
  $permissions_by_provider[$permission['provider']][] = $key;
}


embed photo album hosted on flickr.com using flickr module not showing photo album I am attempting to use the Flickr module  flickr-8.x-1.0-alpha2 along with Flickr API and Colorbox module to display a album of recent photos from  Flickr.com.

I have setup the API keys. and added flickr setings in Text formats and editors, but the it doesnt producing any output for the photoset.

However its working for single  [flickr-photo:id=3711935987].
and when i tried with [flickr-photoset:id=72157626766436507] for photo album its not working .
 giving error in the Flickr module Notice: Undefined index: in Drupal\flickr\Service\Photos->photoGetSize();

does i miss any settings ?

It's likely you have photos in that set that aren't available in the size you've set the photos to display in.

Flickr module documentation > Sizes

  TAKE CARE, the c (800px) size is missing on Flickr images uploaded before March 1, 2012. Check if it exists on the Flickr photo page > Actions > View all sizes.

More info and debug inspiration in the 7.x documentation: Flickr Editor Guide 7.x-1.7


Auto-suggest products based on tags I am interested in autosuggesting products based on the tags an article contains which is read by a user.
How can I accomplish this with Drupal/Drupal Commerce?
thanks

I'm not entirely sure which one better fits your use case:
This blog post has an excellent way to accomplish product suggestions using the Radioactivity module.  http://www.wunderkraut.com/blog/drupal-commerce-product-suggestions-with-radioactivity/2013-08-22

There is also the Commerce Recommender module:  https://www.drupal.org/project/commerce_rec.
Again, I'm not sure if that is precisely what you're after.

A really straightforward way I could see is create a commerce product view that filters down to only products with the same taxonomy terms on the current article, create a block to hold that view, and display those products with/without their Add to Cart buttons.


Custom entity translation interface I created a new custom entity using drupal console, I enabled translation and all looks ok in code.

The problem is that I don't know how to translate an entity from the admin interface, I don't see any options to do this. I looked through the generated files and I don't see any translation related functionality there.

Am I missing something? Should I build my own admin interface and logic to manage translations?

I've missed configuration at admin/config/regional/content-language :|


Is it possible to use an image in my themes directory as the default image of an image field? This question addresses how to add an image using a URL rather than a direct upload using the filefield sources module.  However, that module does not allow the "Default image" to be set.

For my image field, I want users to only be able to upload files (just the way Drupal comes by default).  However, I want the default image to be stored in my themes directory if possible in order to ease deployment across multiple sites.  Is there a way to set the default image to an image on the server rather than having to upload it?

I'm using Drupal 7.

You could make a module whose sole purpose in life is to copy an image into the appropriate place in the file system. Then it would be in code and versionable, independent of what you did with the theme.