Get historical stock level in Ubercart Is there a way to find out the stock level of an Ubercart product on a given date?

I can a) get the total number of items sold between a given date and today, and then b) subtract that number from the current stock level. That's not very useful, though, since the client will likely update the stock level in the interim.

If Ubercart logged changes in stock, something like this, then I think I'd be good to go:

| nid | stock_level | datestamp  |
----------------------------------
| 23  | 15          | 1303707600 |
| 23  | 25          | 1327471200 |

Ubercart doesn't store that information by default, and there's no way to do it without patching the uc_stock.module file.

The reason is that the uc_stock_set() function updates the uc_product_stock database table, but doesn't invoke any hooks to allow other modules to act on that information.

If you create a patch that changes the uc_stock_set() function to this:

function uc_stock_set($sku, $qty) {
  db_query("UPDATE {uc_product_stock} SET stock = %d WHERE sku = '%s'", $qty, $sku);
  $stock = db_fetch_object(db_query("SELECT * FROM {uc_product_stock} WHERE sku = '%s'", $sku));
  module_invoke_all('uc_stock_set', $stock);
}

then you'll be able to write a custom module that implements the new hook_uc_stock_set() hook to save timestamp data to a custom table. That would look something like this:

function MYMODULE_uc_stock_set($stock) {
  db_query("INSERT INTO {MYMODULE_table} (sku, stock_level, datestamp) VALUES ('%s', %d, UNIX_TIMESTAMP())", $stock->sku, $stock->qty);
}

The uc_stock module works with the sku rather than the node id so it would be best to store that in your custom table.

The other hook you'll need to implement is one already provided by the uc_stock module, hook_uc_stock_adjusted(). Your module's implementation would look like this:

function MYMODULE_uc_stock_adjusted($sku, $prior_stock_level, $qty) {
  $stock_level = $prior_stock_level + $qty;
  db_query("INSERT INTO {MYMODULE_table} (sku, stock_level, datestamp) VALUES ('%s', %d, UNIX_TIMESTAMP())", $sku, $stock_level);
}


SSH authentication failed, please provide another key- Acquia Team,

I'm trying to Clone my Cloud website and use it in Dev desktop.

I have generated 4096 keygen and add public key in Acquia Cloud.

I am using Latest Acquia Dev Desktop on Windows 10.

I am getting below error-

  Blockquote
  SSH authentication failed, please provide another key- Acquia
  Blockquote

Anyone facing similar issue?

Thanks,
SS

I had this problem too with Dev Desktop 2.
It was my first time trying to pull an Acquia cloud site to local.
I generated a key, added my public key to my Acquia profile, but still kept getting Authentication errors.

What fixed it for me was...
SSH into the server (little square next to the SSH path in dev desktop), then just close it.
I was then able to pull the cloud site to my local machine.


How to remove "catalog" from Ubercart Catalog View URL I need to remove the word "catalog" from the URL when viewing a category of products. I am using the stock uc_catalog view. Its Page (Table) display has a URL of "/_catalog". What can I change so that the word catalog will be completely excluded?

For example, I'd like my category URLs to be like so:

  mysite.com/shirts

  mysite.com/pants

instead of:

  mysite.com/catalog/shirts

  mysite.com/catalog/pants

Thanks!

Logical we can't change the way the catalog link generation of Ubercart. The format must be catalog/term_id (with default way) and catalog/term_name (With pathauto module). For me the only thing we can deal with that is creating the URL Aliases manually.


Allow users to submit content that is approved before it is published I want to allow users to submit the content to my site, but the content must be first approved, and then it can be published.

Is there a module that do this? Which code should I write for such module, if one doesn't exist?

You might want to try: http://drupal.org/project/workflow & http://drupal.org/project/formfilter

If you create a workflow you can set it to only allow users to create content in the 1st state, something like "needs review". Then, an admin can come in and progress to the 2nd sate, say to "published".

I used an action and trigger to automatically publish any content placed into the 2nd state.

You can use the form filter to disable the ability to set the content straight as published in the normal node edit form.

Ideally you will want some type of approval queue too, you can use the default Workflow summary but I think this requires views.


Content type term reference field selected or populated from URL parameter I need to be able to click on a link, that goes to node/add/example. and populate a term reference field with a URL parameter. I thought i could be able to do this through the default value, but i guess it isn't possible. Anyone have any other ideas to try?

For drupal 6:You can put a link using following code in your node.

function hook_link($type, $object, $teaser = FALSE) {
  $link = array();

  if ($type == 'node') {
    $link['yourlinkname'] = array(
      'title' => t('Your link'),
      'href' => 'node/add/example',
      'attributes' => array(
        'title' => 'Your link',
      ),
    );
  }
  return $link;
}

For drupal 7:You can put a link using following code in your node.

function hook_node_view_alter(&$build)
{
   $build['links']['node']['#links']['example-mylink'] = array(
    'title' => t('Your linkname'),
    'href' => 'node/add/example',
    'html' => TRUE,
    'attributes' => array(
      'title' => 'Your link',
      ),
   );
}


Exclude tpl files in multisite theme I'm working in a multisite, the theme had page--front.tpl.php file for the main site, but I want to exclude this file in the other sites.

How can I do this?

Its trickier to 'remove' the template on sites you don't want it on because Drupal will always recognize the file format as a valid template and add it to theme suggestions. An easier option would be to affirmatively add it using a custom module only on the sites you want it on. For example, following this answer, here's how you would register a particular template file only on the subsites you want by just selectively enabling the module where you need it:

/*
 * Implementation of hook_theme().
 */
function YOUR_SUBSITE_MODULE_theme($existing, $type, $theme, $path){
  return array(
    'YOUR_SUBSITE' => array(
      'variables' => array('content' => NULL),
      'file' => 'page--front', // place your file in 'theme' folder of you module folder
      'path' => drupal_get_path('module', 'YOUR_SUBSITE_MODULE') .'/theme'
    )
  );
}

function YOUR_SUBSITE_MODULE_page(){

  // some code to generate $content variable

  return theme('YOUR_SUBSITE', $content); // use $content variable in moon.tpl.php template
}


Replacement for drupal_add_http_header() I have a custom module which are basically APIs, hence require headers like content-type to be added to the responses. I was using drupal_add_http_header() in Drupal 7, but it seems to be deprecated in 8. Is there any replacement?

I did read about it on the Drupal website talking about Symfony object Response, but I am unable to use that either.

If you want to modify the headers of a response, you need to use an EventSubscriber. Symphony doesn't have a hook system, but instead uses an event/emitter system. Since it's Symphony driving the request/response cycle, you basically needs to integrate with Symphony to do this.

You could take a look at \Drupal\Core\EventSubscriber\FinishResponseSubscriber to see how this is done, the gist of it is this:

/**
 * Add custom headers.
 */
class HeaderResponseSubscriber implements EventSubscriberInterface {
  public function onRespond(FilterResponseEvent $event) {
    $response = $event->getResponse();
    $response->headers->set('Some-Header', 'some value');
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = array('onRespond');
    return $events;
  }
}

Note in the above code all use statements have been excluded, also you need to register your class as a event_subscriber service, this is done in your module's module_name.services.yml file like this:

services:
  name_of_service:
    class: Drupal\Full\Namespaced\Path\To\Class
    tags:
      - { name: event_subscriber }

You can add arguments (other services) that your class will depend on in the services file like normally.


Input form to create content type(s) Use Case

We will have users submitting forms that will then be mapped to one of three content types based on the information they've entered.  We don't want to burden the user with trying determine what content type to use on their own.  They should just enter the data and then we'll make the call based on that.

Best Approach

The way I see us doing this is creating a webform that we then hook into with a custom module that programatically creates the new nodes of the appropriate content type.

I wanted to check with the brain trust here that this makes sense for our use case and there isn't a module to use that makes more sense.

Thanks.

That sounds like a fine solution. The one thing I would suggest is to NOT use the webform module. I think you should just create the custom form with the Form API.

You'll spend more time overriding the unneeded behavior and features of webform than you would creating the form from scratch with FAPI.


Using Date Popup widget with custom format Date field I need to save a date in a very specific format: (2013-03-09\T17:01:34.1\Z to be precise).

I also need to allow users to edit this date after it's been saved.

I want to use the Date Popup submodule of Date to allow users to enter dates. However, it doesn't seem to support custom formats. When I enable Date Popup, I see that I lose seconds granularity, and I can no longer use custom formats at all.

Is there a way to use custom formats with Date Popup? If not, is there a recommended way of adding a popup calendar to my date field in a way that will generate dates in my custom format? Does anyone know why the developer of Date made Date Popup incompatible with custom formats?

Drupal's Date module includes a 'Date Popup' sub-module which handles date pop-up widgets. These widgets are available in the FAPI (form api) and can be configured with custom formats via the #date_format property.

You could implement hook_form_alter() and change the #date_format property on the date field you're working with. I believe this property will support all formatting available in PHP's standard date() function.


Complete checkout for all orders Drupal commerce I am working with Drupal Commerce and Commerce Billy to generate invoices. My question is :

In Complete checkout process I want to edit all orders status to
"Invoiced" !! .

I already created this Rules Component and it works fine. With component I can add 1 order for me(admin) and other orders to user concerned , is that make sense.

So what I want to do is : after complete checkout process I want to change all these orders status to "invoiced"

{ "rules_add_prod_to_cart_6" : {
"LABEL" : "Add Prod to cart 6",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "commerce_cart" ],
"USES VARIABLES" : { "commerce_product" : { "label" : "Commerce Product", "type" : "commerce_product" } },
"IF" : [
  { "entity_has_field" : { "entity" : [ "commerce-product" ], "field" : "field_user_concerned" } }
],
"DO" : [
  { "commerce_cart_product_add_by_sku" : {
      "USING" : {
        "user" : [ "site:current-user" ],
        "sku" : "[commerce-product:sku]\t",
        "quantity" : "1",
        "combine" : "1"
      },
      "PROVIDE" : { "product_add_line_item" : { "product_add_line_item" : "Added product line item" } }
    }
  },
  { "commerce_cart_product_add_by_sku" : {
      "USING" : {
        "user" : [ "commerce-product:field-user-concerned" ],
        "sku" : "[commerce-product:sku]\t",
        "quantity" : "1",
        "combine" : "1"
      },
      "PROVIDE" : { "product_add_line_item" : { "product_add_line_item2" : "Added product line item 2" } }
    }
  }
]

}
}

