Undefined variable "hide_site_name" I am having great difficulty in trying to create my own theme. The errors that persist are:

  Notice: Undefined variable: hide_site_name in include() (line 98 of C:\wamp\www\drupal7\sites\all\themes\ppro8\templates\page.tpl.php).
  Notice: Undefined variable: hide_site_name in include() (line 108 of C:\wamp\www\drupal7\sites\all\themes\ppro8\templates\page.tpl.php).

I copied all files from the bartik theme into /sites/all/themes/myTheme/, and did the following:

I changed bartik.info into myTheme.info, and 'name = bartik' to 'name = myTheme'.
I replaced all occurrences of 'bartik' in templates.php to 'myTheme' (search and replace with notepad++). Up to this stage, the error still shows, so I tried the following as well:

I replaced all occurrences of 'bartik' in all files in the folder 'myTheme'

However, none of the above steps could remove the errors.

Could anyone please shed some light on this issue?

I had exactly the same problem here and complete system cache clearing helped me out.

  Configuration -> Development -> Performance -> Clear all caches.

That solved the problem for me.

See: Undefined variable: hide_site_name in include() while change theme


How to change default query plugin for views? By default Views uses 'views_plugin_query_default' plugin.
How can I alter something so that Views could use another class for building queries?

I found one good example how to write Views query plugins:
building views query plugins

But this example is for custom tables. But I need to have my own query builder for ordinary node, terms and users tables.

Firstly you will need to have defined your query plugin to Views using hook_views_plugins():

function MYMODULE_views_plugins() {
  return array(
    'query' => array(
      'myplugin' => array(
        'title' => 'My custom plugin',
        'handler' => 'MyCustomQueryClass',
      ),
    ),
  );
}

Then, you should be able to override the query class used for any of the built-in tables using hook_views_data_alter() and setting the query class key in the table base property:

function MYMODULE_views_data_alter(&$data) {
    $data['node']['table']['base']['query class'] = 'myplugin';
}


unsetting field via view hooks no effect on aggregation results I have created a view, with some aggregation parameters.

I expected that unsetting (removing) the aggregation field via some view hook (views_pre_render?) would do the trick to disable the aggregation caused by this field.

But it just removes the field from the table, the results are the same (aggregated by the unsetted field, even if it is removed).

some ideas? thanks

with pre_build worked fine and the aggregation disappears.

function views_test_views_pre_build(&$view) { unset($view->field['my_field']); }


How to extract images from Statuses(Facebook style publisher) and display in seperate page? I am using statuses module in my project which is working fine for my requirement. but my new requirement is, i need to extract the user posted pictures(not user profile pictures) in statuses module and need to display in new page along with the author of images posted. If images are more than one it should shown like album or some slide show.

I am not sure if it's related to the statuses module at all. It seems it can be a very different story, unrelated to that module. One easy way is to use bridges like janrain (rpx).


Link to a different view mode from entity reference Created a entity reference field i CONTENT A and linking it to CONTENT TYPE B. It works fine and takes me to the linked FULL CONTENT. Is it possible to link it to a different view mode like a TEASER or other view mode.

a link: /some/somthing/here is just a link. It resolves to a resource on Drupal (see hook_menu).

A node by default lives at the url node/NID which shows the full view mode. You need Views, a Context, a Panel -- and a different url then node/NID to show a different view mode.

So yes ... you can make a different url to show a teaser. How you make the url is up to you.


How do I enable Backlinks View and What Links Here? We used the backlinks view in D6, as well as the What Links Here tab for each node.

We're now using Commerce Kickstart 2. I don't see that View and it appears that the search_node_links table is empty.

Is this disabled because Commerce Kickstart uses the SOLR search in place of the default Search? If so, is there a way to have both the SOLR search -and- the backlinks as well?

Were you using Reverse Node Reference? Now in Drupal 7, you have reverse references available to you in views:

So you can use those relationships to go and load other content from one base content type (e.g. list blog posts or other products that reference this node or product).

Ideally, though, you might use EVA or or Views Field View to attach a view to an entity via a field. That view would use a base of whatever type of content or entity you were wanting to display, and then you'd just a contextual filter to limit it based on the field that references it.

Secondly, Commerce Kickstart doesn't use Solr out of the box, but it does use Search API. You can use Search API with Solr but faceted search and regular search do not require Solr. You can have Solr index entityreference fields and Views can use them, but all that does is change which checkbox you select in your Views config and not how you actually create the View.


Why do I get a "Unauthorized" error even though the user is logged-in? I am trying to programmatically log in a user in a custom module.

The code I am using in mymodule.module is the following.

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_login_block' || $form_id == 'user_login') {
    $form['#validate'] = array('user_login_name_validate', 'mymodule_login_validate', 'user_login_final_validate');
  }
}

function mymodule_login_validate($form, &$form_state) {
  global $user;
  $username = $form_state['values']['name'];
  $password = $form_state['values']['pass'];

  $ch = curl_init();
  curl_setopt($ch,CURLOPT_URL, "http://localhost/MYAPI/oauth/authenticate");
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS,"username=" . $username . "&grant_type=password");
  curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Authorization:Basic xxxxxxxxxxxxxxx"));

  // receive server response ...
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $server_output = curl_exec ($ch);
  curl_close ($ch);
  $postData = drupal_json_decode($server_output);
  $count = db_query("SELECT COUNT(*) FROM {users} WHERE name = :name;", array(':name' =>$username))->fetchField();

  if ($count == 0) {
    if (!empty($postData['access_token'])) {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL,"http://localhost/MYAPI/rest/user/1/get_user_details");
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Authorization:Bearer ".$postData['access_token']));

       // receive server response ...
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       $server_output = curl_exec($ch);
       curl_close($ch);
       $postData = drupal_json_decode($server_output);
       $resRoleArr = $postData['userDetail']['role'];
       $resMail = $postData['userDetail']['email'];
       $roleArr = user_roles();
       $common_roles = array_intersect($resRoleArr,$roleArr);

       if (count($common_roles) > 0) {
         user_external_login_register($username, 'mymodule');
         $user_fields = [
           'pass' => $password,
           'status' => 1,
           'mail' => $resMail,
           'init' => $resMail,
           'roles' => [DRUPAL_AUTHENTICATED_RID => 'authenticated user'],
         ];

         user_save((object) ['uid' => $user->uid], (array) $user_fields);
         $account = user_external_load($username);
         $form_state['uid'] = $account->uid;
         if ($role = user_role_load_by_name($common_roles)) {
           user_multiple_role_edit(array($user->uid), 'add_role', $role->rid);
         }
       }
     }
   }
   else {
     user_login_authenticate_validate($form,$form_state);
   }
 }

As you can see I am trying to login an user externally where it's credentials coming from a REST API.

Before to externally log in, I check if the user already exists in the database.  if it doesn't exist, I use user_external_login_register($username, 'mymodule'); if it exists, I use    user_login_authenticate_validate($form,$form_state).

Though I am able to successfully log in the user in both the cases, I am getting an Unauthorized error.

What could the issue be?

I am using Drupal 7.56.

Below code might help you login-in with current user:

function mymodule_user_login_cred($username, $password)
{
  if(user_authenticate($username, $password))
  {
    $user_obj = user_load_by_name($username);
    $form_state = array();
    $form_state['uid'] = $user_obj->uid;
    user_login_submit(array(), $form_state);
    return true;
  }
  else
  {
    return false;
  }
}


Importing Nodes to D7 with all custom fields I've got a Drupal site with an obscene about of content that has been given to me in CSV format. I'm toying with the idea of building a module to let me do this but if there's one already out there that I can use to just get this site out of the way that would be awesome.

My question is: Is there anything out there that allows you to import a CSV file into D7 that will populate the node table and all the custom fields tables as well?

Thanks.

The Feeds module (sucessor to the FeedAPI module) has that functionality built in.

For your needs specifically it offers:

Import or aggregate CSV files
Create nodes, users, taxonomy terms or simple database records from import
Granular mapping of input elements to Drupal content elements


Hide blocks from the administration page according to the user role Is there a way that certain roles can only manipulate blocks that are assigned to them?

That is, if a user with an a editor role enters to "admin/structure/block", I just want you to see and be able to manipulate the blocks that I define, the rest of the blocks must remain hidden for this user / role.

Is this possible to do?.

To make this work, you will need a custom page, the "admin / structure / block" won't do the work.


How do I add javascript to a module? I'm building a module with a basic form. This form has some js attached to it that I want to keep in the module, so that it's not cluttering my regular scripts file. How do I add it to my module?

I tried to add this is in my .module file but no luck.

function mymodule_init() {
drupal_add_js(drupal_get_path('module', 'mymodule') .'/myscriptfile.js');
}

What should I do?

You can declare the script file inside mymodule.info with

scripts[] = myscriptfile.js

This way it's gonna be included in every page of your site, exactly the same result you obtain adding it manually to hook_init.

In case you want it only when you render a form, add this to the form declaration