Example :
SKU | Label | Price | User |

001 | Product 1 | $10 | Userexample1 |
002 | Product 2 | $40 | Userexample2 |
003 | Product 3 | $20 | Userexample1 |
004 | Product 4 | $70 | Userexample2 |

what I already done:

So after Clicking on "Add product and generate order" button :
In the above example I get 3 orders
the owner of the first order = [site:current-user] and it will return :
All Products (Product1,Product2,Product3,Product4)
The owner of the second order =  Userexample1 and it will contain
Product1 and Product 3
The owner of the last order = Userexample2 and it  it will contain
Product2 and product 4

So the order status of all those orders = Shopping cart (because we didn't complete the checkout yet), and when we complete the checkout it will change ONLY the FIRST ORDER status to "Invoiced", because [site:current-user] is the owner of it.

I want to change all the above orders status when "Complete checkout process" event is fired !

Please see images below:

After Clicking on "Add products to cart and generate orders"

"New 3 orders"

Complete checkout process

First order status = Invoiced , BUT THE TWO OTHERS DOSEN'T CHANGE

Is that possible ? How could I do that using Rules Module ?

I fixed this issue by adding this PHP code:

$orders = commerce_order_load_multiple(array(), array('status'=>'cart'), TRUE);
foreach($orders as $order){
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
    foreach($order_wrapper->commerce_line_items as $line_item_wrapper){
        $product = $line_item_wrapper->commerce_product;
        $node_product = $node_wrapper->field_product;
            $order_wrapper->status = 'invoiced';
            $line_item_wrapper->save();
            $order_wrapper->save();
    }
}


Form handler submit don't work I have a submission handler for my custom form that doesn't work. I tried many solutions, but nothing works.

My_Custom.module

 [...]
function tournament_menu() {
    $items['tournament/newteam'] = array(
        'title' => 'Créer une nouvelle équipe',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('form_newteam'),
        'access callback' => TRUE,
        'file' => 'form_tournament.inc',
    );
}
 [...]

form_tournament.inc

function form_newteam ($form, &$form_state) {

 [...]
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Créer',
    );
    $form['actions']['submit']['#submit'][] = 'form_newteam_submit';

    return $form;
}

function form_newteam_validate($form, &$form_state) {
    //Validation logic
}

function form_newteam_submit($form, &$form_state) {

    drupal_set_message("Bla bla submit !");

}

My validation function works.

I try all this code In form_newteam() function.

$form['actions']['submit']['#submit'][] = 'form_newteam_submit';
$form['#submit'][] = 'form_newteam_submit';
$form['#submit'] = array('form_newteam_submit');
$form['submit'] = array(
 '#type' => 'submit',
 '#value' => 'Créer',
 '#submit' => array('form_newteam_submit'),
);

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Créer',
  '#submit' => 'form_newteam_submit',
);

Go back and scrutinize your validation function. The code you are showing here actually works, so the problem is something you did not include in your sample.

For the reference, the working implementation over here is:

function form_newteam ($form, &$form_state) {
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Créer',
    );

    return $form;
}

function form_newteam_validate($form, &$form_state) {
    drupal_set_message("valid");
}

function form_newteam_submit($form, &$form_state) {
    drupal_set_message("submit");
}

Please note that your function names do not conform to the drupal coding standards. Function names must be prefixed with the module name. Therefore you should name your functions like this: tournament_newteam or tournament_newteam_form. If those are administrative forms, stick them into tournament.admin.inc otherwise place them into tournament.pages.inc.