$form['#attached']['js'][] = drupal_get_path('module', 'mymodule).'myscriptfile.js';


In the Encrypt module, can I switch between phpseclib and mcrypt assuming I keep the Key Provider Settings in place? A client uses the encrypt module as the basis to encrypt some database cells. The current server is RHEL 6/PHP 5.3. They're upgrading to RHEL 7 but will push to PHP 5.6.

The Encrypt module asks for either a method:

PHP Secure Communications Library (phpseclib)
Mcrypt AES (CBC Mode)
None

Currently the client had the second choice selected. However, the php-mcrypt package doesn't exist in PHP 5.6, and from my understanding, it itself hasn't been updated in a while. The alternative of installing the Libraries Module and cloning down a copy of phpseclib from git clone https://github.com/phpseclib/phpseclib.git seems more palatable at the moment.

Question: can I switch out to using phpseclib assuming I keep the Key Provider Settings in place?

No. You cannot just switch out the encryption methods. Mcrypt AES (CBC Mode) pads the input and also prepends two salts and an IV as well other information like the HMAC for authentication in it's output. phpseclib does none of this. Here are some examples:

encrypt('all your base');
// $text = "TUsE3Fwzvj6MT41ritVO/zUuJ/qWNmZJIBU3euDEX9iDMb3IqMyTJEFwssW/SI/GZ8ce/HxqrqPFWGzTNC0d7UZUtRjr2JReoqaCqw18GHyGhbjqr1zZbr/MCIT1rENM";

encrypt('all your base', array(), 'phpseclib');
// $text = "1r/WWYiCW9icZ93iUxStMQ==";

You can actually rewrite the existing mcrypt plugin to use phpseclib instead. You wouldn't necessarily need the HMAC stuff—it's there for added benefit but you can just skip it. But you likely could make a pain-free transition.

For example, replacing the existing decryption code in _encrypt_encryption_methods_mcrypt_aes_cbc():

// Initialize for decryption.
mcrypt_generic_init($mcrypt, $ekey, $iv);

// Decrypt the data.
$processed_text = mdecrypt_generic($mcrypt, $text);

// Terminate decryption.
mcrypt_generic_deinit($mcrypt);

// Remove any padding.
$pad = ord($processed_text[strlen($processed_text) - 1]);
$processed_text = substr($processed_text, 0, -$pad);

// Close the Mcrypt handle.
mcrypt_module_close($mcrypt);

With this rewrite:

$path = libraries_get_path('phpseclib');
require_once $path . '/Crypt/AES.php';
$aes = new Crypt_AES();
$aes->setIV($iv);
$aes->setKey($ekey);
$processed_text = $aes->decrypt($text);

Returns the correct plain-text given the original mcrypt encryption ciphertext. At least, it should. I've got mcrypt on my system and so phpseclib is probably using it, but it should "just work" for you.

Oh yeah, FYI, use phpseclib 1.x. As the 2.x branch will not work.


How to add custom column in-between people/users admin page table? I have created a custom column to display last user changed time, but I need this field to be inserted before OPERATIONS column. Below is my code which appends my custom field at the end.

function meme_user_update_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
  $changed_column = array('changed' => array(
    'data'  => 'LAST CHANGED',
    'field' => 'u.changed'
  ));
  $form['accounts']['#header'] = $form['accounts']['#header'] + $changed_column;
  foreach ($form['accounts']['#options'] as $key => $row) {
    $user_object = user_load($key);
    $user_language = ($user_object->language) ? $user_object->language : LANGUAGE_NONE;
    $form['accounts']['#options'][$key]['changed'] = $user_object->field_user_changed[$user_language][0]['value'];
  }
}

You need to change the sequence of the array, like:

function meme_user_update_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
  $changed_column = array(
    'data'  => 'LAST CHANGED',
    'field' => 'u.changed'
  );
  $operation_column = array_pop($form['accounts']['#header']);

  $form['accounts']['#header']['changed'] = $changed_column;
  $form['accounts']['#header']['operations'] = reset($operation_column);

  foreach ($form['accounts']['#options'] as $key => $row) {
    $user_object = user_load($key);
    $user_language = ($user_object->language) ? $user_object->language : LANGUAGE_NONE;

    $operation_column = array_pop($form['accounts']['#options'][$key]);

    $form['accounts']['#options'][$key]['changed'] = $user_object->field_user_changed[$user_language][0]['value'];
    $form['accounts']['#options'][$key]['operations']['data'] = reset($operation_column);
  }
}


PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table In my site, I get the following error:

  PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cambodia_ohchrProduction.ohchr_cache_block' doesn't exist: TRUNCATE {cache_block} ; Array ( ) in cache_clear_all() (line 167 of /home/cambodiaohchr/public_html/includes/cache.inc).

How can I fix problem?

This error happened to me before, I don't really know why but the only solution that I can really tell you (and it worked for me) is to get some Database backup that you may have saved (from a past date) and export the schemas from the tables cambodia_ohchrProduction and revision_cambodia_ohchrProduction into your actual site .

Remember just the schemas of those 2 tables.

And that should work!


delete scheduled tasks fails when task identifier is account:uid I have an action set as a scheduled task that deletes a user, that seems to be working fine:

{ "rules_delete_unregistered_user" : {
    "LABEL" : "Delete unregistered user",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user" : { "label" : "user", "type" : "user" } },
    "ACTION SET" : [ { "entity_delete" : { "data" : [ "user" ] } } ]
  }
}

and I also have a rule, that should delete this action set, but it fails:

{ "rules_user_accepted" : {
    "LABEL" : "user_accepted",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "account:field-accepted" ], "value" : "1" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_delete_unregistered_user",
          "task" : [ "account:uid" ]
        }
      }
    ]
  }
}

now I do not have any idea what should I use as a task identifier to delete that action set.

EDIT:

the rule that schedules the action set:

{ "rules_create_new_user_after_registration_form" : {
    "LABEL" : "create_new_user_after_registration_form",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "new user based on webform" ],
    "REQUIRES" : [ "webform_rules", "rules", "php", "rules_scheduler" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : [ "form-id" ],
          "selected_webform" : { "value" : { "webform-client-form-104" : "webform-client-form-104" } }
        }
      }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "user",
            "param_field_lastname" : "[data:lastname1-value-raw]",
            "param_field_firstname" : "[data:firstname-value-raw]",
            "param_name" : "[data:email-value-raw]",
            "param_mail" : "[data:email-value-raw]"
          },
          "PROVIDE" : { "entity_created" : { "new_user_request" : "new_user_request" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "user",
            "property" : "uid",
            "value" : [ "new-user-request:uid" ]
          },
          "PROVIDE" : { "entity_fetched" : { "user_fetched" : "Fetched entity" } }
        }
      },
      { "schedule" : {
          "component" : "rules_delete_unregistered_user",
          "date" : { "select" : "site:current-date", "date_offset" : { "value" : 60 } },
          "param_user" : [ "user-fetched:0" ]
        }
      }
      }
    ]
  }
}

this actually works fine.

If you go to /admin/config/workflow/rules/schedule you will see a table of your scheduled components. One of the columns in that table is the task identifier - that's the string you will have to use to delete the scheduled task. You didn't post any details related to the scheduling, so I don't know what you used as a task identifier. The task identifier is necessary because one component may be queued to execute many many times, each time with a different identifier. The component name is not unique. The task identifier is.


View - show predetermined result set prior to exposed filter Standard behavior: I have a view that has some filters exposed to the user. When the user first visits the page, the exposed filters are empty and the view just shows everything. When the user modifies a filter, the view shows a subset of the results based on their query.

Ideal behavior: When the user first visits the page, and have not performed a search using the exposed filters yet, I'd like the view to show a predetermined set of results... like a group of highlighted* items that I'd want the user to see. Then they perform a search, and the view acts normally.

Is this possible?

*These "highlighted" items would be determined by a field in the node.

All you need to do is:

Create a Boolean field to mark highlights (Let's say field_highlights)
Add a views filter for field_highlight with the following detail:

2.1. Not exposed

2.2. Operation: Is one of

2.3. Options: Select both 'On' and 'Off'
Write a bit of magic code which:

3.1. Checks if the user has not used the exposed filters yet

3.2. Alters the options for our filter to only show 'On' values

Last part sounds difficult? Actually it's not:

    <?php

    /**
     * Implements hook_views_pre_view().
     *
     * Applys a custom filter if there is no filter applyed by user
     *
     */
    function YOURMODULE_views_pre_view(&$view, &$display_id, &$args) {
        // Make sure we are altering the right view
        if ($view->name == 'YOUR_VIEW_NAME') {
            // Get the user input for exposed filters
            $user_input = $view->get_exposed_input();
            // Check if there is no user input
            if (empty($user_input)) {
                // The filter name for selecting highlighted items
                $filter_name = 'field_highlighted_value'; // Figure the filter name by looking at the exported views
                // Getting the filter array
                $filter = $view->get_item($view->current_display, 'filter', $filter_name);
                // Setting the value to TRUE
                $filter['value'] = array(1=>'1');
                // Saving the changes to the filter
                $view->set_item($view->current_display, 'filter', $filter_name, $filter);
            }
        }
    }


Drupal 7 - Internationalization module - some blocks not visibile (i18n) After adding the Internationalization module for Drupal 7, I am having some trouble with a particular block not showing up when switching languages.  I set the block to be translatable (and set full html to be translatable) - the block only contains an image and is displayed in the "slideshow" region of the IV Solutions Theme.  The block/image shows up fine when the page is set to English, but when the language is changed, it disappears.

Thanks for any assistance you can give-

Translatable means you have to actually translate it to show on the second language. On the block configuration it should give an option to translate it or perhaps check the block's visibility language settings.

Another option if you want the same exact image on both languages you make the block untranslatable.

You need to also enable i18n_select if you have not done so
and go to "detection and selection" admin/config/regional/language/configure
and enable at least URL selection for interface/content

This will allow that when you visit yoursite.com/page assumes English
and when you visit yoursite.com/LAN2/page assumes LAN2

More info on setting up internationalization


Rules: save a node but not "fire" a rule that create a loop I have a rule that "fire" on a condition of "node save". Now in the action of this rule I get the node that I receive via "arguments" and set/change some values if some other values are foo or bar.

My problem is: how can I save the node without create a loop ?

Edit: I misread the question but this might be beneficial anyway. Not sure if you're using saving or updating and what you mean by arguments.

You need a Boolean field in your content type that you set to true in the actions of your rule. Then add a condition that if the Boolean is true, the rule doesn't fire repeatably.

You could also skip the extra field and add a condition that one of the fields you set is empty.

If you can't access the fields, you need to add an "entity has field" condition.


Drupal 7 ajax button added via ajax callback I have an issue with this ajax callback in a form. Here is the callback:

function mymodule_add_more_callback($form, $form_state) {

$commands = array();

$current_id = $form_state['number_fieldsets'] - 1;

$id = 'node_group_custom_' . $current_id;

$fs = drupal_render($form['custom_fieldset'][$current_id]);

$commands[] = ajax_command_append(".vertical-tabs .vertical-tabs-panes", $fs);

$commands[] = array(
    'command' => 'enable_tab',
    'id' => $id,
    'id_li' => 'vertical_tabs_li_' . $current_id,
    'current_id' => $current_id,
);

return array(
    '#type' => 'ajax',
    '#commands' => $commands,
);

}

enable_tab is a custom ajax command that works fine.

$fs is a fieldset that contains a few form elements.

$fs also contains another ajax button that is intended to remove the corresponding fieldset via Ajax

$form['custom_fieldset'][$i]['remove'] = array(
'#type' => 'submit',
'#value' => 'x',
'#limit_validation_errors' => array(),
'#attributes' => array(
    'title' => t('Remove section'),
    //'class'   => array('remove_section'),
    'style' => 'cursor:pointer',
    'id'    => 'remove_section_' . $i,
),
'#ajax' => array(
    'callback' => 'mymodule_remove_section',
    'wrapper' => 'names-fieldset-wrapper',
)

);

The problem is that the remove ajax button does not work as expected. It should trigger this callback mymodule_remove_section but it is just reloading the page. I assume this is happening bcause it is added with ajax_command_append. Is there any solution to add ajax buttons with ajax_command_append called from another ajax callback?

EDIT

I'm passing a html string - $fs = drupal_render($form['custom_fieldset'][$current_id]); that obviously does not have the ajax event attached. Is there any other alternative? For example to pass the $form['custom_fieldset'][$i]['remove'] button instead of rendered html source along with my custom command?

I found the answer here.

I was because of the id of my button.


How do I query node sort by randomize? I want to get all articles content type, but I want to get it randomize, how can I do that? Refer to my code below:

$nids = \Drupal::entityQuery('node')->condition('type', 'articles')->sort('RAND()')->execute();

I'm using drupal 8

I don't think this is possible with an entity query directly, but you can alter entity queries after they are converted into select queries.

Add a tag to your entity query and then you can alter it there.

  $nids = \Drupal::entityQuery('node')
    ->condition('type', 'article')
    ->addTag('sort_by_random')
    ->execute();

Then add a query alter function to your custom module using the tag you added.  Drupal's select query even has a built in function to make a query sort on "RAND()":

function mymodule_query_sort_by_random_alter(\Drupal\Core\Database\Query\AlterableInterface $query) {
  $query->orderRandom();
}

If you're going to have to tag an entity query to alter it, and it's not essential that you use an entity query, you might want to just replace it with a select query.

$query = \Drupal::database()->select('node_field_data', 'n')
  ->fields('n', ['nid'])
  ->condition('type', 'article')
  ->range(0, 10)
  ->orderRandom();

$results = $query->execute()->fetchCol();

if (!empty($results)) {
  $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($results);
}


How to use same view.tpl for some taxonomy terms I have few taxonomy terms (taxonomy/term/1 taxonomy/term/2 ...etc ).
Every of that term has a different view.

I want to be able to use the same views-view--[myview]--page.tpl.php for more than one view.

The easiest way is just to copy the file and  alter the myview name to be the same of the each view.

Is another solution?

I use different taxonomy views because i have a FILTER CRITERIA of Taxonomy term: Parent term (= x) for every one.

Example:
taxonomy/term/1 has Taxonomy term: Parent term (= 1) to show all taxonomy terms that is child of taxonomy term 1.

Drupal 7

After some try and error and for the hint  Jack-PL tell me i figure this out.

I make a new view with taxonomy terms. I set the Field (taxonomy name and taxonomy id) .Contexual filters i set the Taxonomy term: Parent term >Provide default value>Taxonomy term id from url.

So know i only have to use Displays >Add>Page>And that did the trick!

Now i can theme with one tpl all the taxonomy pages!


Is it possible to export organic groups global roles using features? I like to keep functionality that I build in features, both for version control and deployment.

I'm new to using Organic Groups and I wanted to know if it's possible to add an organic gorups global role to a feature.  I couldn't see any mention of this when I tried to recreate my feature through the UI or drush.

There is a issue for this in the organic groups queue.  features integration for organic groups permissions and roles.  You may also want to install strongarm and see if that helps you store the configuration settings that are stored as variables.


What is the difference between context layouts and the delta module? I was recently introduced to the Delta module and I think it is fantastic. Specifically the way it works with the Omega theme in Drupal 7. It allows me to copy the theme settings and create layouts to load in context as a response. This is great, but as I went to enable the module on my system I ran across the context layouts module and am left wondering if I shouldn't just use the context layouts module.

So I am wondering if anyone can provide some insight into this. I will go ahead and check both out here in a minute, but I think they both do almost the same thing. I guess it really just depends on what restrictions on layout the context layouts module offers along with whether or not it can let me use the settings in the theme and modify those based on a context.

This also will be interesting to see if the delta module creates files or if it puts all of this into the DB. I suspect the latter, but am concerned about the former for packaging things up into features.

The Delta module is not an alternative to Context Layouts, you should use them together.

Delta allows you to create different versions of your Omega theme with different settings/layouts each.
Context Layouts is part of the Context module, and will allow you to switch the different layouts you previously created with Delta, when a specific 'context' is active.


Is there any way to delete ubercart role expiration through rules in Drupal 7 I am using Drupal 7 and ubercart roles where I have given the role expiration period of 1 day,
and with that role the user can create one node.
I want that as soon as the new node is created the role expiration should be deleted.

I am able to remove the role through rules but as the expiration period is still set, it cannot be re-assigned the role the same role if the user purchases the same role again,

Is there any way to remove the role expiration of ubercart?

thanks for any help.

It seems that you are removing the role through the drupal standard rules. Try calling the own uc_ubercart function to better compatibility.

/**
 * Deletes an expiration using user id or user id and rid.
 *
 * This function deletes expirations associated with users and roles. If
 * no role ID is passed, the function deletes all role expirations associated
 * with the given user. Otherwise, the function only deletes expirations whose
 * user and role IDs match. If any roles were actually deleted, the function
 * notifies the user. The menu cache is then flushed, as privileges to view
 * menu items may have been lost in the process.
 *
 * @param $account
 *   A Drupal user object.
 * @param $rid
 *   A Drupal role ID.
 * @param $silent
 *   When set to TRUE will suppress any Drupal messages from this function.
 */
uc_roles_delete($account, $rid = NULL, $silent = FALSE) {}

An example with custom module (without rules):

https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_insert/7

/**
 * Implements hook_node_insert().
 */
function mymodule_node_insert($node) {

  if ($node->type == 'customtype') {
    $rid = 3; //@TODO: set rol ID
    $account = user_load($node->uid);
    // Delete UC Role!
    uc_roles_delete($account, $rid, TRUE);
  }

}

You can also use this code on the rules action PHP but I prefer the hook.


Soft and hard copies of a single product in Drupal Commerce? I am setting up products for an online store using Drupal Commerce. Some of the products (eg. books, music) require an option for both hard copies and soft copies so that customers can choose one or the other. I would like certain products to have a drop down in which customers can choose either "Hard Copy" or Soft Copy" and the price will change accordingly. Then depending on the option chosen, after payment, the customer will get a confirmation email for the hard copy, while for the soft copy they will also get the download link.

I have installed Commerce File to cover the soft copy option, since Drupal Commerce handles the hard copy option out of the box (being a manual shipping process), however I cannot see how this can be done using this module. I have created a commerce file product which allows for soft copies, and a standard product which allows for the hard copies; but how do I create a product that has both of these as an option? Is Commerce File not the module for this?

After some more experimenting I have worked it out. For any sort of product variations you need to edit the Product reference field. Change the field to a select list and also make sure the you set the number of values to unlimited (or at least more than 1). This will then create a drop down list which when changed will switch between the different products within the same node. I hope that this helps!


Pagination in Panelizer drupal I'm using panels and panelizer. I created a custom content in panelizer where I can upload a file. When I render the results, I have a lot of items. Now I want to paginate them.

How can I add the pagination in panelizer or use a view in panelizer?

Pagerer

  Features:

  multi-pane pager
  Views pager plugin
  control whether to display links to pages, to items, or to item ranges
  direct input of the page to go to through an input widget
  selection of the page to go to through a jQuery UI slider
  selection of the page to go to through a client-side scrolling pager
  links to progressively more distant pages (like +10, + 20, +100, +200)
  adaptive logic links
  specify text to be used to render page separators (like a vertical bar) and page breakers (like an ellipsis)
  supports Views' AJAX enabled pager


Is it possible to put a single field of views in panels? There is an existing views with a few fields output. I would like to put one of these fields in panels. Can I get it directly in Add Content of panels?

If it is impossible, what is the best way to put a single field in panels?

Yes, you can add a single field directly from panels using Add Content, for this you may need to add a context with your entity.

use Arguments option to pass an entity id from url argument and load dynamically context based on that entity;
use Context option to manually specific a entity id to load its context;

You can check node view page as example, which has node context by default.


How to define custom content entity one to many relationship? I have two custom entities; A, B.

In terms of database relationships, I want A to have many B.

I find I am able to define a reference_entity field in the entity's baseFieldDefinition(). However, because this just defines a single column in the database my relationships are back to front:

I can give B a reference to A and then use $B->getEntity()->referencedEntities() to get a B's associated A, but I can't do it the other way round because there's just a single id for each row.

Is there a correct way to query or set up these kinds of relationships 'out-the-box' or is a better solution to add my own method to the A entity getReferencedBs() and query the B table for references to A.

Many thanks

Sounds like you need to add setCardinality(-1) to your B reference field definition in your A entity. This will change the B reference field to support an unlimited number of references instead of 1, the default cardinality.


Can we override Drupal includes files? I want to modify the menu.inc file that is in the Drupal "includes" folder, but I want to create an overriding file for it, so that we can easily package only our custom theme.

Generally Clive is right. Don't touch core. But sometimes you are forced to do a core patch or it's just much easier to solve your requirements.

If you must: I'd recommend to put your whole project into git. This gives you the possibility to have a clean core version in one branch and the patched one in an other. Everytime a new core version is published you can merge it in a clean way.


How can I search for a specific user on the People administration page? I can filter by Role, Permission and status on the people page, is there an easy way to search for one specific user?

That's all you can do with core Drupal - it is a little frustrating for sure.  :-)

However, there are lots of contrib modules that let you do more, such as

Advanced User, in which user fields to filter/search by can be configured in the module's settings or
the simpler User search to People Admin which simply puts the user search box on there for you.

Of course, you can also opt to make yourself a user-based view and create an admin page yourself by using relationships and filters.  :-)