Lack of permissions on sites/default/files I currently manage a Drupal install on a shared university computer (i.e. I don't have root access to the box), but the sites/default/files directory was created with all permissions and ownership set to a unknown user (as is shown below), therefore I have absolutely no way to delete or change anything in this folder without using the Drupal interface or contacting the sysadmin.

I believe the owner of these files is the webserver's user (which is on another box). Is there any way to change the uploaded files permissions/owner within Drupal (or at least delete/chown this folder)?

myself@sparta:~/public_html/drupal/sites/default/files$ ls -la
total 252
drwxrwxr-x 4     48        48   4096 Set  3 11:43 .
dr-xr-xr-x 3 myself  students   4096 Set  2 12:07 ..
-rw-r--r-- 1     48        48 227057 Set  3 11:43 Estatuto.pdf
-rw-rw-r-- 1     48        48     93 Set  2 12:30 .htaccess
drwxr-xr-x 2     48        48   4096 Set  3 11:25 imagefield_thumbs
drwxrwxr-x 2     48        48   4096 Set  3 10:47 languages
-rw-rw-r-- 1     48        48   2666 Set  3 11:25 posse.jpg

Thanks!

You can install the devel module and visit /devel/php on your site. This will give you a place to run ad-hoc PHP from where you could run chown() or something similar on the files in question.

I'm sure it doesn't need to be said but be careful, the last thing you want to do is make a mistake with permissions!


From where d7 render comment_form Can i know from where drupal core render comment_form Actually what i mean is what is the location of file which bear comment_form ..In my d7 folder , i am now testing it on localhost win7.I want to know it so that i can easily do change in comment form texts, do change in comment buttons, is this possible?

@rakibtg, To change the comment button text you are not supposed to change any comment module which is available in the core. Simply Never hack Core!!!

For your question, to change the comment button text,

1.You need to write up a custom module with hook_form_alter,

  function mymodule_form_comment_form_alter(&$form, &$form_state, $form_id) {
     $form['actions']['submit']['#value'] => t('Post Comments');
 }


Why is my form themed as table not posting data correctly, or displaying correctly? I have created a form in the admin.

$form['things'] = array(
  '#prefix' => '
',
  '#suffix' => '
',
  '#tree' => TRUE,
  '#theme' => 'table',
  '#header' => array(t('Field Label'), t('Field Name'), t('Location'), t('Stuff')),
  '#rows' => array(),
);

I then add each row to it like:

foreach ($type_fields as $field_name => $attrs) {
  $stuff = array(
    '#type' => 'textfield',
    '#default_value' => $attrs['stuff'],
  );

$form['things']['#rows'][] = array(
  array('data' => 'label'),
  array('data' => $field_name),
  array('data' => $field_name),
  array('data' => $stuff),
);

}

The form looks great! But the first problem is the value assigned to #default_value is not showing up in the form.  When I change it to #value the correct value DOES show up. So I wonder how this should be done? The Drupal documentation says #value should not be used with forms although it is functioning exactly how I would expect it to function.

The main problem is when I fill in some test data in one of the textfields and submit it: I do not see any of the submitted values in my _submit function.

Neither $form nor $form_state contains any of the values I input into the text fields.

I wonder if this is because I am rendering #theme => "table"?  Has any one ran into this issue? Any Ideas on changes I can make that would allow me to see the values I am inputting when I post the form to the _submit function?

The problem is that your textfield elements are located under the #rows property of your render array.

Drupal sees any array key beginning with # as a property/attribute, and any array key not beginning with that as an element that needs to be recursively attended to. As such the children you've got under #rows will be ignored by the form builder.

Since theme_table will run on the render array, your form elements will actually be rendered out to the screen, but the form won't have any knowledge of the values (as they are not technically children of the form).

In my experience the best way to do this sort of thing is to use a specific theme function on the element:

function MYMODULE_theme() {
  return array(
    'MYMODULE_textfield_table' => array(
      'render element' => 'element'
    )
  );
}

function theme_MYMODULE_textfield_table($vars) {
  $element = $vars['element'];

  $rows = array();
  foreach (element_children($element) as $key) {
    $rows[] = array(
      array('data' => 'label'),
      array('data' => $element[$key]['#extra_data']['field_name']),
      array('data' => $element[$key]['#extra_data']['field_name']),
      array('data' => render($element[$key]))
    );
  }

  $header = array(t('Field Label'), t('Field Name'), t('Location'), t('Stuff'));
  return theme('table', array('header' => $header, 'rows' => $rows));
}

Then in your form function you would use code like the following

$form['things'] = array(
  '#prefix' => '
',
  '#suffix' => '
',
  '#tree' => TRUE,
  '#theme' => 'MYMODULE_textfield_table'
);

foreach ($type_fields as $field_name => $attrs) {
  $form['things'][] = array(
    '#type' => 'textfield',
    '#default_value' => $attrs['stuff'],
    '#extra_data' => array('field_name' => $field_name)
  );
}

After that your textfields should be registered in the form and you should be able to see the value in the $form_state array as normal.


Problem ignoring in a view the images inside the .views field body and the minimum number of characters? I need to remove the images appears in the view in the field body. I have tried the following code.

.view-mydisplay .views-field-body {
    display:none;
}

However, I cannot see the image but the "maximum length of characters" of my field-body are not showing completely. If I remove the image manually in the body, then the characteres are complete in the view.   Seems how if the image were counted like character.

For example if I have 300 max. characters in my view and I put an image only are showed 100 characters, after remove the images with css.  If I don't put the image in my body, the view shows the 300 characters configured in the view.

The Smart trim module might be helpful. You'll be able to trim units by words or characters on stripped HTML.

  After installing and enabling Smart Trim, you should see a "Smart
  trimmed" option in the format dropdown for your text fields. With
  smart trim, you have control over:

  The trim length
  Whether the trim length is measured in characters or words
  Appending an optional suffix at the trim point
  Displaying an optional "More" link immediately after the trimmed text
  Stripping out HTML tags from the field


Using git to fetch changes from testing version to live website I am maintaining and developing a Drupal website and have a testing/development version of the site in a subfolder of drupal instalation. I started to learn git and I am wondering about how could I use it in my development process. I came up with following solution:

Make a git repository for live site and clone it in the test subfolder (which will be added into live site's .gitignore file). Make some development in the test directory, test it and when I'm satisfied, switch to the live site repository, fetch and merge the changes.

Since I am a newbie to git, I'd like to know if this approach can be succesfully used, or if not, which aspects should I change/or come up with completely different solution.

I would use a post-update hook that will pull changes into the webroot and perhaps also run some other commands like clearing the caches etc.

First you need to create a bare repository:

mkdir /var/git/<repo-production.git>
cd /var/git/<repo-production.git>
git init --bare
cp hooks/post-update.sample hooks/post-update
chmod +x hooks/post-update

You then need to modifiy your post-update to something like:

#!/bin/sh
cd /var/www/<your_www_root> || exit
unset GIT_DIR
git pull hub master
# if you have drush installed you clear caches here
# drush cc all
exec git update-server-info

Then you need to clone out the repository in your webroot:

cd /var/www
git clone /var/git/<repo-production.git> <your_www_root>
cd <your_www_root>
git remote rename origin hub

Then on your local machine you add the remote like this:

git remote add production ssh://root@example.com:/var/git/<repo-production.git>

Of course you need to change the above to match your own username, hostname and path to your repository.

You should now be able to push changes to the remote repository, than in turn will deploy any changes into the webroot.

git push production

Notice that you can setup another bare repository for your staging environment and modify the above so it checkout the code to a different location. A nice approach would then be to add it using git remote add staging <path_to_staging_repoistory>. Done this you are able to push your code either to production using git push production or to staging using git push staging.


Detecting one account being accessed from multiple computers at the same time I need to detect member access to the same account from different computers or web browsers at the same time with same email and password?

Are there any options or modules to get this information?

If you just want to log the user out to prevent multiple logins at the same time, then you could use the Session Limit module.

  Session Limit allows administrators to limit the number of
  simultaneous sessions per user.

Also taken from the project page:

  Assuming the session limit is 1, if a user is logged in to a Drupal site from their work computer and they log in from their home computer, they would be forced to either log off the work computer session, or abort their new login from home.


Setting up sub sections with their own editors I'm new to Drupal (v7.21) and hoping to use it for a site that contains several sections each run by a separate owner and their team of editors. Just wanted to ask if it would be possible and how I could go about it. The type of flow I'm looking for is:

Main Site
- Forum
- Store

  Section One
  - Blog
  - Book

  Section Two
  - Blog
  - Book

As normal the Admin would have overall control with each section having an 'owner' that can edit their sections Blog, Articles etc. The owners would also be able to give an 'editor' role to other users so they can edit content within the section.

It would be helpful if the urls for the site were:

domain.com/
domain.com/forum/
domain.com/store/

domain.com/sectionone/
domain.com/sectionone/blog/
domain.com/sectionone/book/

domain.com/sectiontwo/
domain.com/sectiontwo/blog/
domain.com/sectiontwo/book/

If I haven't included enough information please let me know. Any help would be greatly appreciated.

Organic Groups is probably what you're looking for. Checkout the following help resources.

the module's project page: http://drupal.org/project/og
NodeOne's Learn Organic groups
Modules Unraveled's Organic Groups


Content Type Fields, populate field with usable data when adding new content Trying to build a site that majoritly just uses Views and data structures defined within Drupal itself (aka: almost no programming on my end, though if it boiled down to it I will)

Trying to make a Music Album manager. Each album is a content type, and each track is a content type. I have in the Track content type a field called "Album" as a drop-down list which I wish to populate with existing Album records.
Problem is, I have no idea how I'm supposed to do that..

Is there a method? is there a module? is there anything I can do? There must be a way somewhere, I would hate to have to drop the entire process here and start from scratch again

Don't worry you don't need to start again, this is such a common use case there are actually 3 modules out there that you can choose between.

Entity Reference
References (can be considered deprecated in favour of entity reference).
Relation (allows for complex relationships, probably overkill for your case)

All 3 will allow you to add a field to your track content type that references an album node. You can choose from a select list, radio/check buttons or autocomplete widget out-of-the-box but I'm sure there are add-ons available if you need them.


how to modify drupal 7 mysite/user/login and mysite/user/registration pages "in-place"? I am trying to find out a way to add fields/modify existing fields/theme the default Drupal 7 login/registration pages in-place.

What I mean "in-place" is to find a way to not create new login/registration pages through creating "page--user--register.tpl.php" files.

I am looking for a way to add/modify/theme the mysite/user/login and mysite/user/registration pages without having to create page--user--register.

However, if overriding the hook_theme() in "template.php" and creating "page--user--register.tpl.php" file is the only way, then is there a way to have it use the same theme as the rest of the pages? I can make the custom registration page have the same theme through coyping code from "page.tpl.php" and pasting it in my "page--user--register.tpl.php" file, but this seems wrong to me.

Any help or comments are appreciated.

If you want add form fields to either the login or registration form(s) you will have to write custom PHP code in a module file to make any use of the fields.

The forms are just blocks on the page, and should inherit or reuse block.tpl.php pretty much everywhere. Since they are just blocks, sitewide css can target them specifically once you've made them.

The drupal login and registration system is fairly pluggable, you can "inject" your own validation code (to handle your own custom fields) and authentication pretty much however you wish.

A useful tutorial/blog post might be:
http://omegadelta.net/2011/03/23/custom-authentication-with-drupal-7/

It doesn't add custom fields, but does modify the existing drupal login behavior which is what you're trying to do as well.

In your case you probably want to do something like:

create a custom login/registration block in a module, it simply
loads the default login or registration block as an object.
Implement hook_block family of functions.
hook_form_alter() the block and inject your fields and override the default user authentication validator with your own to consume your fields
(similar to the linked blog posts' _geospike_user_login_form_alter()
function).
define a hook_menu path which outputs a page that
loads/outputs your custom defined block to login or register.

Drupal can do what you want with basically a custom module and like a few hook functions. Your not creating your own user login or registration form, and your not writing your login login validators from scratch -- you are just overriding the pre-existing ones for new ones your basically telling drupal exist now via your module.


Calculate the greater of two values in Rules? I'm trying to set up a rule which sets a CCK field to the greater of two other CCK fields, but calculate a value only has +-*. How do I figure out the greater of two values?

I guess that you can try this to the 'numeric comparison' rule:

here is the lines used with cck fields field_test1 and field_test2:

 <?php $field1 = $form_state['values']['field_test1'][0]['value']; echo $field1; ?>
 <?php $field1 = $form_state['values']['field_test2'][0]['value']; echo $field2; ?>


How to override $page_top variable? I am new to drupal 7 theming. I see that there is a variable called $page_top  in html.tpl.php file, which contains HTML markup for the header section of the body. I want to override this and print my markup. How can I do that in template.php file, or is there any other way?

You override markup by using :

  function template_preprocess_field(&$vars){
    if($vars['element']['#field_name'] == 'field_event_geofield')
     {
          //kpr($vars); //Uncomment to output the $vars array.

           if(isset($vars['element']['#items']['0']['lat']) && isset($vars['element']['#items']['0']['lon'])) { $vars['items']['0']['#markup'] = 'View Map'; } return; }
           }


What module should I install for php? I am trying to import a rule for facebook autopost in Configuration>Workflow>Rules, but after I click import button, I receive the error message below. I don't know which php module I have to install. I have searched on drupal site but I don't figure out which module I have to install.

Regards,

You should enable PHP Filter modules under CORE . Go to /admin/modules and find PHP Filter module and enable

It allows embedded PHP code to be evaluated


Programmatically get View Custom Image filed url I have:
$view = Views::getView('ads');

$view->setDisplay('block_9');

$view->execute();
$view_result = $view->result;

foreach ($view_result as $data) {
  $entity = $data->_entity;
  kint($entity->get('field_image_ads')->getValue());

}

A screenshot of Output Kint:

But I want the image URL also.
Thanks.

Your field_image_ads looks like an entity reference field, so try this:
$entity->field_image_ads->entity->getFileUri();


How to save the definition of an entity? I am trying to figure out if there is a difference between saving an instance of an entity and saving the definition of an entity.

My use case is this:  I wrote a small module that defines an entity, which I then used in other code on my site.  All of this worked just fine, and I thought that once I had created some instances of my entity, and that those instances were stored in my database, I could then disable the little module that defined my entity.  I thought, in other words, that defining an entity would be like defining a Content Type, and that once you had done so the new entity, like a new Content Type, would "stick around".

That, however, is not how things work.  If I disable the little module that defines the new entity, that entity disappears from my system, and the code that uses that entity fails.  Re-enabling the little entity-defining module returns everything to normal and the site works again.

I think I may have missed a step here [entity_save?] but find nothing in the documentation that discusses saving the definition of a programatically defined entity.

Two more things.  First, I have noticed that the "model" module, which provides a template for creating your own entities, exhibits the same behavior that my little module did:  if I disable that module, the entities that I used it to define vanish from my system.  I have also noticed that the Entity Construction Kit [ECK] creates, in addition to the base table, two additional tables, one of which, eck_bundles, looks like it has entity properties.  I have not been willing to disable the ECK, though, because the documentation says that Drupal needs it.

Another way of posing my question would be this:  "Do you have to keep the code that defines your entity in your system, or is there some way of storing the entity definition for subsequent use?"

I am running Drupal 7.39

Yes, the module providing the entity type needs to be enabled for the entity to work correctly, and any module using that entity should include the defining module as a dependency. Drupal modules are generally not factories that produce configuration and can then go away (the major exception being modules generated with the Features module which can behave this way at times), they generally provide ongoing functionality that Drupal will expect to be available on demand.

In your case Drupal loads the class from that module under a variety of conditions (not the least of which is anytime you load an instance of that entity) and so needs to continue to be active as long as you use the entity. That module is also the place to define any special behaviors of the new type of entity you have defined (like changes to the save/load process, or other actions the entity may provide).


Using Drupal 5 Gmap + location. What's the Drupal 7 equivalent? I have an existing Drupal 5 site that I want to port over to Drupal 7.  In my existing site, I have custom CCK types for, for example, a business type such as restaurants.  I have the Location and GMap modules enabled.  When entering a new restaurant, I type in the address of the restaurant and it is geocoded and the node type displays a map.

Now in Drupal 7 I'm trying to figure out how to do the same thing.  I know CCK got partly rolled into Drupal 7.  Which modules should I use for entering in the address info?  I looked at the Location and GMap modules but they're both currently in dev only and I don't want to run development modules on my production site.  So what's the drupal 7 way to handle address info, geocode it, and display a google map?

I found this blog post which looks promising: Placing Users on a Map in Drupal 7 - with Openlayers, Addressfield and Geocoding

It says to use a combination of:
Addressfield
Geofield
Geocode
Openlayers

Except geocode doesn't seem to have an official 7 release

UPDATE

I successfully got this working, using this blog post as a foundation.  The article is talking about adding map data to user profiles.  In my case, I wanted to add map data to content nodes so I didn't need the Profile stuff. I used the following modules (and their dependencies):

Address Field  7.x-1.0-beta2
Geofield   7.x-1.0-beta2
Geocoder   7.x-1.x-dev
OpenLayers   7.x-2.x-dev

Yes, some of these are dev modules which is not ideal, but it seemed unavoidable to get the functionality I wanted.

In the article he talks about using his own fork of the Geocode module, but I found using the Geocoder (note the "er" ending) module (as suggested by the geofield module) instead worked fine.

Overview

In a nutshell this solution uses Address field to hold the address data and geofield to hold the coordinate data and OpenLayers to display the map.  The geocoder module is the glue between the address data and the empty geofield, taking the address data and populating the geofield.  The OpenLayers module uses the geofield coordinates to display the map.

Steps

I created a "Map" in OpenLayers which is basically like a preset of how you want the map to look and behave (e.g, map type, zoom level, etc).  This takes some tweaking to get things setup the way you want them.

Then I added a content type xyz.  In that content type I clicked "Manage Fields" and added an address field (Postal address).  Then I added a Geofield, and in the widget drop down I chose "Geocode from another field".  In the settings for the field I was able to choose the Address field I created earlier as the source.

Then in the "Manage Display" section of my xyz content type, for my geofield I chose "OpenLayers" from the Format drop down list.  And in the configuration of that field I chose the OpenLayers map type I had created earlier.

One thing I'm not crazy about is with the OpenLayers module; I can't seem to get the normal Google Maps pan and zoom controls and instead get some somewhat funky looking pan/zoom controls.

UPDATE

Apparently you can customize the pan and zoom controls using any images you like via css.  This blog post discusses it at the end: Take Control of Your Maps


Are changes to the user status stored somewhere? I've made a pretty serious error of judgement creating a view for a client that shows users created before a date AND still active. The error was adding a date filter.

This was meant to be used at the end of each month, and it was, with an email of users sent to the client. Now, after many users have been blocked, they're showing back on the view I created.

With quarterly billing, this is an issue as new users get counted fine, but any old users who have been blocked since don't show. A year from now, this period could actually show zero users.

The accounts were blocked using the editable_fields module.

Core doesn't store revisions/changes for the User entity type (the functionality simply isn't available out of the box).

So unless you have something like the User Revision module installed, or some custom functionality storing that data, you're unfortunately out of luck.

If you take regular backups, you might be able to fudge something together using those, but it would be a very manual process.


Have the server interpret www.example.com/directory as a directory rather than a Drupal path I've got a Drupal 6 site running at webroot, and a MediaWiki wiki running at webroot/wiki. I can access the wiki fine by going to wiki.webroot, but when I try to access it using the path webroot/wiki the server interprets this as a Drupal 6 path: how do I get the server to interpret this as a directory? I'm guessing this is something to do with htaccess?

So, your drupal site lives at webroot, and your wiki lives at webroot/wiki? First thing i would suggest is to put your wiki outside your drupal root and creating a separate virtual host. You're asking for trouble with your current setup.

The .htaccess file that ships with Drupal should properly be treating webroot/wiki as a directory, if it exists. See https://stackoverflow.com/questions/15879029/dont-understand-rewritecond-request-filename-f-and-d

If it just won't work for you, update Drupal's .htaccess to explicitly add your wiki path:

RewriteCond %{REQUEST_URI} ^/wiki

Put this right before:

RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

Your rewrite section will look like this (comments elided):

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteCond %{REQUEST_URI} ^/wiki
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]