Hope one of these helps!


How to pass content type filter to taxonomy I created a classified ad website with different content type like vehicle, clothing, mobile phone, computers, etc. Within this content type has a field called location. A location field is an address of the item posted on my website like cities.

My question is on how can I filter location plus the content type. Currently, when I click the location, all of the content type article shows.

Here's an example of what I want:

Select article about vehicle, within the vehicle article is a field called location. When I click the location of the item, the result should include only items related to the previous content type, that is, vehicle content type. Location field is connected to Location taxonomy I created.

BTW, I already installed views and it is working fine.

I think you need to edit the location links to include a second "parameter" so it could look like:

yoursite.com/yourview?location=yourLocation&articletype=yourArticle

For this you would need to implement some hooks. Maybe you can start with hook_preprocess_node.

What I would do is to:

Use the said hook
Get the location terms available for the current viewed node
Construct the URL based on the term data and content type the way I want it to look.

Then in your view, you need to add just two contextual filters that would be those fields. The location term reference field and the content type.

EDITED

Node view and term link update

Created a new content type name Article 2 (Machine name: article_2) to follow your structure of content types having Vehicle, Clothing and etc. So mine is just Article and Article 2. My content types have the Term reference field of the Tags vocabulary w/c in your setup is the Location.
Added terms into the Tags vocabulary: Term 1 and Term 2.
Created a simple custom module using hook_preprocess_node() w/c looks like:

function yourmodulename_preprocess_node(&$vars) {
  // Check if your term field is being rendered in the node view
  if (isset($vars['content']['field_tags']['#items'])) {
    // Loop through all terms present in the node
    foreach ($vars['content']['field_tags']['#items'] as $index => $info) {
      $node_type = '/' . $vars['type'];
      // We append the node type to the URL of a term so that
      // it can be used as a contextual filter in the term view.
      $vars['content']['field_tags'][$index]['#href'] .= $node_type;
    }
  }
}

Remember to do a Flush Cache since were adding a new hook function into the system. Now when you view a node, check the term link(s) listed and you will see that the URL structure is not like http://yoursite.com/taxonomy/term/2/article

Term View

Clone the Taxonomy Term view (So that we wont be changing the original)
Add a second wild card argument in the Path w/c looked like taxonomy/term/% to taxonomy/term/%/%. The second argument would be for the content type.
Under contextual filter add the Content: Type field following the settings in the image.

And then place the Content: Type contextual filter at the second row to match the URL structure w/c would look like:

And that's it. A simple sample result based on this URL http://localhost/drupal/taxonomy/term/2/article would look like:

So it's filtering the right node that has Term 2 as its Tag(my setup)/Location(your setup) and only the Article content type.

My test data are:

Article content type: Article 1, Term 1
Article content type: Article 2, Term 2 (This is the result in the latest screenshot)
Article 2 content type: Article 3, Term 1
Article 2 content type: Article 4, Term 2

Issue

So far I haven't figured out how to use this style with Pathauto so the URL would look better for example, www.mysite.com/illinois/chicago/article.


Change field type with hook_update_n for a module Hello I need to update the field type of one of my content types. The content type is of a module so I need to do this with the Drupal API for let users update the module for their 7.x-1.0 branch.

This is the hook for update the field, I need to change it from Integer to Decimal like this:

 /**
 * Change field_inq_description field from Integer to Decimal
 */
function field_updates_update_7100() {
  // Manual database changes.
  db_query("UPDATE {field_config} SET type = 'number_decimal' WHERE field_name = 'field_rin'");
  db_change_field('field_data_field_rin', 'field_rin_value', 'field_rin_value', array(
    'type' => 'numeric',
    'precision' => '10',
    'scale' => '2',
  ));
  db_change_field('field_revision_field_rin', 'field_rin_value', 'field_rin_value', array(
    'type' => 'numeric',
    'precision' => '10',
    'scale' => '2',
  ));
  // Clear caches.
  field_cache_clear(TRUE);
  // Apply the new field instance configuration.
}

After I apply the update with update.php script I get these notices everywhere in the test website.

Notice: Undefined index: precision in number_field_schema() (line 35 of /home/servilla/public_html/servillantasgiraldo.com.co/modules/field/modules/number/number.install).
Notice: Undefined index: scale in number_field_schema() (line 36 of /home/servilla/public_html/servillantasgiraldo.com.co/modules/field/modules/number/number.install).

What Im I doing wrong?

You just need to add precision and scale to the field config settings:

// API way.
$field = field_info_field('field_rin');
$field['settings']['precision'] = 10;
$field['settings']['scale'] = 2;
field_update_field($field);

// Raw way (shorthand, you'll want to add error checking).
$data = unserialize(db_query("SELECT data FROM {field_config} WHERE field_name = 'field_rin'")->fetchField());
$data['settings']['precision'] = 10;
$data['settings']['scale'] = 2;

db_update('field_config')
  ->fields(array('data' => serialize($data)))
  ->condition('field_name', 'field_rin')
  ->execute();


Easily add term to vocabulary with long list of terms A client is complaining about the way on how to add terms to a vocabulary in taxonomy.

It's a long list of terms and sub-terms. So I told him when he adds a term he can select a Parent term and set the weight in the Relations block.

But the list of parent terms is long and not very clear. Isn't there a way to make this more user friendly? Maybe search in parent terms or .. ?

For better UI management of taxonomy terms try Taxonomy Manager

This module provides a powerful interface for managing taxonomies. A vocabulary gets displayed in a dynamic tree view, where parent terms can be expanded to list their nested child terms or can be collapsed.

The Taxonomy Manager has following operations and key features:

 - dynamic treeview
 - mass deleting
 - mass adding of new terms
 - moving of terms in hierarchies
 - merging of terms (using the Term merge module in 7.x)
 - fast weight changing with up and down arrows (and AJAX saving)
 - AJAX powered term editing form
 - simple search interface
 - CSV Export of terms
 - i18n support for multilingual vocabularies (per language terms)
 - Double Tree interface for moving terms in hierarchies, adding new
   translations and switching terms between different vocabularies


Editting field collections with service api I am trying to build an phonegap app which uses data of a drupal site. I need to update some informations with using app. For example I have nodes and users need to update field_collections of a node. My nodes have field collection as:

"field_bundle_news":{
    "und":[
    {
        0:{ target_id: "308" }
    }]
}

I want to add some additional items or remove some of them with using service api. For example if I use put method with using "/node" endpoint I can edit some data of that node but I can not edit field collections.

Could anybody give me information about this problem with examples because actually I dont know drupal well I am learning it with implementing a mobile app.

You must send acceptable field structure in order to create or edit the node

try to understand the field structure through Implementing hook_node_insert in custom module and  watchdog the inserted node via watchdog and you will have the structure drupal uses to insert then build it when you create/edit node through services

function hook_node_insert($node){
  watchdog('node', json_encode($node));
}

after adding a node of the same type open dblog in your project and see that log, you could use pro.jsonlint  to understand it well

Hope that helps


Is there a module that helps link similar articles together and insert them into each other? I'm looking for the module that would allow me to manually link related articles together and to then set them to appear within the body of content - as links.

What would be your recommendation?

I tried to find different modules, but I need specifically something that could work by me simply creating links between different articles on a separate module settings page, so I don't have to enter into the EDIT mode for each article to add the connection.

You can set up nodes to be used like taxonomy items.  Take a look at this:  https://www.drupal.org/project/entityreference

That module will allow you to set a content type as the source for cross-linking nodes.


"Unable to generate the derived image located at public://styles/uc_category/public/tg.jpg" (Drupal 7 under Linux)

This is clearly a Drupal permissions problem, but I'm baffled. If I

rm -rf styles

and refresh the page causing the error, styles and it's sub-dirs are re-created thus:

drwxr-xr-x 3 www-data www-data 4096 Jan 25 16:07 styles

drwxr-xr-x 3 www-data www-data 4096 Jan 25 16:07 uc_category

drwxrwxr-x 2 www-data www-data 4096 Jan 25 16:07 public

But I still get the error. And I still get it if I

chmod -R 777 styles

Any suggestions?

If you are sure this is not a permission issue, also make sure you have a graphical library installed on your server.

In D7, the configuration page for this is: /admin/config/media/image-toolkit


Where are my views being used? I created a clone of a view and have completely forgotten why I did that.
I suspect that I was experimenting, but before I delete the view, I want to make sure that it is not being used.
Is there a mechanism by which one can list where views are being used?

Open the View and you'll see if it is a page or block, if it is a page you can see the path to the page under Page Settings, if it is a block just look for that block in the list (/admin/structure/block).

The block is named like Views:[view_name] and if it is disabled I think you can safely remove that View, if not you can see the region and where you can see that block when you edit block and look at Visibility settings.

I think that there is no other automated way to find out where some View is used.


Why no alias record could be found when I'm trying to sql-sync the database? I'm trying to synchronize a production database to two development installations at once, instead of having the production database dumped twice.

In aliases.drush.inc file I'm defining a site-list alias as following:

$aliases['dev'] = array(
  'site-list' => array('@dev1', '@dev2'),
);

$aliases['prod'] = array(
  'uri' => 'default/prod',
  'root' => '/docroot/prod',
  'db-url' => 'mysqli://root:pass@localhost/prod',
);
$aliases['dev1'] = array(
  'uri' => 'default/dev1',
  'root' => '/docroot/dev1',
  'db-url' => 'mysqli://root:pass@localhost/dev1',
);
$aliases['dev2'] = array(
  'uri' => 'default/dev2',
  'root' => '/docroot/dev2',
  'db-url' => 'mysqli://root:pass@localhost/dev2',
);

Running a Drush command against any of these aliases works fine.

Running drush @dev status works fine too, and displays the status for both @dev1 and @dev2.

However, trying to execute drush sql-sync @prod @dev gives me the following error:

  Error: no alias record could be found for @dev

Do you have any clues?

Seems that this feature is buggy in Drush and will be removed. Check this out: drupal.org/node/1316378


Override Load More button for Views I am currently using Drupal Views and its "Load More" Pager. I wish to change the words on the button to say something else instead.

It looks like the UI does not provide me with an easy way to do that, so I am wondering if there is any easy programming way to achieve that.

There is an option to change the text. Follow the steps

In you 'view' you can find PAGER settings

Click on Settings to change the text

Enter the text whatever you want to see at Output


How can I make someone else group manager of a group I've created? I created a few groups and populated them with users. I also selected an admin per group. I don't want to appear on the OG members view of the group anymore, therefore I want to remove myself from the group. I find this impossible.
Probably, because I'm the group manager. How can I change the group manager to that admin?

Change the author of the group node. Make it someone else than yourself.


How set a time type field programmatically? I create a custom content entity type.

I want one field for the event time.

Since there is no time field, but a dataTime_type, I create a plugin for a custom field :

  FieldType : TimeItem.php

/**
 * Plugin implementation of the 'time' field type.
 *
 * @FieldType(
 *   id = "time",
 *   label = @Translation("Time Field"),
 *   description = @Translation("Permet la creation d'un champ de type time"),
 *   default_widget = "time_widget",
 *   default_formatter = "time_formatter"
 * )
 */

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return array(
        'columns' => array(
            'value' => array(
                'description' => 'The time value.',
                'type' => 'int',
                'length' => 6,
            ),
        ),

    );
  }

I try to change type to time (for mysql) but mysql error return me a null for the type.
So I use int for store time in seconde.

  FieldWidget : TimeWIdget.php

/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$value = isset($items[$delta]->value) ? $items[$delta]->value : '';
$element += array(
'#type' => 'time', //HTML5 input
'#default_value' => $value,
'#size' => 4,
'#element_validate' => array(
array($this, 'validate'),
),
);

return $element;
}

My entity :

 $fields['heure_evenement'] = BaseFieldDefinition::create('time')
        ->setLabel(t('test'))
        ->setDescription(t('test'))
        ->setRequired(TRUE)
        ->setDefaultValue('')
        ->setDisplayOptions('view', array(
            'label' => 'above',
            'type' => 'string',
            'weight' => 3,
        ))
        ->setDisplayOptions('form', array(
            'weight' => 3,
        ))
        ->setDisplayConfigurable('form', TRUE)
        ->setDisplayConfigurable('view', TRUE);

All is working except one thing, the HTML5 input type time

Drupal know some input in html5 but not all... type tel, email, number, range, color, date, datetime is ok but not the type time alone.

So I was hoping get it with a custom plugin, but no...

Edit 1

The only way I have found is to create 2 select for this type :

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$value = isset($items[$delta]->value) ? $items[$delta]->value : '';

    //heure
    for($i=0;$i<=24;$i++){
        $hour[]=$i;
    }

    //minutes
    for($i=0;$i<=59;$i++){
        $minutes[]=$i;
    }

$element += array('hour'=>array(
    '#title'=>t('Hour'),
    '#type' => 'select',
    '#options'=>$hour,
    '#default_value' => $value,
    '#element_validate' => array(
    array($this, 'validate'),
    ),
)
);

    $element += array('minutes'=>array(
        '#title'=>t('Minutes'),
        '#type' => 'select',
        '#options'=>$minutes,
        '#default_value' => $value,
        '#element_validate' => array(
            array($this, 'validate'),
        ),
    )
    );

return $element;
}

Any idea about this?

The form element property #type refers to an element type, not a HTML element. It is okay to define your own element types (or theme types), and you can provide your own markup for it. This can be done by implementing a RenderElement plugin.

Update:

You can also use the datetime render element and disable the date portion.

$element['#date_date_element'] = 'none';

Update 2:

The comment form has an example of a render array that uses the datetime type. So given that as a guideline,

  $form['time_without_date'] = array(
    '#type' => 'datetime',
    '#title' => $this->t('Time without date'),
    // HTML 5 time element format can be H:i
    '#default_value' => DrupalDateTime::createFromFormat('Y-m-d H:i:s', '1970-01-01 20:00', 'UTC'),
    '#size' => 20,
    '#date_date_element' => 'none',
    // This sets html 5 time element use explicitly, probably not necessary.
    '#date_time_element' => 'time',
  );


How to load into a normal page instead of the (blog-like) front page? I have my drupal site, loading the  page when I open the site. It is the normal behaviour, but I don't want it.

I have a different HOME page that I want to see when I open my site (instead of the  page with all my articles).

I still have the  page with articles and I have a link NEWS in my menu that points to it, because I want to keep the articles page.

I tried this:

Configuration > Site information > Default front page > (I wrote "home")

But the NEWS link didn't point to the articles anymore, because it seems that now the page is my HOME page.

So, it loads the HOME page on opening, like I wanted, but now my articles page is not accessible via the NEWS link in the menu.

How can I see my HOME page as default page when entering the site "without" losing access to the page of articles?

Thanks

it is a bit confusing your question. But I try help you.

First, did you create a view called 'NEWS' (in Structure -> Views)? OK great, make this view accessible by url '/news'. (if not, make this sentence true).

Check if your 'HOME' view is set to < front> (url '/home', same url that you set in Site information page - with '/home') and make it accessible.

Then, edit the 'main content' block (in Structure -> Block Lay out) to only appear in NEWS page.

This is for drupal 8, but seems to be almost the same for drupal 7 (same modules, Block and Views).
PS: Edit your question and add a tag with your drupal version.


Limit amount of emails sent per time frame? Is there a module which allows for the limiting of emails sent per hour using drupal mail system?
My server has a limit of how many emails can be sent per hour. Most of my users are online at the same time of the day, so it makes sense to spread the emails out over the day rather than sending all at once.
But the only mail modules I've found so far send all emails in one go rather than being able to limit the amount per hour.
How can I set Drupal to limit the amount of emails it sends per hour and all unsent emails are queued for the next hour?
Thanks

There is an option, Queue mail module that queues all output emails in the queue ( you can define what email Ids queue). then set Cron to run each hour with ultimate_cron module)
the only problem is that you can not define how many hours can be sent in a Cron run. you can just set how many seconds the Cron can be run ( Queue processing time) . I think with a couple of tries you find your desire time.


Contact form placeholder translation I am working drupal 8 site. In this site I create a contact form for contact page. I am able to translate field label but I want to translate my placeholder.I can't find any option for translate contact forms placehoder in drupal 8.

Normally you should be able to translate the placeholder in configuration translation as described in https://drupal.stackexchange.com/a/191927/47547. @Berdir pointed out that there is an open issue that prevents this: https://www.drupal.org/node/2546212

A workaround is to make the placeholder translatable in a form alter hook:

function mytheme_form_contact_message_feedback_form_alter(&$form, $form_state) {
  $form['subject']['widget']['0']['value']['#placeholder'] = t('Please enter a subject');
}

After visiting the translated form you can translate this string in the user interface translation.

If you want to translate all placeholders in the form and use the untranslated strings from the widget settings:

function mytheme_form_contact_message_feedback_form_alter(&$form, $form_state) {
  array_walk_recursive($form, function (&$value, $key) {
    if ($key === '#placeholder' && is_string($value) && $value !== '') {
      $value = t($value);
    }
  });
}


Show required user profile fields after the account is verified during first login The user can register with their username, email and password. Once the account verifies their account i need to show custom required fields like age, sex , profession to be filled.

Complete profile comes in handy to force filling of required fields.

But, if i mark the fields as required they show on the registration form. Is there a way to hide the required fields of the user profile in the registration form???

I tried Field Permission and removed permission for anonymous users to see the fields. Though it doesn't show the fields, once the form is submitted it returns the hidden fields as required.

Use this module: https://www.drupal.org/project/required_by_role
In rules you can add rule "After login user" -> Do: redirect to "profile edit"

Or add rule if user view content -> redirect to "profile edit" and show status message "required fields need to be filled"


Show advanced search form outside fieldset When I search for a keyword in core Drupal search, it shows a results page with a link named Advanced search that hides a fieldset with more form options. I want it to be shown in the basic search form, not only on search result page, and it should be expanded by default.

Note: I want all this with core search in Drupal 7.

take a look at the Advanced Search Module:

This module alters the default search box in many ways. If you need to
have options available like in advanced search, but directly in the
search box, this module is for you.
Basic options The module adds
options to select:
which content type(s) to search, which specific module search to use
(node, help, user or any module that implements search), which input
type to use (with Elements), advanced criteria For all these choices,
there are options to switch between a select box, checkboxes or radio
buttons, and also customize the selector label and the default - Any -
text.
Advanced options There are also options to:
change the default search box label, add a default text in the search
box, add advanced search criteria, change the default submit button
text, use an image instead of the submit button, change the order of
all the elements, include some elements in a popup block, add a filter
to the results page, show/hide basic and/or advanced search in the
results page, show/hide meta data in the results page, multiple search
paths


How do I add multiple images in JSON to meet Google's schema.org requirements? The Google guidelines for article on schema.org state:

  For best results, provide multiple high-resolution images (minimum of
  300,000 pixels when multiplying width and height) with the following
  aspect ratios: 16x9, 4x3, and 1x1.

How do I do this in Drupal?

This takes a little while to set up but is pretty straightforward.