Contextual Filter Path Alias I searched for this for some time now but couldnt find an anwser. I am using drupal 9.1.5 and pathauto. I have content types department and depratment news. The news are linked to the department. So whenever you create a department news you link it to a department. Now I want to display all depratment news linked to the department when i am on the department page (all children) and when I am on a page of a children (department news) I want to display all siblings, i.e. all departments news linked with the same department.
My url for departments is
[node:title]
and for department news is
[node:field_department:entity]/[node:title]
I thought that using a contextual filter in my view using the raw value from the url would work. So I used path component 1 and checked to use path alias. However this does not display anything.

When using path component 2 and disable to use path alias it works for the department news, which makes sence as I am internally on page node/xxx. I was so frustrated that I tried every other combination of path component and use path alias but nothing works. When using a fixed value for a department everything works as expected for that specific department

You can search for examples for each of your questions with "backwards views" and "sibling views". In short:
Show children on parent page
Create a Views that lists Children, then add the Entity reference field as the Contextual filter (not Content ID). Configure it to Provide default value Content ID from URL.
No Relationships needed in this solution. Place the Block on Parent pages and don't forget to configure the Block contextual option, it won't work without it.
Show siblings on child page
Create a Views that lists Children. This time you'll need 2 Relationships and 1 Contextual filter, all sequentially linked.
The first Relationship is for your ER field (the Field on Child that references a Parent), this one introduces the Parent info.
The second Relationship is the "backwards" Relationship for the same field, it is named a bit differently that the "forwards" one. Make the second Relationship use the first Relationship. This will trace path "backwards" from Parent to all their Children.
Add the Content ID Contextual filter and make it use the second Relationship. Configure it to Provide default value Content ID from URL. This will tell Views which Child's page you're currently viewing and will match to the Parent and then Parent's children.
Exclude current Child from Views
Your current Child will also be listed in Views because it satisfies the same condition! (It's also Parent's Child, just like other Siblings.)
You can exclude it by adding the second Contextual Content ID Filter that doesn't use any Relationships, Provides default value Content ID from URL, but under the last section More also check Exclude.


Database updates Out of date I downloaded a couple of module updates. Before I did so, I didn't disable the modules. Is this ok? I am now seeing the following in my Status Report:

Database updates    Out of date
Some modules have database schema updates to install. You should run the database update script immediately.

Is it safe for me to run the database update script now? Or should I first do a core update (am currently running 7.18 and would be upgrading to 7.19)?

Yes.  Go ahead and run update.php.  It will run the updates (which are usually but not necessarily schema updates) for the new modules.

There is no need to disable modules before updating them.  There is no need to update Core first.  You should, however, put the site into maintenance mode before updating the modules until after you run update.php.

You should run update.php every single time you update a module or the Core.


How to check if library is present in vendor folder? I have a form in which I am providing some options to users. But I want the options to appear in the form on the basis of presence of 3rd party libraries in vendor directory. I want something like this:

public function buildForm(array $form, FormStateInterface $form_state) {
    $form['settings']['tools'] = array(
      '#type' => 'radios',
      '#title' => $this->t('tools'),
      '#options' => array(),
      '#default_value' => $this->config('module.settings')->get('tools'),
    );
if(check_whether_xyz_library_is present_in_vendor_folder) {
  $form['settings']['tools']['#options'] = array('xyz' => 'xyz');
}

The vendor folder is present in the module directory itself and I am using composer to download third party dependencies. Since I do not want to check this  during installation of module but during form rendering then I suppose hook_requirements is not option. Any ideas on how to do so?

If you are talking about libraries, which are defined in files like *.libraries.yml, then you can use this:

\Drupal::service('library.discovery')->getLibraryByName('MODULE_NAME', 'LIBRARY_NAME')

You'll receive an array with all data including paths to check that files are exist.


User or Content Type for employee directory I am trying to create an employee directory using drupal 7. I have the following fields for each employee profile:

• Name
• Department
• Job Title
• Phone
• Email
• Optional photo
• A narrative-paragraph
• Note

Here is my requirement:

• Data (including photo) can be entered/updated by each employee using their login/password.
• Data can also be entered by the administrator
• Employees cannot remove their name.
• Admins can see when information was updated.
• Listing that is searchable by name and department

I could not decide which is the best way - content type 'employee' or user role 'employee' with profile fields.
If I create user as employee, how can I have the feature of the red information "updated" which we have in the content list (admin/content) when each content was updated?

I think you would be dealing with 'users' so using profile fields on user profiles would be your best shot.  As a bonus, Drupal is well thought out and flexible enough to handle whatever kind of userbase you throw at it.  Unless you want to re-invent the wheel in node hooks, I would shoot for profile fields and if you need to code up a custom module (or two), I can highly recommend entity api module to help you deal with profile field data.

The 'red' information you want (I assume) added to new content for example, (or any other possible variable) is easily done in templates. Usually based on conditionals and often (but not always) based on a bool variable of some kind.

For example, consider a 'flag' variable called $is_new. If $is_new isset (or !empty),  either you send a conditional stylesheet, or set up a template to show that background in red text in black. As simple example here is a repost of recommended way to use if's in a template:

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

<?php print $is_new ; ?>

<?php endif; ?>
 // You can use foreach statements for arrays you want to render
<?php foreach ($new_items as $item): ?>

<?php print $item; ?>

<?php endforeach; ?>

As for the different views for different is totally a different matter, but happily is also built in natively via roles, permissions and content-access system.

Good-luck!


How to create a $navigation main menu with target="_blank" on specific page.tpl.php pages I have a Drupal 7 site using the main menu for all pages. However, I've just added some unique landing pages for some advertising campaigns which all come from 'page--landing.tpl.php'

Oddly, my client wants just the 'page--landing.tpl.php' pages to have the main menu for these pages only work in such a way that the links all open in new windows (like target="_blank").

Does anyone know how to achieve this?

In the 'page--landing.tpl.php' file, the menu is created with:

<div id="menu">
<?php print $navigation; ?>
</div>

Thanks for any and all help given.

There are many ways to do this

A quick way would be to use jQuery to rewrite the anchor tags in the menu with the target attribute

$( '.page--landing [menu link selector] ).attr( 'target','_blank' );

Using the Drupal API

function MODULE/THEMENAME_menu_link_alter(&$item)
{
   if (some logic that sets it only for the desired paths/context)
   {
     $item['options']['attributes']['target'] = '_blank';
   }
}

an example from the documentation for function hook_menu_link_alter

function MODULE/THEMENAME_menu_link_alter(&$item)
{
  if($item['link_path']=="admin/tutorial14333")
  {
  $item['options']['attributes']['target'] = '_blank';
  }
}


how to calculate a value by rules I have three fields in a content type and want to calulate sum of them in another field.
First, I use Computed Field but it does not work at all.
Then I tried to use conditional field but it is not made for this purpose at all.
So I am trying rules module and make an event: After saving new content(or before) - The condition is: Content is of type [something] - The action: Execute custom PHP code.

And the code is:

$field_a = field_get_items($entity_type, $entity, 'field_absence');
$field_b = field_get_items($entity_type, $entity, 'field_delay');
$field_c = field_get_items($entity_type, $entity, 'field_vacation');
[node:field-sum] = $field_a[0]['value']+$field_b[0]['value']+$field_c[0]['value'];

But it does not do anything at all. I used the same code in computed field but it has no result. I'm not an expert Drupal programmer. So I need your helps in it. Thanks in advance.

The Math Field module defines a new field type to dynamically calculate values on entity forms. This is an alternative to Computed Field
that does not require the use of PHP Filter.

Note: the above info is an excerpt from its project page.


Implementing an age check using InboundPathProcessorInterface I'm trying to create an age checker for a Drupal 8 site.

I've created a custom module which has a form where the user enters their DOB and my form submit saves a cookie so I know they have passed the age check. Code is as follows:

public function submitForm(array &$form, FormStateInterface $form_state) {
  $day = $form_state->getValue('day');
  $month = $form_state->getValue('month');
  $year = $form_state->getValue('year');

  $timezone = new \DateTimeZone('Africa/Johannesburg');
  $age =
    \DateTime::createFromFormat('d/m/Y', $day . '/' . $month . '/' . $year,
      $timezone)->diff(new \DateTime('now', $timezone))->y;

  if ($age < '18') {
    // if less than 18 display the age_check.fail route
    $url = Url::fromRoute('age_check.fail');
    $form_state->setRedirectUrl($url);
  } else {
    // set cookie so we know this user has passed the age check
    setcookie('age_checked', 1, time()+3600, '/');

    $original_path = $_COOKIE['age_checked_prev_path'];

    if (!empty($original_path) && $original_path != '/') {
      $redirect_url = Url::fromUserInput($original_path);
      // Add a redirect to requested page. Using $form_state built in redirects.
      $form_state->setRedirectUrl($redirect_url);
    } else {
      // For everything else, redirect to homepage.
      $form_state->setRedirect('<front>');
    }
  }

}

Cool that is working fine i get redirected to a age-check-fail page if under 18. If over 18 I should be redirected back to the page I originally wanted to go to. Now I've tried to implement this using a Path Processor.

   /**
   * Path processor for age_check.
   */
class AgeCheckPathProcessor implements InboundPathProcessorInterface {

/**
 * {@inheritdoc}
 *
 */
public function processInbound($path, Request $request) {
  $alias_manager = \Drupal::service('path.alias_manager');
  $request_alias = $alias_manager->getAliasByPath($request->getRequestUri());
  // set cookie with original request path
  setcookie('age_checked_prev_path',$request_alias, time()+3600, '/');

  //get all cookies
  $cookies = $request->cookies->all();

  if(!array_key_exists('age_checked', $cookies) && empty($cookies['age_checked'])){

      // paths to skip age check
      $skip_path = [
        0 => '/admin',
        1 => '/user',
        2 => '/user/login',
        3 => '/age-check',
        4 => '/age-check/fail'
      ];

      // loop through each skip path and if match to current request return it
      foreach ($skip_path as $key => $path) {
        $url = trim($path);
        $url_alias = $alias_manager->getAliasByPath($url);

        if ($url == $request_alias || $url_alias == $request_alias) {
          // Leave $path intact.
          return $request_alias;
        }
      }

    // show the age check page.
    return '/age-check';
  }
  return $request_alias;
}

This isn't working as intended. One main problem is that coming from the home page, submitting the age check form correctly it still redirects me back to the age check form, if i then enter the url to an article I am allowed access to the site as intended, but trying to go back to the home page still shows the age checker form.

Am I using the Inbound Path Processor class correctly?

service:

  blah.preserved_system_paths_redirect:
    class: Drupal\blah\Redirect\PreservedSystemPathsRedirect
    tags:
      - { name: event_subscriber }

--

<?php

/**
 * @file
 * Contains \Drupal\blah\Redirect\PreservedSystemPathsRedirect.
 */

namespace Drupal\blah\Redirect;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Routing\RouteMatch;

/**
 * Class PreservedSystemPathsRedirect.
 */
class PreservedSystemPathsRedirect implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST] = 'checkSystemPaths';
    return $events;
  }

  /**
   * Redirect from original system paths to their new locations.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $response
   *   The created response object that will be returned.
   * @param string $event
   *   The string representation of the event.
   * @param \Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher $event_dispatcher
   *   Event dispatcher that lazily loads listeners and subscribers from the dependency injection
   *   container.
   */
  public function checkSystemPaths(GetResponseEvent $response, $event, ContainerAwareEventDispatcher $event_dispatcher) {
    $routeMatch = RouteMatch::createFromRequest($response->getRequest());
    $route_name = $routeMatch->getRouteName();

    switch ($route_name) {
      // Regional settings are now available in the blah/site settings form.
      case 'system.regional_settings':
      // Maintenance mode is now available in the blah/site setting form.
      case 'system.site_maintenance_mode':
        $url = \Drupal::url('blah.settings');
        break;
    }

    if (isset($url)) {
      $returnResponse = new RedirectResponse($url, Response::HTTP_MOVED_PERMANENTLY);
      $response->setResponse($returnResponse);
    }
  }

}


How do I redirect users from the registration page to Paypal? Only users with a "Sign Up Code" are allowed to sign up to the website. If they provide a valid signup code, they will be directed to a sign up page where they can provide user information, and PayPal processing is used to process the fee. On completion of payment an account is created.

How can I redirect user to Paypal?
How can I check the payment is paid by user?
How can I create the account if the user paid?

Use the Drupal Commerce module.

Add the Paypal payment method module; hook the login/register form to provide a different redirect page, or use the Rules module.
You can look at the generated transaction.
I would create the account anyway; set a flag, or something, for payed accounts.


Access Denied For Views We have a View showing all nodes of type 'member'. We have set permissions to view this node only for authenticated users. If anonymous user tries to access this view then it displays blank page. We expected that it will be redirecting to the page set under 'admin/config/system/site-information' for the 403 page(Access denied), but it is not. It is redirecting if anonymous user tries to access any node instance of 'member' itself but not if the view. How to configure 'Access denied' page for a view? Thank You

Drupal 7.23

Thank You

I think in this case you should set access to the view directly under page access in the view itself (assuming this is a page view). You would select Access > Role > "member" (and any other role that needs access).

Then users who do not have the role "member" should get a 403, and your custom redirect should work.


Field collection item code not working Hi Every one I am trying to create new field collection item programmatically but code is not working. I want to create a number of field collection items but no Luck. My code is following.

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\field_collection\Entity\FieldCollectionItem;

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if($form_id == 'my_form'){

for($i = 0; $i < 2; $i++) {

$new_experience_item = FieldCollectionItem::create(['field_name' => 'field_collection_name']);

      }

    }

}

My first Question-> Can we run this code in the hook_form_alter?  If yes, Then why my code is not working perfectly?

Paragraphs or Field Collection doesn't matter for your code. You need to add the newly created items to a field.

For example if the field collection field is in a node:

$node->field_collection_name[] = $new_item;

Not in a form alter hook, but in an entity create hook. See the linked question.


Each node has a score (percentage) which is updated weekly & want to show latest and the past scores in below/in a chart The site is keeping scores (by percentage) of how well it does in a certain area. So each node is a different area and that node will have a score of 7% in week 1. An example: Liverpool's score is 11.23% for week 1 of 2018, week 2 that node (Liverpool) is updated and it gets a score of 12.01%, etc, etc.

In week 2, we update that nodes score to 9.5%, I want to show this prominently at the top of the page as the current score. Then underneath, show a chart of the previous scores or at least at the very minimum show all the scores in a neat line, going back/down in order of date.

I then also want to show all of these nodes (areas) in one view, showing in a ranking list, this would just be a view?

Is this the right way to go about it, with nodes that are updated/revisions? Or am I thinking about this all wrong?

What about using table field for the past scores and just having the current score as it's own field shown at the top?

You could implement them with a field_collection (currently not stable for either D7 or D8) or with the paragraphs module (currently stable for D8 only) if you need to keep track of old scores of each node and when they've been set.

I've also implemented similar things (paired values) by simply having two multivalue fields, one after the other, and letting editors keep them in sync manually, then rendering them together in a table or the alike with a custom template.

Using two simple multivalue fields (and they could be both numeric fields, if the time is something simple as the number of the week) may eventually simplify accessing such data in a view.


Can I programmatically create a new node revision, without the new revision becoming the "current" one? Whenever my feeds import finds a new version of an existing piece of content, it creates a new revision of this node instead of overwriting data.