Download and install the Image Widget Crop and Schema.org Metatag modules.
Go to admin/config/media/crop and create three crop types: 1x1, 4x3, and 16x9.  Set the aspect ratios to 1:1, 4:3, and 16:9, and set a hard limit of height 696 and width 696 for all three as stated in Google's documentation.
Go to admin/config/media/image-styles and create three image styles, 1x1, 4x3, and 16x9, and each should use the effect Manual crop pointing to the crop type you created in step #2.
Go to /admin/structure/media and find your image type. Go to Manage form display and use the crop widget.  Require all three crops.
Go to /admin/config/search/metatag/ and choose the content that includes the images.
For Schema.org Article, scroll down to Image and choose ImageObject. Enter the URLs as tokens.

For example, if your image styles are:

hero_16x9
hero_4x3
hero_1x1

And your node contains an entity reference to the image you want to use in field_ref_media_hero, then you can enter the URLs separated by commas like this:

[node:field_ref_media_hero:entity:field_media_image:hero_16x9:url], [node:field_ref_media_hero:entity:field_media_image:hero_4x3:url], [node:field_ref_media_hero:entity:field_media_image:hero_1x1:url]


How to override node add template for custom content type? I have a custom content type named called "circular". For Admin user the "circular" node add form is opening using administration theme (i.e. Seven). But for Authenticated user the node add form is opening using my custom theme. I want to override template of the node add/edit form the custom theme.

I created page--node--add.html.twig in the template folder of the custom theme and used {{ form }} to render the form. But blank page is coming.

How do I fix this?

This template will be used when a node edit form specifies 'node_edit_form' as its #theme callback. Otherwise, by default, node add/edit forms will be themed by form.html.twig.

Try this on your theme:

use Drupal\Core\Form\FormStateInterface;

function YOURTHEME_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $form['#theme'] = ['node_edit_form'];
}

After this your theme can read template node-edit-form.html.twig.

https://api.drupal.org/api/drupal/core%21themes%21classy%21templates%21content-edit%21node-edit-form.html.twig/8.2.x


How to import CSV feed into nodes with multiple taxonomy terms? My question title says it all.

I have feeds for importing and tamper for editing the data before being put into my nodes.

I have my values delimited by commas and explode is making them into individual values.  I've made sure of this by also assigning them to individual text fields.

The exploded values are not getting assigned to already created taxonomy terms.  I've noticed that there are spaces in front of all terms except the first and after all terms except the last.  I've tried to add additional options like trim or exact. Neither have had any affect.

To simplify things, I've removed all but one taxonomy terms and removed all spaces before and after commas from the .csv file. Still nothing shows up into my term field when I explore.

Additional I've tried to use the search term by name add-on for feeds, but it gives me a query error.

Since I'm obviously missing a step, I'm curious how to set up each step of the puzzle.

Content type field set up, mapping to the term reference field, and finally the tamper set up. Since mapping is fairly straight forward I'm only concerned with getting multiple taxonomy terms attached to the nodes I am trying to import.

I'm hoping to avoid trial and error of every combination of settings here as such, any and all help provided is appreciated.

You just set Search taxonomy terms by: Term name in mapping at Node processor & uncheck Auto create.

Add explode plugin at Feed Tamper tab with string operator such as ||.

Provide multiple value separated by your set string operator and it will work. It works for me at several places.


How do I find or set the apropriate form for base scheme fields? In my custom entity I want to set a base scheme field, which is an integer. The field has a minimum of 0, a maximum of 360 and a default of 180.

I tried this so:

    $fields['pan'] = BaseFieldDefinition::create('integer')
  ->setLabel(t('PAN'))
  ->setDescription(t('Horizontal Positioning'))
  ->setSettings(array(
    'default_value' => 180,
    'min_value' => 0,
    'max_value' => 360
  ))
  ->setDisplayOptions('view', array(
    'label' => 'inline',
    'type' => 'default',
    'weight' => -3,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'number',
    'weight' => -3,
    'settings' => array(
      'default_value' => 180,
      'min' => 0,
      'max' => 360
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

Neither the form is limited nor the input is limited when I post.

How can I get the correct type for my form and the correct settings? How can I look for them? Where?

Edit: solution is the following:

    $fields['pan'] = BaseFieldDefinition::create('integer')
  ->setLabel(t('PAN'))
  ->setDescription(t('Horizontal Positioning'))
  ->setDefaultValue(180)
  ->setSettings(array(
    'min' => 0,
    'max' => 360
  ))
  ->setDisplayOptions('view', array(
    'label' => 'inline',
    'type' => 'number_integer',
    'weight' => -3,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'number',
    'weight' => -3,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

You can always create a field with the desired settings in the field, widget and formatter settings in the UI. Then export the configuratio and use the settings from there. The field settings are in two files:

field.storage.entity_type.yourname.yml
field.field.entity_type.bundle.yourname.yml

For base fields, you can merge the settings together into a single array.


Views exposed filter in block redirects to homepage instead of current page Problem is similar to drupal.org/node/1807916 #65.

I'm using Views ("7.x-3.6+4-dev" in D7.21) exposed filter in bartik, with my filter exposed as block in sidebar. When I click the reset button I am redirected to homepage instead of current page as desired.

URL shown:

  "localhost/?field_sku_value=123&field_name_value=&field_component_value=&op=Reset"

(last filter values)

Filter exposed on Views Page is ok.

Try to tweak $form_state['redirect'] in views_plugin_exposed_form.inc doesn't work. Any idea?

There is a jquery fix for this issue.  See https://drupal.org/node/1109980, #23.


How to theming attachment views? I don't get nothing when I add elements to the tpl I'm trying to theming the attachment glossary view

I have create the new tpl files for the elements I want to theming, but I don't get nothing.

I have clear cache several times, and also clean apc.

Any idea how to theming attachements?

Oskar

you can use display suit module and write some tpl file for your element you want to theme in a specific view mode you choose for your view and suggest it to drupal.


Is there any way to generate url alias instead of this taxonomy/term/%/faq, in views I have created a page view taxonomy/term/%/faq. It works fine but I need to replace taxonomy/term/% with its url alias.

Pathauto just allows you to generate the URLs automatically so I believe you would still have the issue.

You will need something like https://www.drupal.org/project/path_alias_xt to extend the alias functionality to the other subpaths like the node/%/edit, taxonomy/term/%/faq etc.


Migrate to node content type with the right user id (migrate module) I want to migrate an old website (not Drupal) into Drupal.
I want to migrate a table to a specific content type...

Inside that table there are many fields in addition to the user_id field,
so every record has 'field_1', 'field_2', ..., 'field_n' and 'user_id' field (foreign key of table "users")

First I successfully migrated "users" table. The problem is that 'user_id' ( of old website) is not the same as 'uid' of the Drupal website.
For example assuming that the first record will be migrated, has the 'user_id' = 255. This user is already inserted with the 'uid' = 55 inside Drupal. Now I want to insert the node with the correct uid (witch is 55), but inside the table I have 255.

How can I do the correct mapping inside the Migrate class to insert every record inside "node" table with the correct 'uid' ?
Or if there is another solution to do it "All in one" (create users and the nodes at the same time) maybe Migrate module has some powerfull functionality like creating a temporary database table that tell the migrate classes that the uid 55 is the same as the user_id 255 of the old website...

Thanks in advance.

You use the sourceMigration() method of the migrate module. You should:

1) Write one migration to migrate old users to the new version of drupal.
2) Then write a migration that moves an old table to the new version of drupal.

In (2) when you setup your field migration it sounds like you've written:

# Field Mappings Docs: https://www.drupal.org/node/1133448
# this maps new <= old field.
$this->addFieldMapping('new_user_id_field', 'old_user_id_field');

When you want to write:

# Search for sourceMigration on this page:
# https://www.drupal.org/node/1133448
$this->addFieldMapping('new_user_id_field', 'old_user_id_field')->sourceMigration('MigrateLegacyUsers');

This then uses a previously run MigrateLegacyUsers migration I described in (1) as the lookup for the new user ID in the new drupal site from the mapping table stored by Migrate for the old_user_id_field created during the MigrateLegacyUsers migration task.

Also note if you possibly have multiple users migrated into the system, say from a drupal legacy system, a wordpress system or LDAP you could write:

`->sourceMigration(array('MigrateLegacyUsers', 'MigrateWordressUsers', 'MigrateLDAPUsers'));`

This means: Find the legacy user id among all these possible prior migrations of Users. The first user_id that matches the requested legacy ID will be used by migrate (so be careful to assure all the user_ids are unique across multiple sources).


Ubercart attribute changes price without page reload on Drupal 7 Running Drupal 7, and the latest stable UB. Currently, each product's price is set to $0. We have attributes that get selected and that is what determines a product final price. When a user selects the attribute. We want it to automatically change the product price without a page reload or needing to add it to the cart. How can I accomplish this?

Update: This is the latest patch that was mentioned here. I have patched my code as follows. I attached a pastebin of the patched code for review in case I missed something. Also if anyone wants post-patch code prior to it getting released to dev.

http://pastebin.com/FnKCrYGk - uc_attribute.module
http://pastebin.com/f2GN5Ms9 - uc_order.order_pane.inc
http://pastebin.com/1AURsfML - uc_product.admin.inc
http://pastebin.com/i5JF3dif - uc_product.module
http://pastebin.com/7VnGKQap - uc_product_kit.module

Some people report that the patch works. I unfortunately haven't been able to get it to work. The blue spinning ajax icon shows like its doing something but my display price doesn't change.

UPDATE FIX!: This thread details the answer to this question.

This is planned to be included in Ubercart itself, see http://drupal.org/node/1380772 - any tests or comments are welcome in that issue.


How can I create a view that lists users who have NOT completed an order? I am helping with a Drupal 6 / Ubercart site that has tons of spam user accounts registered.

I want to create a view that will list spam accounts. My thinking is that users who have registered but never bought anything in Ubercart have a high probability of being spam so I want to create this view. However, I can't figure out how to filter my user view to list only users who have not completed an order.

Is this possible?

To save to anyone else the trouble, this is the view I created to achieve the above.

$view = new view;
$view->name = 'Spambots';
$view->description = '';
$view->tag = '';
$view->base_table = 'users';
$view->core = 6;
$view->api_version = '2';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->override_option('relationships', array(
  'uid' => array(
    'label' => 'Order user',
    'required' => 0,
    'id' => 'uid',
    'table' => 'uc_orders',
    'field' => 'uid',
    'relationship' => 'none',
  ),
));
$handler->override_option('fields', array(
  'mail' => array(
    'label' => 'E-mail',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'link_to_user' => 'mailto',
    'exclude' => 0,
    'id' => 'mail',
    'table' => 'users',
    'field' => 'mail',
    'relationship' => 'none',
  ),
  'created' => array(
    'label' => 'Created date',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'date_format' => 'small',
    'custom_date_format' => '',
    'exclude' => 0,
    'id' => 'created',
    'table' => 'users',
    'field' => 'created',
    'relationship' => 'none',
  ),
  'login' => array(
    'label' => 'Last login',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'date_format' => 'small',
    'custom_date_format' => '',
    'exclude' => 0,
    'id' => 'login',
    'table' => 'users',
    'field' => 'login',
    'relationship' => 'none',
  ),
  'edit_node' => array(
    'label' => 'Edit link',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'text' => '',
    'exclude' => 0,
    'id' => 'edit_node',
    'table' => 'users',
    'field' => 'edit_node',
    'relationship' => 'none',
  ),
  'delete_node' => array(
    'label' => 'Delete link',
    'alter' => array(
      'alter_text' => 0,
      'text' => '',
      'make_link' => 0,
      'path' => '',
      'absolute' => 0,
      'link_class' => '',
      'alt' => '',
      'rel' => '',
      'prefix' => '',
      'suffix' => '',
      'target' => '',
      'help' => '',
      'trim' => 0,
      'max_length' => '',
      'word_boundary' => 1,
      'ellipsis' => 1,
      'html' => 0,
      'strip_tags' => 0,
    ),
    'empty' => '',
    'hide_empty' => 0,
    'empty_zero' => 0,
    'hide_alter_empty' => 1,
    'text' => '',
    'exclude' => 0,
    'id' => 'delete_node',
    'table' => 'users',
    'field' => 'delete_node',
    'relationship' => 'none',
  ),
));
$handler->override_option('sorts', array(
  'uid' => array(
    'order' => 'DESC',
    'id' => 'uid',
    'table' => 'users',
    'field' => 'uid',
    'relationship' => 'none',
  ),
));
$handler->override_option('filters', array(
  'order_id' => array(
    'operator' => 'empty',
    'value' => array(
      'value' => '',
      'min' => '',
      'max' => '',
    ),
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'order_id',
    'table' => 'uc_orders',
    'field' => 'order_id',
    'relationship' => 'none',
  ),
  'rid' => array(
    'operator' => 'not',
    'value' => array(
      3 => '3',
      6 => '6',
      4 => '4',
      5 => '5',
    ),
    'group' => '0',
    'exposed' => FALSE,
    'expose' => array(
      'operator' => FALSE,
      'label' => '',
    ),
    'id' => 'rid',
    'table' => 'users_roles',
    'field' => 'rid',
    'relationship' => 'none',
    'reduce_duplicates' => 0,
  ),
));
$handler->override_option('access', array(
  'type' => 'role',
  'role' => array(
    3 => 3,
    5 => 5,
  ),
));
$handler->override_option('cache', array(
  'type' => 'none',
));
$handler->override_option('header', 'The following accounts have no orders associated with them and are not assigned a specific role. Therefore it is safe to assume they are spambots.');
$handler->override_option('header_format', '1');
$handler->override_option('header_empty', 1);
$handler->override_option('use_ajax', TRUE);
$handler->override_option('items_per_page', 20);
$handler->override_option('use_pager', '1');
$handler->override_option('style_plugin', 'table');
$handler->override_option('style_options', array(
  'grouping' => '',
  'override' => 1,
  'sticky' => 0,
  'order' => 'asc',
  'summary' => '',
  'columns' => array(
    'mail' => 'mail',
    'login' => 'login',
    'uid' => 'uid',
    'delete_node' => 'delete_node',
  ),
  'info' => array(
    'mail' => array(
      'sortable' => 0,
      'separator' => '',
    ),
    'login' => array(
      'sortable' => 0,
      'separator' => '',
    ),
    'uid' => array(
      'sortable' => 0,
      'separator' => '',
    ),
    'delete_node' => array(
      'separator' => '',
    ),
  ),
  'default' => '-1',
));
$handler = $view->new_display('page', 'Page', 'page_1');
$handler->override_option('path', 'spambots');
$handler->override_option('menu', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));
$handler->override_option('tab_options', array(
  'type' => 'none',
  'title' => '',
  'description' => '',
  'weight' => 0,
  'name' => 'navigation',
));

It will need tweaking to your needs because I've got it set up to filter based on user role too but should give you a good base to start with.

Also the SQL is:

SELECT users.uid AS uid, users.mail AS users_mail FROM users users  LEFT JOIN uc_orders uc_orders ON users.uid = uc_orders.uid LEFT JOIN users users_uc_orders ON uc_orders.uid = users_uc_orders.uid LEFT JOIN users_roles users_roles ON users.uid = users_roles.uid AND (users_roles.rid = 3 OR users_roles.rid = 6 OR users_roles.rid = 4 OR users_roles.rid = 5) WHERE (uc_orders.order_id IS NULL) AND (users_roles.rid IS NULL) ORDER BY uid DESC


How to deal with PHP Fatal error: Cannot unset string offsets in field.default.inc when implementing custom widget? I have a custom auto-complete widget that I use to create a custom field that is used to create a custom content type in a custom module.

I have hook_field_widget_info

function MODULE_field_widget_info()
{
    return array(
        "MODULE_taxonomy_autocomplete" => array(
            "label"         => t("MODULE Autocomplete term widget (tagging)"),
            "field types"   => array("taxonomy_term_reference"),
            "settings"      => array(
                "size"              => 60,
                "autocomplete_path" => "taxonomy/autocomplete",
            ),
            "behaviors"     => array(
                "multiple values"   => FIELD_CARDINALITY_UNLIMITED,
            ),
        ),
    );
}

I have hook_field_widget_form

function MODULE_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element)
{
    $tags = array();
    foreach ($items as $item)
    {
        $tags[$item["tid"]] = isset($item["taxonomy_term"]) ? $item["taxonomy_term"] : taxonomy_term_load($item["tid"]);
    }

    $element += array(
        "#type"                 => "textfield",
        "#default_value"        => taxonomy_implode_tags($tags),
        "#autocomplete_path"    => $instance["widget"]["settings"]["autocomplete_path"] . "/" . $field["field_name"],
        "#size"                 => $instance["widget"]["settings"]["size"],
        "#maxlength"            => 1024,
    );

    return $element;
}

I have hook_field_widget_error

function MODULE_field_widget_error($element, $error, $form, &$form_state)
{
    form_error($element, $error["message"]);
}

Here I am creating the field of the content type

field_create_field(
    array(
        "field_name"    => "field_MODULE_tags",
        "type"          => "taxonomy_term_reference",
        "bundles"       => array(
            "node" => array(
                "CONTENT_TYPE",
            ),
        ),
        "cardinality"   => "-1",
        "settings"      => array(
            "allowed_values" => array(
                array(
                    "vocabulary" => "TAXONOMY_LIST",
                    "parent"     => 0,
                ),
            ),
        ),
    )
);

field_create_instance(
    array(
        "field_name"    => "field_MODULE_tags",
        "entity_type"   => "node",
        "label"         => "Tags",
        "description"   => "",
        "bundle"        => "CONTENT_TYPE",
        "widget"        => array(
            "weight"    => 1,
            "type"      => "MODULE_taxonomy_autocomplete",
            "settings"  => array(
                "size"              => 60,
                "autocomplete_path" => "taxonomy/autocomplete",
            ),
        ),
    )
);

All of this appears to work fine, the content type shows the correct field, the auto complete works great, but when I try to save a new node of the custom type, I get the following error:

PHP Fatal error:  Cannot unset string offsets in /modules/field/field.default.inc on line 41

If I look at field.default.inc file I see

function field_default_extract_form_values($entity_type, $entity, $field, $instance, $langcode, &$items, $form, &$form_state) {
  $path = array_merge($form['#parents'], array($field['field_name'], $langcode));
  $key_exists = NULL;
  $values = drupal_array_get_nested_value($form_state['values'], $path, $key_exists);
  if ($key_exists) {
    // Remove the 'value' of the 'add more' button.
    unset($values['add_more']);
    $items = $values;
  }
}

where line 41 is unset($values['add_more']);

If I output $values, I get a string where unset is expecting an array.

How can I make my value an array?

I've tried using hook_form_alter to add a custom submit function so I can manipulate the value but the custom submit never gets fired (which is weird).

hook_node_validate was how I was able to fix this issue.

function MODULE_node_validate($node, $form, &$form_state)
{
    foreach ($form as $field => $field_data)
    {
        $field_info    = field_info_field($field);
        $instance_info = field_info_instance("node", $field, "CONTENT_TYPE");

        // since this field returns a string when an array is required, we need to correct
        // the data here before it goes any further.
        if ($instance_info["widget"]["type"] == "MODULE_taxonomy_autocomplete")
        {
            // Recieved: string
            // Expecting: array(array("tid" => TID),)
            $tag_names = explode(",", $form_state["values"][$field][$node->language]);
            $form_state["values"][$field][$node->language] = array();
            foreach ($tag_names as $tag)
            {
                $term = taxonomy_get_term_by_name($tag, $field_info["settings"]["allowed_values"][0]["vocabulary"]);
                $term = array_shift($term);

                $form_state["values"][$field][$node->language][] = array("tid" => $term->tid);
            }
        }
    }
}


Custom entity, entity_save() leads to PDO Exception? I have built a custom entity called 'person'.

In a module called 'beautify' I use a hook.

Inside this hook I want to create an instance of this object with bundle 'person'. (entity: 'person', bundle: 'person')

In my bundle person I have different fields created by the fields UI. One of these fields is called 'field_person_copy'. The colums of this table called 'fields_data_fields_person_copy' are created by the drupal system:
entity_type, bundle, deleted, entity_id, revision_id, language, delta, field_copy_person_value.
The field is required.

I want to use the drupal system to create new persons, not a db_inject.

  function beautify_contact_person($message){
  // dpm($message);
  $e = entity_create ('person', array(
    $entity->name = $message['params']['last_name'],
    $entity->field_person_copy['und'][0]['value'] = 'NO',
    ));
  //dpm($e,'Instanziiert eine entity');
  entity_save('person', $e);

(Testing with entity->save let the system say that this method is undefined.)

This leads to the following error message:

  PDOException: SQLSTATE[23000]: Integrity constraint violation:
  1048 Column 'entity_id' cannot be null: INSERT INTO {field_data_field_person_copy}
  (entity_type, entity_id, revision_id, bundle, delta, language, field_person_copy_value)
  VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2,
 :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5,
 :db_insert_placeholder_6); Array ( [:db_insert_placeholder_0] =>
 person[:db_insert_placeholder_1] => [:db_insert_placeholder_2] => [:db_insert_placeholder_3]
 => person [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und
[:db_insert_placeholder_6] => NO ) in  field_sql_storage_field_storage_write()
(Line 451 von /home/duke/sites/mia-casa/modules/field/modules/field_sql_storage/field_sql_storage.module).

which means that the system doesn't generate the entity_id and fuels it in the function.

So is that a bug of the entity_api or from me? (I hope the latter) ;)

In my custom_module to build the entity, I only overwrote the function "buildContent" in the class EntityApiController, so create, save and update is not influenced by me.

Thx in advance,

maen

The problem is centred around this bit of code:

$e = entity_create ('person', array(
  $entity->name = $message['params']['last_name'],
  $entity->field_person_copy['und'][0]['value'] = 'NO',
));

It's sort-of-technically-valid PHP (though you don't have a variable named $entity in scope), but certainly isn't doing what you expect. It's almost like you're trying to apply a feature from another language (like object initialisers from C# maybe).