Normally the new revision becomes the "current" one right away. I would like the currently displayed revision however to remain the same, and let a moderator decide later if the new one should be published.

A standard Drupal install does not allow you to create a "Pending" revision.  You have two options:

Programatically create a new revision but programatically revert back to the original revision (which creates an even newer revision, but it has the original content)
(Recommended) Use Workbench Moderation, Revisioning or Workflow which are well thought-out solutions for version control and/or access control.

For option 1:
You can add this code as a new Rule or use it in a new module

<?php
  // Programatically load the existing revision and save it
  // Taken from http://api.drupal.org/api/drupal/modules!node!node.module/function/node_save/7
  // Load the revision
  $original_revision = node_load($nid);
  $original_revision->revision = 1;
  $original_revision->log = t('Copy of the revision from %date.', array('%date' => format_date($original_revision->revision_timestamp)));

  $new_revision = node_load($nid);
  // Make any changes to the new revision here...
  $new_revision->revision = 1;
  $new_revision->log = t('Summarize your changes here');

  // Save the new revision first
  node_save($new_revision);

  // Save the original one again so that it is still the current revision
  node_save($original_revision);

  watchdog('content', '@type: reverted %title revision %revision.', array('@type' => $node_revision->type, '%title' => $node_revision->title, '%revision' => $node_revision->vid));
  drupal_set_message(t('@type %title was saved with a new revision, but reverting to original revision from %revision-date.', array('@type' => node_type_get_name($node_revision), '%title' => $node_revision->title, '%revision-date' => format_date($node_revision->revision_timestamp))));
  drupal_goto('node/' . $node_revision->nid . '/revisions');
?>

For option 2:
I would recommend Workbench over Revisioning or Workflow, but each is different depending on your needs.  Workbench is kind of the successor to Revisioning, and Workflow is a lot more than just version control, so it may or may not be a good fit for your needs.

Here's a quick breakdown on the differences between Workbench and Workflow.


Using twig extensions in Drupal 7 I would like to be able to use some custom PHP code that generates an SVG image in my .tpl.twig file. Since I can't write PHP in a twig template I figured I should try and make a twig extension (http://symfony.com/doc/current/cookbook/templating/twig_extension.html)

How could this be done in Drupal? Or is there another way?

When you are using tfd7 you can use extensions, functions, etc. The easiest way to go is to create an own module for handling all the php-functions.

In your OWN_MODULE.module:

function OWN_MODULE_twig_function() {
  $functions = [];
  $functions['XYZ_unset_key'] = new TwigSimpleFunction('XYZ_unset_key', 'XYZ_unset_key_callable');

  ...

  return $functions;
}

function XYZ_unset_key_callable($key, $array) {
  unset($array[$key];
  return $array;
}

After that you can use the function XYZ_unset_key in your twig-files:

<div>
  {{ XYZ_unset_key('field_xyz', 'content') }}
</div>


Is there any way to use views contextual filters in block configuration? For my situation, i need to create views for taxonomy terms content listing, I have created that with blocks. I am using contextual filter in that views to filter the content with taxonomy terms dynamically.

Is there any way to give value for contextual filter from block configuration page ?

If we have that options, then it would save me from creating separate blocks for each terms.

Contextual filter configuration :

My question is can i give value for the contextual filter from the block configuration page ?

The contextual filter is not possible to be exposed on a block. It is only possible with filter criteria.

The other posibility is use a taxonomy term view and use the module Taxonomy menu or Taxonomy menu block to show a list of taxonomy terms on a block.


How to theme the $content variable's contents? I am trying to theme the teasers of a particular content type.

I have gotten to the point where I created a file of name node-content_type-teaser.php, where content_type is the relevant name.

The trouble is, I am unable to style the actual $content. It outputs the teaser of the text in a <p> tag, and an image thumbnail (I get it from a CCK field). I just need to change the order, and output the image first, so I can float it.

To summarize, how do I control the order in which $content is output?

If all you want to do is change the order, you do that in the edit content/manage fields form where you can drag and drop the fields in whatever order you want them to be output.

If that's not exactly what you want, you can also change how they are displayed in the "display fields" form.

If all of the above doesn't do exactly what you want, you can print out each field however you want inside the template itself, eg, instead of printing $output, you can print out each field you want when and how.

So, if for example, you have a text field called field_description, you can output it by putting a  print $node->field_description[0]['safe']; in there since the entire $node is available inside the template to play with.

To see all there is to work with in your specific case, a quick drupal_set_message('<pre> . print_r($node,true) . '</pre>'); in your template will show you lots of information.


You must include at least one positive keyword with 3 characters or more Drupal 6.20 according to the changelog file.

We took over a site from another company who built the site in Drupal, and we'll be converting it over to Wordpress eventually but we need to resolve the search issue first.

I get the "You must include at least one positive keyword with 3 characters or more." error message whether I use the search bar (search module) which leads you to "search/node/KEYWORD" with KEYWORD being your search parameter or if I just go to /search after the URL.

I've read about this and have tried all the suggestions that I saw and none have resolved the issue. I re-indexed the site, and ran cron.php. After I ran cron.php I looked at the settings again and it shows that 100% of the site has been indexed.

I also manually changed the search module status in the database, but it only made the search bar disappear and after I changed the status back to active I got the same result. I tried that because it worked for another module that wasn't working on startup.

The entire site and DB was copied over, and the site that is on the other company server the search functions properly. I don't think it's php version related because I ran a script to revert back to PHP 5.3. Does anyone have any suggestions on what else I might try to possibly get the search working?

The search module is a little weird in Drupal, and can take some time to wrap your brain around.  If you start reading from node_search(), you will see a call to do_search() which is the function that links the search indexes to the things you are searching over.

If you read that function, you will see that there is a variable minimum_word_size, that defaults to 3.  If you need to be able to search on smaller words, you need to set this smaller.  I believe you can set this on 'admin/settings/search', but I don't have any Drupal 6 sites to check against.

Change this value, then wipe the search index and rebuild it.  These last two steps are most easily accomplished with Drush.


form_alter to change value of default in dropdown list I need to change the first value (the default one) in one of my taxonomy based dropdown menus. It is currently set to '- CHose a value -', and I need it to be changed to: '- Chose city -'.

I thought I might use form_alter for this, But I cant get further then to the correct form_id.

What to I do next?

First you need to find out where the element that you're trying to manipulate is within the form array. The best way to do that is to install the Devel module and use the dpm() function to inspect the $form variable:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form') {
    dpm($form);
  }
}

When you see the variable outputted to the message you can drill down until you find the particular element. Note the keys of the element's parents in the array as you'll need them too.

If this is a node form and the taxonomy list is provided by a term reference field the actual form element will be found somewhere like this:

$form['field_field_name']['und'][0]['tid']

Using that example your form alter would look like this:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form') {
    $form['field_field_name']['und'][0]['tid']['#options'][0] = '- Choose City -';
  }
}

Again you'll have to confirm using dpm() whether 0 is the right array key for the default select option that you're changing.


How to call a function when a node is being viewed? Whenever I view a node page, I want to call a function but I'm not sure how to do that.

I was thinking I should use hook_menu() and declare the path as node/%, and attach a callback function to that path. Is that the right way, or is there a correct/better way?

You can implement hook_node_view()

  Act on a node that is being assembled before rendering.

e.g.

function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'the_type' && $view_mode == 'full') {
    // Call your function here.
    my_function($node);
  }
}


How do I debug a the output errors on SimpleTest when I'm not sure where in the script the error occurred? I'm trying to build a simple test. I'm having trouble submitting webforms. With help form a previous question I've cobbled together these functions within the larger class.

They completely work in the following test.php script run on the command line via drush scr test.php

$data = array(
  1 => array('1'),
  2 => array('2'),
  3 => array('3')
);

$T = new MyTest();
$T->insertMockData($data);

However, when I try to run as `drush test-run MyTest things fail completely.

Source snippet:

  function setUp($modules = array()) {
        $modules[] = 'webform';
        parent::setUp($modules);

        $this->insertMockData($this->randomData());
    }
function insertMockData($data = array(), $submitted_datetime = REQUEST_TIME) {

        $node_web = node_load(1);
        $submission = (object) array(
        'nid' => $node_web->nid,
        //'uid' => $user->uid,
        'submitted' => $submitted_datetime,
        'remote_addr' => ip_address(),
        'is_draft' => FALSE,
        'data' => $data,
            'serial' => $this->serial_value++,
        );
        module_load_include('inc', 'webform', 'includes/webform.submissions');
        webform_submission_insert($node_web, $submission);
            //webform_submission_send_mail($node_web, $submission);
          }

    function randomData() {
    $random_line_of_text  = array(
      "Mary had a little lamb",
      "a little lamb",
      "With fleece as white as snow",
      "And everywhere that Mary went",
      "That lamb was sure to go");

    return array(
      1 => array($random_line_of_text[array_rand($random_line_of_text)]),
      2 => array($random_line_of_text[array_rand($random_line_of_text)]),
      3 => array($random_line_of_text[array_rand($random_line_of_text)]),
    );
}

Errors on console

Test MyTest->insertMockData() failed: Trying to get property of non-object                       [error] Test webform_webform_submission_presave() failed: Trying to get property of non-object             [error]
Test webform_webform_submission_presave() failed: Invalid argument supplied for foreach()          [error] Test webform_submission_insert() failed: Trying to get property of non-object                      [error]
Test webform_submission_insert() failed: Trying to get property of non-object                      [error] Test webform_submission_insert() failed: Trying to get property of non-object                      [error]
Test webform_submission_insert() failed: Trying to get property of non-object                      [error] Test webform_submission_send_mail() failed: Trying to get property of non-object                   [error]
Test webform_submission_send_mail() failed: Invalid argument supplied for foreach()                [error] Test MyTest->insertMockData() failed: Trying to get property of non-object                       [error]

Question: How do I debug a the output of SimpleTest when I'm not sure where in the script the error occurred?

Part of why your test is failing is pretty easy to see.  Your code is relying on node 1 existing:

function insertMockData($data = array(), $submitted_datetime = REQUEST_TIME) {

        $node_web = node_load(1);
        $submission = (object) array(
        'nid' => $node_web->nid,
        //'uid' => $user->uid,
        'submitted' => $submitted_datetime,
        'remote_addr' => ip_address(),
        'is_draft' => FALSE,
        'data' => $data,
            'serial' => $this->serial_value++,
        );
  //lots of stuff omitted here...
}

The code assumes that there's a node in your DB for you to load.  Sadly, no :-)

When SimpleTest runs, it creates a whole empty DB that's just installed.  If you need a node, you have to create one, like this:

$settings = [
  'title' => 'My Test Content',
  'body'  => 'and what a body it is',
  'status' => 1,
  'type' => 'article',
];

$test_node = $this->drupalCreateNode($settings);
$this->assertNotNull($test_node, "Make sure our settings work");

See core/modules/simpletest/src/WebTestBase.php for some of the methods you can use to create nodes and users and other useful test data.  But in general: your test or the test's superclasses need to create everything you need either in setUp() or in your test itself.


Why does "Cancel People Account" not work? I have Drupal 7 with Devel installed running over PHP internal server and MySQL.
All user operations work correctly except Admin>People>Cancel Account operation.

This leads to the overlay Add User and a Cancel Accounts button.
If I select the option: Delete the account and its content and press Cancel Accounts.

This leaves the overlay(displays the home page of the user)

All I want at this point is to be in the backend Overlay and show the message Changes saved or something similar.
When I return to Admin People overlay, the user is still there.

Has anyone experienced a similar problem - and do you have a solution?

Thank You.
-Robert.

I can confirm your suggestion what it actually should be like and that actually exactly that should happen what you expect. After canceling an account you will be provided with further steps about the users written content etc. and finally you will become a progress bar showing the deletion or re-assigning of the written content of this user and the final confirmation about the success of it all.

The misbehaviour what you describe can be caused by several issues I only can list here for your research:

there is a mod_rewrite issue sometimes if the server is not set up correctly but this would actually also come up by many other tasks
is your admin account clean and has never been modified? The user 0 is something special in Drupal world and can sometimes be corrupted by some changes on it
you mentioned a local installation. Does has your DB user which is connected to the DB management of your Drupal installation, the right to DELETE in the mysql database?
and as mentioned by Molot also the redirecting via overlay or any other modal frameworks and jquery can be the issue, often fixed by using jquery_update module and playing around with jquery versions in the settings of the module.
Also, any PHP cache or similar can cause freezing batch processes or overwrite the use of pecl progressbar (default in Drupal)
Did you tried different users or only one? Or is this user you try to delete a spam account? They also can cause issues since they are not really registered but somehow signed up. This would be another story ...

Sorry, just some ideas...


Language-dependent logo How can I use a custom logo image in Drupal 8 that is language dependent? There does not seem to be an appropriate setting in the Content and Language Translation configuration page.

Langauge is a visibility condition for blocks, so you could use multiple branding blocks and hard code the paths.

Setting it automatically is a little harder, language is not available in $variables in preprocess so you'd need to add it - you could add these to all preprocess functions and templates:

/**
 * Preprocess variables for all templates.
 * @param $variables
 */
function HOOK_preprocess(&$variables) {
  // Inject the current language into every template to ease theme development.
  $variables['current_language'] = \Drupal::languageManager()->getCurrentLanguage();

  // Inject a usable directory path.
  $variables['theme_path'] = base_path() . $variables['directory'];
}

You can use these in the branding block or page template to set a path to a language specific logo, e.g.:

<img src="{{ theme_path ~ '/logo-' ~ current_language.getID() ~ '.svg' }}" alt="{{ 'Home'|t }}" />

So you'd have logo-en.svg for english, logo-sv.svg for Swedish etc in your theme root, getID() just returns the two character language code.

You could go further and just build the whole thing in preprocess, just for the template you are using (either page or the branding block).


Programmatically load the page variant being used on path or node object I'm attempting to be able to load a page variant given a specific path. My ultimate goal is to loop through all the links in a menu, find out what page_manager variant is being used and load the context data from that variant. I'm able to grab the data just fine if I manually supply a page id. Below is me obtaining the data from the about page I've created in page manager.

$page_storage = \Drupal::entityTypeManager()->getStorage('page');
$variant_storage = \Drupal::entityTypeManager()->getStorage('page_variant');
$about = $page_storage->load('about');
$about_variant = $about->getVariants();
$about_variant = reset($about_variant);
foreach($about_variant->getContexts() as $context){
    $label = $context->getContextDefinition()->getLabel();
    if($label == 'Icon'){
        var_dump($context->getContextValue());
    }
}

This works just fine. But what if I want to load the context data of each link in a menu? These are links that I can't anticipate. Also some of these links will be regular pages and some will be actual nodes that also have their own variant.

I can load the nodes from the route like so

$params = \Drupal\Core\Url::fromUserInput($path)->getRouteParameters();
if (isset($params['node'])) {
    $node = \Drupal\node\Entity\Node::load($params['node']);
    //We have a node which I don't know how to get the variant of
} else {
    //We have a regular page that I don't know obtain the id of
}

But even though I have the node I have no idea of a way to interface with it in a way that allows me to obtain the page variant I'm using. If it's a regular page, then as long as I have the page id of it I can load the page variant like I have done before, but I don't know how to obtain that.

So ultimately I suppose I need to be able to programmatically obtain two things

How to obtain the page id from a page given its path
How to see the page variant being used on a node

UPDATE: I did manage to obtain the page with this line

$page = \Drupal::entityTypeManager()->getStorage('page')->loadByProperties(['path' => $link]);

Still not sure how to grab the variant the node is using yet though.

In order to get the variant being used by the node I was able to retrieve the info inside the array returned by

$node->panelizer->getValue()

And to get the page I used

$page = \Drupal::entityTypeManager()->getStorage('page')->loadByProperties(['path' => $link]);


Hook into other module's field formatter? Am currently trying to implement a node referenced image field on my Drupal 7 site that will change it's 'view mode' depending on programmatical logic just before render. The field is currently being rendered on a number of content types via their display mode settings, each of which are using the field formatter 'Rendered node'.

first attempt

My first idea was to implement the following, considering a hook is a hook is a hook:

function HOOK_field_formatter_view( $entity_type, $entity, $field ... ){
  switch ($display['type']) {
    case 'node_reference_node':
      /* Programatical logic here to modfy field render settings */
    break;
  }
}

Obviously exchanging HOOK for my module's name.

It didn't really matter if the above would fire before or after the original function node_reference_field_formatter_view in node_reference.module because I would either override it's output entirely or, hopefully, modify its values before rendering. The only problem is, the above hook seems to function only on a per module basis — i.e. it's not site-wide, so basically it doesn't fire for my module.

Now obviously I can write my own field formatter to output a rendered node. But it seems a bit of a waste considering there is already one that exists.

other approaches

My other approaches have been to HOOK_preprocess_node and HOOK_preprocess_field but the former doesn't contain any view_mode information, and the latter contains at least 5 different complicated structures that all have references to a view_mode property at different levels — and it feels rather hacky to have to modify each of their values. Even when I've changed certain view_mode properties the resulting image doesn't change.

question

Does anyone know of a clean way to step in before a field formatter renders (of a contrib module) and change it's settings on a per page request basis — i.e. by not having to change the actual content type's permanent view mode settings?

The question mentions that hook_field_formatter_view() is only called on the originating module, but you can take ownership of the field formatter via hook_field_formatter_info_alter().

You should be able to set the module key of the formatter to MYMODULE like:

function MYMODULE_field_formatter_info_alter(&$info) {
  $info['some_field_formatter']['module'] = 'MYMODULE';
}

Then you can implement MYMODULE_field_formatter_view(), optionally feeding through the existing module which handled it to get an element to alter.

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  // Your custom logic
  $element = OTHER_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display);
  // Any alterations
}


Why does deleting a translation on my custom entity delete the entire record? I have defined a custom content entity. (You may find the details below.) If I create an entry in the table and a translation for the entry and then delete the translation it removes the entire entry.

/**
 * @ContentEntityType(
 *   id = "my_custom_entity",
 *   label = @Translation("My Custom Entity"),
 *   handlers = {
 *     "storage" = "Drupal\Core\Entity\Sql\SqlContentEntityStorage",
 *     "access" = "Drupal\my_custom_entity\MyCustomEntityAccessControlHandler",
 *     "form" = {
 *       "default" = "Drupal\my_custom_entity\Form\MyCustomEntityForm",
 *       "delete" = "Drupal\my_custom_entity\Form\MyCustomEntityDeleteForm",
 *     },
 *     "list_builder" = "Drupal\my_custom_entity\Entity\Controller\MyCustomEntityListBuilder",
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "views_data" = "Drupal\my_custom_entity\MyCustomEntityViewsData",
 *     "translation" = "Drupal\content_translation\ContentTranslationHandler"
 *   },
 *   translatable = TRUE,
 *   base_table = "my_custom_entity",
 *   data_table = "my_custom_entity_field_data",
 *   fieldable = FALSE,
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label",
 *     "langcode" = "langcode"
 *   },
 *   links = {
 *     "canonical" = "/my_custom_entity/{my_custom_entity}",
 *     "edit-form" = "/my_custom_entity/{my_custom_entity}/edit",
 *     "delete-form" = "/my_custom_entity/{my_custom_entity}/delete",
 *     "collection" = "/my_custom_entity/list"
 *   },
 *   list_cache_contexts = {"user"}
 * )
 */

Update: I've made a bit of progress on this. The issue seems to be that the entity provides a delete-form. On account of this core/modules/content_translation/src/Access/ContentTranslationManageAccessCheck::access ends up returning AccessResult::forbidden() on line 85 (Drupal 8.3.7) when looking at the path /my_custom_entity/{my_custom_entity}/translations/delete/{language}. Instead it uses /my_custom_entity/{my_custom_entity}/delete. Now I've got to figure out what I'm supposed to do instead. The User entity does not declare a delete-form, but the Node entity does. My initial attempt at removing the delete-form key on my entity resulted in Uncaught PHP Exception Symfony\\Component\\Routing\\Exception\\RouteNotFoundException: "Route "entity.my_custom_entity.delete_form" does not exist." at /var/www/html/drupal8/core/lib/Drupal/Core/Routing/RouteProvider.php line 190. However, I didn't actually uninstall and reinstall the module. I just visited the Extend page and cleared cache.

TL;DR: Extend ContentEntityDeleteForm instead of ContentEntityConfirmFormBase.

The solution was to pattern my approach after the way Node and Taxonomy Terms create their delete forms. I changed my delete form to extend ContentEntityDeleteForm instead of extending ContentEntityConfirmFormBase. Look at ContentEntityDeleteForm::submitForm

// Make sure that deleting a translation does not delete the whole entity.
if (!$entity->isDefaultTranslation()) {
  $untranslated_entity = $entity->getUntranslated();
  $untranslated_entity->removeTranslation($entity->language()->getId());
  $untranslated_entity->save();
  $form_state->setRedirectUrl($untranslated_entity->urlInfo('canonical'));
}
else {
  $entity->delete();
  $form_state->setRedirectUrl($this->getRedirectUrl());
}

It explicitly takes care not to delete the whole entity when you are deleting a translation.

ContentEntityConfirmFormBase inherits the ContentEntityForm::submitForm method, which in turn executes the EntityForm::submitForm method. The entity never gets deleted anywhere in that process. Thus, I needed to override the submitForm method in my class. I hadn't included the necessary logic to account for translations, though. Rather than reproducing the necessary logic in an overridden submitForm method, it made more sense to change the class that I was extending.


Manage Display page not displaying anymore I set (or at least tried to) my user display page (admin/config/people/accounts/display) to use DS 1col on friday and part way through the request my computer crashed out (the server is running on the local machine too) and now I can't seem to access that page if I let it run forever I get:

  Fatal error: Maximum execution time of 120 seconds exceeded in /Applications/MAMP/htdocs/modules/field_ui/field_ui.admin.inc on line 145

I've tried to:

Clear caches
Run cron
Disable and re-enable DS

Although I'm continuing to play with DS, I'm assuming whatever got corrupted is related to the field_ui module because of the error and it only seems to be affecting the manage display for the user account page; no other user account pages or manage display pages are affected.

Does anyone know if there is a simple way to reset that page to the default?

after playing around in the database for awhile and trying things (I backed it up first) I found the problem in the field_group table by deleting all the default user groups I can now see and edit the manage display page for the account


How to use EntityFieldQuery::fieldCondition for entity reference field? Suppose, we have an entity "song", that has an entity reference field, called "authors":

I added a filter for this field as a group of checkboxes:

After the user submits the form with checkboxes group, it must be used inside WHERE condition for the list of songs. So, I added the following code:

//query to get the list of entities
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'song');

if(!is_null($form_state['input']['field_authors'][LANGUAGE_NONE]))
{
    $query->fieldCondition('field_authors', /* what to put here? */,
            $form_state['input']['field_authors'][LANGUAGE_NONE], 'in');
}

I don't understand, what value to put into column parameter. I tried target_id, but it doesn't work. Here is the description of field_data_field_authors table:

DESCRIBE field_data_field_authors;
+-------------------------+------------------+------+-----+---------+-------+
| Field                   | Type             | Null | Key | Default | Extra |
+-------------------------+------------------+------+-----+---------+-------+
| entity_type             | varchar(128)     | NO   | PRI |         |       |
| bundle                  | varchar(128)     | NO   | MUL |         |       |
| deleted                 | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id               | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id             | int(10) unsigned | YES  | MUL | NULL    |       |
| language                | varchar(32)      | NO   | PRI |         |       |
| delta                   | int(10) unsigned | NO   | PRI | NULL    |       |
| field_authors_target_id | int(10) unsigned | NO   | MUL | NULL    |       |
+-------------------------+------------------+------+-----+---------+-------+

You need to use 'target_id'

Your code should by this:

//query to get the list of entities
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'song');

if(!is_null($form_state['input']['field_authors'][LANGUAGE_NONE]))
{
    $query->fieldCondition('field_authors', 'target_id',
            $form_state['input']['field_authors'][LANGUAGE_NONE], 'in');
}

You can found a good explanation here:

How to use EntityFieldQuery with a simple text field?


how to create view that display just 2 level of taxonomy vocabulary i have a vocabulary that contain plus of 5 level descendant, i need to create the view to display the first 2 levels and grouping by the first one, i do this:

FIELDS: (Parent) Taxonomy term: Name - Taxonomy term: Name
FILTER CRITERIA: Taxonomy vocabulary: Machine name (= All Type
Announce)
SORT CRITERIA: (Parent) Taxonomy term: Weight (asc)
RELATIONSHIPS: Taxonomy term: Parent term

and i get all list of taxonomy for this vocabulary grouping by parents, how to set only 2 levels?

It's simple. In fact, there is no need to add any relationship in the Views. Just create the taxonomy term view and add a filter criteria of Taxonomy term: Parent term. (see screenshot)
Then set the value to be equal to ''. This will fetch you all the parent terms as they don't have any parent! ('')


Does using MongoDB for field storage limit functionality? I am considering using MongoDB on a site for field storage, and not just moving cache, session, lots, etc., out of my SQL database.

The Field Storage API should make this seamless, assuming I am using the Drupal API for accessing data.  But, does this limit my site in any way.  In particular, I am wondering how Views will be affected.

its a cool question.

Im on my 5 week adventure of playing around with Drupal 7 and mongo,

However as Cahpabu stated and quoted.

  NO RELATIONSHIPS WHATSOEVER. EFQ Views do not support relationships
  because Mongo doesn’t support JOINs." - Under the Converting the Views
  section on this post. (Just to clarify, I'm not being argumentative,
  I'm genuinely curious) – Chapabu Sep 6 at 15:57

I think you can do a lot using mongo with Drupal, moving a lot of other stuff into mongo, like sessions, etc. simple "fields" however :

Since Views is extremly limited with Mongo db. I found out that its better(and much more timeconsuming) to rewrite some custom modules fitting into the schema of mongo.

So its for sure, a great adventure if your starting up a new project/site. But the adventure will be filled with great challenges down mystery lane.

Even the Whitehouse had to go back to Mysql from mongo.
here is a quote I found on it.

  "The current release depends on MongoDB. When we first created the
  application, we wanted to make sure we had a highly scalable
  application and database to meet our anticipated performance needs
  under high loads. We have been running MongoDB in production for over
  a year, but we have decided that the performance benefits it provides
  are outweighed by the complexity of trying to extend Drupal features
  backed by MongoDB."

However other people had great succes with mongodb and Drupal 8
Mongodb and Drupal 8

  As they state in their slide, To achieve full mongodb functionality is
  of course impossible.

But you will have to give up several modules using SQL, (which is a lot) For now, I still have the feeling that Drupal cant dance a full tango with Mongo. Even using the modules. its still a rough way.


How to completely wipe and rebuild drupal menus? A while ago I found a cool blog post that detailed how to empty the menu tables, and rebuild the menu system with a drush php call, a necessity since the site will be unusable after emptying those mysql tables. This way, you could reset your menus like it was a new Drupal site.

Can anyone detail this technique or do you have the link for that blog?

I have been looking a while for a solution to the problem to rebuild Drupal menus until I stumbled upon a Drupal issue that helped me. My solution (in a php script) is the following:

db_query("DELETE FROM {menu_links} WHERE module = 'system'");
db_query("DELETE FROM {menu_links} WHERE menu_name = 'management'");
menu_rebuild();

This could also be done by entering the queries through phpmyadmin or something alike:

DELETE FROM {menu_links} WHERE module = 'system'
DELETE FROM {menu_links} WHERE menu_name = 'management'

And then rebuilding the menu structure. If you use the devel module, you can achieve that by visiting the page /devel/menu/reset. I you don't have the devel module, I'm not sure how to rebuild the menu structure.

Don't forget to backup your database before you try this.


Creating multiple destinations from one source I'm writing a Drupal 8 migration from a non-Drupal site where I need to migrate news articles that have inline images in them, sometimes more than 10. I've figured I'll do this in two steps:

A migration for creating file entities for each image present in the source node body.
A migration that creates news article entities, and for each image encountered, look up the file entity that was created in the 1st migration and use the File Usage API to indicate the file is used in this node.

My problem is the first migration. The Migration API wants to map a single source to a single destination. I need to be able to map a single source to MULTIPLE destinations, since I will be creating as many as 10 file entities from this single source row.

Does anyone know if this is possible, and if so, are there any examples in core or contrib migrating like this?

If I can't find a way to do it this way, I'll instead just migrate everything in the same single migration, and create the file entities on the fly. I'll just have to write a custom rollback implementation to remove them as well.

I usually use D7 migrate. But from what i've read of D8 either of these approaches should work:

  My problem is the first migration. The Migration API wants to map a single source to a single destination.

Option 1

In migration 1 simply import any encountered file into drupal. Then record the file id to a custom table of columns legacy_url, old_source_id, drupal_file_id for example in the complete() method of the migration.

In your second migration pass an array of drupal_file_id to your Node's file field from a select drupal_file_id from mytable where old_source_id = $old_source_id. This will attach the legacy files into the new Node. You may need still need to adjust any inline usage of images, or just use a view_mode to show the file list in D8.

Option 2

Just import articles (don't use a 1st migration for just files) and use complete() method in a migration to scan the HTML using DomDocument or simple_html_dom to find file urls and use the drupal API to save the remote file to drupal and then update the DOM with the new url. Create a custom rollback function to remove these files if needed.

Edit

Some example Drupal 8 file migration logic and classes can be seen at the following link. This may not address your exact issue, but in my opinion is good reference.
http://www.jeffgeerling.com/blog/2016/migrating-20000-images-audio-clips-and-video-clips-drupal-8