I'm guessing somewhat, but I imagine what you're trying to do is:

$e = entity_create ('person', array(
  'BUNDLE_KEY' => 'BUNDLE_NAME',
  'name' => $message['params']['last_name'],
));

$e->field_person_copy[LANGUAGE_NONE][0]['value'] = 'NO';

entity_save('person', $e);

Or maybe

$e = entity_create ('person', array(
  'BUNDLE_KEY' => 'BUNDLE_NAME',
));

$e->name = $message['params']['last_name'];
$e->field_person_copy[LANGUAGE_NONE][0]['value'] = 'NO';

entity_save('person', $e);

Where BUNDLE_KEY and BUNDLE_NAME are whatever you have set up for your entity type.


How to set/display select options in selectbox using form-api I have created a form to allow users to enter some details but I also need to display some mysql data into that form. The contents and fields of the form are displayed in a tabular format. I just want to know the right way to display mysql data in one of the table columns along with the form fields.
How can i display select options in selectbox using form-api ?

You can make use of theme_table to make a table view.
You can use form-api inside the table as you wish.

Sample code for creating table.

$header = array();
$rows = array();
$rows[] = array(
    array('data' => 'Head1', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head2', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head3', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head4', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head5', 'rowspan'=> 2, 'header' => 1),
    array('data' => 'Head6', 'colspan'=> 6, 'header' => 1),
);
$rows[] = array(
    array('data' => 'SubHead6-1', 'header' => 1),
    array('data' => 'SubHead6-2', 'header' => 1),
    array('data' => 'SubHead6-3', 'header' => 1),
    array('data' => 'SubHead6-4', 'header' => 1),
    array('data' => 'SubHead6-5', 'header' => 1),
    array('data' => 'SubHead6-6', 'header' => 1),
);

return  $output .= theme('table', $header, $rows);

To make a select box with db values you can try this

$query = "SELECT * FROM {tablemanme}";
$query_result =  db_query($query);
while (($data = db_fetch_object($query_result )) !== FALSE) {
  $opt[$data->id] = $data->name;
}

$form['select'] = array(
    '#type' => 'select',
    '#options' => $opt,
);

Good luck.


Complex where condition with entity field query (D8) Is there a method similar to the D7 dynamic query where method to allow us to use arbitrary snippets of SQL to restrict the result set?

Take the following MYSQL query as an example:

SELECT id, publish_date
FROM teaching_period
WHERE publish_date IS NULL OR UNIX_TIMESTAMP(STR_TO_DATE(CONCAT(publish_date, ' 23:59:59'), '%Y-%m-%d %H:%i:%s')) > UNIX_TIMESTAMP(CURRENT_TIMESTAMP)
ORDER BY created DESC
LIMIT 0, 1

How can I create the where statement in this query using the D8 entity query API? Is it even possible?

No, in general, it is not. Entity query is not an SQL-query replacement, it designed to also work with other storage backends, so you can not use 100% of the SQL features.

If you need that, you have to implement your own SQL query.

That said, I don't quite understand why your special SQL logic is even necessary, date fields can be queried natively, e.g. publish_date > :date should just work, as long as you provide the date in the correct format as and timezone input.

See How to do a date range entityQuery with a Date only field in Drupal 8?


Stop User From Publishing an Event if the Start Date is Before a Certain Month Using Rules I'm working on a development site that will not be launching for a few months. I'm looking to create a rule that will not allow a user to publish an event if the event's start date is prior to launch. I am using the date field in this content type.

How could I accomplish this with rules? Thanks!

I'm not sure that Rules is required to do that.

I would rather use Field Validation module. It is able to configure complex validation rules for any field.

In its submodule called "Field validation extras" there's a validation rule that will help you, it's called "Date range2". You can set a specific minimum date according to your needs, and a far enough maximum date.


redirect to another page on webform submit using [current-page:query:?] token I am trying to configure a webform to redirect to another page after submission by including the redirect location in the url:

http://mysite/content/barb?destination=content/discus

According to webform there is a token [current-page:query:?] which I assume can extract the value of destination.  I have including it in the webform redirect to custom URL of the form, but I cant get it to work.

I have tried:

[current-page:query:?]
[current-page:query:?destination]
[current-page:query:destination]

But nothing seems to work. What is the correct way of using this token to get a variable from the URL?

I've found that no token is required for this...

You can select Confirmation page as the redirect location, then the ?destination= parameter will just work. Not sure that this is a documented feature, though.

See also https://drupal.stackexchange.com/questions/120466/webform-redirect-to-referring-page-on-submit-not-showing-message which highlights a downside to this method.


is getString() returning translated content? $links['node']['#links']['node-readmore']['attributes']['title'] =

$entity->field_anc_label->getString();

I am using getString() value , need to know whether its translated or we need to call it under t() to get it translated ?

you can check translation with something like

if ($entity->get('field_anc_label')->getFieldDefinition()->isTranslatable()) {
  // The field translation is enabled.
$links['node']['#links']['node-readmore']['attributes']['title'] = $entity->field_anc_label->getString();
}else{
$links['node']['#links']['node-readmore']['attributes']['title'] =
t($entity->field_anc_label->getString());
}


Can I override/modify an existing hook_widget_info for an existing CCK field type I want to modify the default Link field, so that instead of just a text field it will always have a Validate Button next to it (for active checking).

I don't want to create a new Widget, I want to override the basic link, so that any link field deriving from the original will inherit these changes. Also of course, is it then possible to override the override (for a specific link variant - say, Twitter link, to change this new button to a checkbox or just remove it for that type)?
Can I just add in my custom module the link_widget_info() function?

Thanks!

You can do that with hook_field_widget_form_alter

hook_field_widget_form_alter(&$element, &$form_state, $context)

  Alter forms for field widgets provided by other modules.

The function parameters there allow you to check and target specific cases as needed.


Menu callback rendering node xxx I want to render node/7 on /mymodule/info. I don't want to use path to cover it. What callback function shall I use?

function mymodule_menu() {
  $items = array();

  $items['mymodule/info'] = array(
    'title' => t('My module'),
    'description' => t('My module description'),
    'page callback' => ?????????,
    'type' => MENU_CALLBACK,
   );

  return $items;
}

You have to call the same callback issued from node/%node menu i.e. node_page_view :

function mymodule_menu() {
  $items = array();

  $items['mymodule/info'] = array(
    'title' => t('My module'),
    'description' => t('My module description'),
    'page callback' => 'node_7',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function node_7(){

include_once(drupal_get_path('module','node') . '/node.pages.inc');

return node_page_view(node_load('7'));

}


Drupal 7 Bartik theme drop down menu Possible Duplicate:
  Drop down menu in drupal 7

How can I add the drop down menu item to the navigation menu in the Bartik theme?

You can able to do it using Nice Menus module. Check here for detailed step by step tutorial on how to use nice menus module.

  Nice Menus enables drop-down/right/left expandable menus. It uses only
  CSS for most browsers, with minimal Javascript for IE6. (Version 2
  uses the Superfish jQuery plugin for all browsers, with an option to
  disable JS, and falls back to CSS-only for browsers that can handle
  it.)


Webform - trying to set submit handler On a Drupal 7 Webform I've added a button using a markup field like this:

<button name="get" value="" type="submit" class="primary-submit submit" id="get">
Get Address
</button>

I am directing it to a submit handler like this:

function new_webform_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'webform_client_form_88') {
    $form['submitted']['name']['get']['#submit'][]='new_webform_get_submit';
    dpm($form);
  }
}

I can tell the button #submit is being changed, but the whole form is submitted instead of executing the handler code. What am I doing wrong?

Turns out the form was not actually being submitted but the custom handler was not being processed because the form validation was failing. I disabled it with

$form['submitted']['name']['get']['#limit_validation_errors']=array();

and now the handler works.