How can I put form elements into a table and have a submit at the bottom? I'm working on this module and I want it displays a page as follows.

What I am doing to get that is just displaying a table through theme() and typing out the HTML for the upload. I want the whole page to be seen as a form; the only element that will need changing is the image that's uploaded. I want also a submit button on the bottom to save changes.

One way to solve this would be to put an edit button and have it go to a new page that is just a form and that would work, but I'd prefer to have it on one page.

What is the best way to do this? Every site I read on is just confusing me more because they are all doing it different; it's not the result I am looking for because not all that is displaying is going to be a form element.

You should use theme_table.
It will help you.
:)


Remove datatype attribute from meta about tag I'm trying to validate my Drupal 7 website on http://validator.w3.org but I can't keep getting the following error:

  Attribute datatype not allowed on element meta at this point.

This is because <meta about="/frontpage" property="sioc:num_replies" content="0" datatype="xsd:integer" /> automatically gets the 'datatype=xsd:integer' attribute. I want to remove the datatype attribute altogether.

Apparently the meta tag isn't the problem. The problem is the validation service and how you use it. After some digging I found this article. The author suggest using a different validation type namely: http://validator.w3.org/nu/ with the following preset set in the additional options: "HTML5 + SVG 1.1 + MathML 2.0 + RDFa 1.1 + Microdata". This will validate said meta tags without any errors.


Description field has no text format The Feed module successfully imports a RSS feed. However the Description field does not display.  I can only see it if I click on "Edit". The problem is that the feed-items do not have a text format.

How can I give the Description field a default text format?

Seems to work properly if I do not use the default feed importer. Instead I created my own feed importer, I think with the exact same settings, and now it imports full html!


Views - Combining Fields into a single link? I'm using the Views module to build some views for our company's locations and employees.  What I've got set up is:  when a user looks at a page for one of our locations, they get a list of employees there.  The 'Employee' content type is set up with separate fields such as "Last Name", "First Name", "Middle Init" and so forth.

What I want to do is to find a way to combine these fields in a single line that forms a link to the employee's profile when clicked.

I've found I can do this by changing the "Title" field to something like "Display Name" and adding that field to the view (as the title field gives you the option to link back to the original content), but I'd really rather do it the other way as the data for the content type is imported and I'd rather not sift through all that to add a "Display" field and everything that goes along with it.

Any ideas or am I out of luck?

You can add the 4 fields in this order:

nid
first name
middle name
last name

For the first 3 fields, check the "Exclude from display" checkbox.

For the 4th field, in the rewrite results section, check the "Rewrite the output of this field", then in the "Text" text area use the replacement patterns for the other fields to join them together.

It will be something like this:

[field_first_name] [field_middle_name] [field_last_name]

Then also check the "Output this field as a link" checkbox and for the "Link path" you can again use the replacement patterns (expand the fieldset to see the available replacement tokens).

It will be something like:

node/[nid]


Time shown in incorrect language I have a php_view field in a view, it basically pulls a date field on a specific node, and then use the php function setISODate to get the 'monday' date of the week.

The thing is, i'm on a french language site and the date that the function return is in english, not that I don't like english hehe but the month just doesn't fit very well in the display on that view

Here's the code.

// Retrieve the date field of that node.
$node = node_load($data->nid);
$date_field = $node->field_date;
$date = $date_field['und'][0]['value'];

// Put the year in $annee and the week number in $semaine.
$annee = date("Y", strtotime($date));
$semaine= date("W", strtotime($date));

// Get the monday date of that week
$lundi = new DateTime();
$lundi->setISODate($annee , $semaine);
print "Semaine du " . $lundi->format('j F Y');;

?>

I've tried to use the following code, but it doesn't do anything.

setlocale (LC_TIME, 'fr_FR.utf8','fra');
print (strftime("%j %F %Y", $lundi));

This is working :

setlocale(LC_TIME, 'French_France.utf-8', 'fr.UTF8', 'fr_FR.UTF-8', 'fr.UTF-8');
//setlocale(LC_ALL, '') ;// if you try on local windows server

$annee = date("Y", strtotime($date));
$semaine= date("W", strtotime($date));

// Get the monday date of that week
$lundi = new DateTime();
$lundi->setISODate($annee , $semaine);

print "Semaine du " . strftime("%A %d %B %Y",strtotime($lundi->format('j F Y')));


How to add links in the title for a profile text field so i have this as a check box for profiles and it is being shown on the registration page as well "I accept the Terms & Conditions and Privacy Policy." and i need to make Terms & Conditions and Privacy Policy links that point to their respective pages. also i'm using Drupal 6

It sounds like you should be looking at the Terms of Use module, which will place the check box on the user registration page. It provides a link to a node, which you create, outlining the terms the user must agree to to register on the site.

On the project page they also mention the Legal module, which provides similar, but more extensive options.

Check both, and see which best satisfies your needs.


Keep line breaks when printing custom plain text textarea field I'm using Drupal 7. I'm printing out a custom plain text textarea field in the node template using the following code:

print ($taxonomy_term->field_address['und'][0]['value']);

However, when I print it out I lose all the line breaks.  Is there a way I can keep the line breaks in when I print out the field value?

I have already changed the plain text format to add "limit allowed HTML tags" rule for <a> <br> <p>, and removed the "display any HTML as plain text" rule.

Many thanks,

Ben

I worked it out. I just needed to use the following code:

print nl2br($taxonomy_term->field_address['und'][0]['value']);

This uses the print nl2br function to convert line breaks to <br> tags.


Webform redirect to login before submit I am creating a webform for my users to submit it but i have one question.
How to redirect users to login before they submit a webform?

Take a look at the Login Redirect module. It should do what you are describing.


problem with authenticated users I'm on drupal 8.3, I have do the same for the view block and it's ok just for the admin user, but for authenticated users, the block does not appear, what should I do?

Navigate to

  admin/people/permissions

and check if u have permissions for authenticated user.

Do you using the field permissions module?


Drill-down contextual filtering I've created a view called "Upcoming Events" that presents upcoming events in chronological order at the url /upcoming-events/all. Each event has associated tags. Currently my contextual filter is set so that replacing all in the url with a valid tag will present just events with that tag. Tags are set up as links with the url /upcoming-events/[field_tags].

My question is two-fold. How do I set up the contextual filter so that adding more tags on the end of the url (/upcoming-events/happy-hours/drupal/ for example) will further narrow the results presented to the user? Also, how do I set up the tag links to append the field tag to the end of the url rather than replace it?

If you click on More link under the contextual filter settings, there is an option to allow multiple values.

Enabling this option, you can use URLs like /upcoming-events/happy-hours,drupal to show events having both happy-hours and drupal tags.


Is there a way to dynamically resize remote images in drupal 7? Part of the site, I'm making has a YouTube video gallery. I want to display the thumbnails in list format but I need to resize them first. Using theme('image_style', etc) would be the simplest solution but it seems to only work on local files. Is there a way to get this to work with remote files?

Try out Imagecache External module

  Imagecache External is a utility module to allow you to use
  imagecache(D6)/image derivatives (D7) with external images.


How to load field configurations in code I have defined fields using the UI, and some more fields using YAML files in my custom module, e.g.:

The field storage is defined in field.storage.node.my_heading:

langcode: en
status: true
dependencies:
  enforced:
    module:
      - my_module
id: node.my_heading
field_name: my_heading
entity_type: node
type: string
settings: {  }
module: core
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

The field instance (which attaches a field to an entity) is defined in field.field.node.my_content_type.my_heading:

langcode: en
status: true
dependencies:
  config:
    - field.storage.node.my_heading
    - node.type.my_content_type
id: node.my_content_type.my_heading
field_name: my_heading
entity_type: node
bundle: my_content_type
label: 'Heading'
description: 'An optional heading'
required: false
translatable: true
default_value: {  }
default_value_callback: ''
settings: {  }
field_type: string

After installing this custom module, how do I get the field configuration in code?

The terminology is a bit confusing (as usual with Drupal), but here goes:

Field storage configurations are defined by FieldStorageConfig. To load one, do this:

$field = Drupal::entityTypeManager()->getStorage('field_storage_config')->load('node.my_field');

Field instance configurations are defined by FieldConfig. To load one, do this:

$field_instance = Drupal::entityTypeManager()->getStorage('field_config')->load('node.my_content_type.my_field');


Create a template for a custom page in Drupal 7? Is there a simple way to create a custom template in a theme for a custom page in Drupal 7.

I've tried all of the normal conventions:

page-custom_page_name.tpl.php
page-custom--page--name.tpl.php
etc.

None seem to be working. Help would be much appreciated!

Drupal automatically provides path based overrides; so if the path to your custom page is, say, 'custom/page/path' you can create a template file called 'page--custom--page--path.tpl.php`, which will only be used for that page.

Remember to clear Drupal's caches each time you add a new template file or the theme registry won't pick it up.


View showing related nodes before unrelated nodes I'm trying to create a view, which will show constant number of nodes.
I want it to show related nodes first, and after them (if there aren't enough related nodes) to show other nodes.
As far as i understand, contextual filters will remove all the unrelated nodes and I can't find sort order which will promote related nodes to the top.

Is there any way of doing this with views?

similarterms might fit your bill. If not, here is a comparison of 4 modules that show related content


How to Bi-directional link two nodes from different content type? Hello i am new to Drupal. I have used Joomla for very long time and some wordpress.

I want to link 2 or more nodes bi-directional. Meaning that if i link A to B, B must be also linked to A.

I will give you a simple example:

Lets say i want to make a Lyrics site. Where i will have 2 content types.

1) Artist / Band
2) Song Lyrics

The Artist / Band type will have information about the artist with maybe a photo and textaera for description.

The Song Lyrics will have the actual song lyrics (textaera).

Finally i want to link the Song Lyrics to an Artist / Band. So when i view the Lyrics page it will link to the Artist page. And when i go to the artist page it will link to all the lyrics that are available for that artist.

How can i do this in Drupal 7? Can i do it with the Core, or do i need to install additional Modules?

While still new and with rough edges, the Relation module will be the right module for that job.


Edit weight of block without using drag and drop I'm attempting to reorder blocks. I understand that it can be done by dragging and dropping on the block structure page, however I have a limitation.

When saving, the order isn't saved. This is most likely because there is a very large number of blocks and the server can't handle that many inputs in one form. So it just reverts to it's original position. I do not have access to the server so I'm unable to make the changes to allow the server to handle that many inputs.
I also do not have access to the mySQL database.

I'd like to be able to change the weight manually within the block, but weight is not a field I can edit when attempting to edit that specific block.

Is there a way to add this field? Or is there another possible way to perform this action?

you can do it by using context name in hook_context_load_alter() and tweak it.

/**
 * Implementation of hook_context_load_alter()
 */
function mymodule_context_load_alter(&$context) {
  if ($context->name == 'my_context_name_from_the_ui') {
    $context->reactions['block']['blocks']['my_block_name']['weight'] = -99;
  }
}


Webform Tokens lets me access form meta-info but not user-submitted values (with Fill PDF) I'm attempting to use the Fill PDF module to populate an editable pdf. The data source is a Drupal Webform submission. I'm specifying those values to Fill PDF using tokens from the Webform Tokens module.  I have also tried this using Webform's tokens made available to Fill PDF via the Webform Rules module, which does not work at all (no PDF is generated).

With the Webform Tokens module I have partial success: I can get a PDF to fill in with non-user-submitted values from the webform (such as the submission ID and the webform component label) but user-submitted values always end up blank. For example:

I enter the following into the Value field of the PDF-Field key in /admin/structure/fillpdf/[form ID]/edit/[pdfkeyname]:

The SID of this submission is [webform:meta-sid].
The value of the form component titled [webform:meta-label-textmetest]
is [webform:val-textmetest].`

For the submission in question the value of the textmetest field is "glasstest."

I go back to /fillpdf?fid=53&webform[nid]=4&webform[sid]=10 and it now reads

The SID of this submission is 10.
The value of the form component titled textmetest
is  .

Thus, the [webform:meta-sid] and [webform:meta-label-textmetest] tokens are being replaced, but not the token [webform:val-textmetest].

I have confirmed that the webform's ID is indeed 4, the SID is 10, the value of textmetest for SID 10 is glasstest, and the form ID for the pdf is 53.

I know that it is trying to access a specific submission, because if I use a nonexistent SID in the URL (e.g., /fillpdf?fid=53&webform[nid]=4&webform[sid]=99) the field reads: The SID of this submission is . The value of the form component titled  is  . , i.e. the SID and title don't populate for a nonexistent submission. However, I can't get at the values for any specific submission.

If I try Webform Rules enabled instead, instead using the tokens [webform:sid], [webform:textmetest-value], and [webform:textmetest-title], which are the corresponding tokens that Webform Rules exposes to Fill PDF, it does not even generate a PDF; I get a 500 internal server error.

Does anyone have any suggestions, either for how to make this work or for another way to get at webform values?

The issue is that Fill PDF 7.x-1.9 doesn't work with Webform 4 due to a change in the structure of the $submission variable from Webform via webform_get_submission().  See this post for an explanation and an ad hoc fix.


How to make submit button work in form themes I am trying to create a form which calls an external template file to format the form but ended up into a typical issue. This is what I was doing. I created a hook menu and called a theme, in the theme declared the template, and in template called the form elements and rendered along with html code. Everything is working fine except the submit button. If I render form directly, submit is working, or if I use drupal_get_form in menu page callback, it works (again template is not getting applied). I'm confused what am I doing wrong. I am a newbie so excuse me if this is a repetitive or stupid question.

Here is my code.
My module file named agents.module

<?php
function agents_menu(){
  $items=array();

  $items['myform']=array(
    'title'=>'Form',
    'description'=>'Submit Form into database',
    'page callback'=>'agents_form',
    'access callback'=>TRUE,
    'access arguments'=>array('access content'),
    'type'=>MENU_CALLBACK,
  );

  return $items;
}

function agents_form(){
  return theme('students');
}

function agents_theme(){
  return array(
    'students' => array(
        'render element' => 'form',
        'template' => 'customTemplate',
    ),
  );
}

function students_form($form, &$form_state){
  $form = array();
  $form['efname'] = array(
    '#type' => 'textfield',
    '#title' => 'First Name',
    '#size' => 28,
    '#maxlength' => 10,
    '#required' => TRUE,
  );

  $form['elname'] = array(
    '#type' => 'textfield',
    '#title' => 'Last Name',
    '#size' => 28,
    '#maxlength' => 10,
    '#required' => TRUE,
  );
  $form['submit_btn'] = array(
    '#type'=>'submit',
    '#value'=>'Submit',
    '#submit' => 'agents_myForm_submit'
  );
  return $form;
}

function students_form_validate($form, &$form_state){
  dpm($form_state['ename']);
}

function students_form_submit(){
  dpm('into submit');
}

and my customTemplate.tpl.php code looks like this

<?php
  dpm(drupal_get_form('students_form'));
  $form = drupal_get_form('students_form');
?>

  <?php print render($form['efname']); ?>
  <?php print render($form['elname']); ?>

  <?php print render($form['submit_btn']); ?>

<?php
  dpm(render($form['form_build_id']));
  print render($form['form_build_id']);
  print render($form['form_token']);
  print render($form['form_id']);
?>
<?php print drupal_render_children($form);

I am a newbie to drupal, and I was not able to figure out what am I doing wrong. If I directly render the form without rendering submit individually, (i.e. print render($form) ) it works fine. It would be a great savior of the day if someone helps me cross this hurdle.

You don't want to run your drupal_get_form from inside your template, you want to render it from your page callback. You'll instead declare the theme for your form with $form['#theme'] = 'students' in order to use your template.

function agents_form() {
  $form = drupal_get_form('students_form');
  return render($form);
}

function students_form($form, &$form_state){
  $form = array();
  $form['efname'] = array(
    '#type' => 'textfield',
    '#title' => 'First Name',
    '#size' => 28,
    '#maxlength' => 10,
    '#required' => TRUE,
  );

  $form['elname'] = array(
    '#type' => 'textfield',
    '#title' => 'Last Name',
    '#size' => 28,
    '#maxlength' => 10,
    '#required' => TRUE,
  );
  $form['submit_btn'] = array(
    '#type'=>'submit',
    '#value'=>'Submit',
  );

  $form['#theme'] = 'students';

  return $form;
}

You also had a '#submit' attribute on your submit button element but it would need to be set as an array rather than a string '#submit' => array('agents_myForm_submit'), However I didn't see that submit function defined so I removed it.

Then your customTemplate.tpl.php can be as simple as:

  <?php print render($form['efname']); ?>
  <?php print render($form['elname']); ?>

  <?php print render($form['submit_btn']); ?>

<?php print drupal_render_children($form); ?>


taxonomy delete vocabulary I have a huge taxonomy vocabulary (over 5k terms) and I'm using a shared hosting account.

Whatever I try to delete the vocabulary from drupal I get the error

Fatal error: Maximum execution time of 30 seconds exceeded in /home/username/public_html/drupal_site/includes/database/database.inc on line 2179

Anyway after looking online I found that with shared hosting I can't change the max_execution_time .

My next bet is to delete it from the database level in phpmyadmin.

How would I go about doing that? Are there any other ways for me to accomplish what I'm trying?

You could also download and install the site / database on a local machine, delete the terms, and then restore the updated database using the 'backup and migrate' module. That way you would have full control of php.ini settings.


Create image style options, when user is uploading an image Is there any way to provide image style options, when user is uploading any image and can select any style from the drop down?

Insert

  Insert is a utility that makes inserting images and links to files
  into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.

more details Upload images style


Difference between theme.info and drupal_add_js ( jquery-2.0.3 ) On a fairly new drupal (7.23) site I tried including the jquery-2.0.3.js file with the drupal_add_js function in one of my modules hook_init function.  All was working good and well when I was testing the login screen but then I went to some others pages, I got this error in firebug console:

TypeError: $(...).add(...).filter(...).once is not a function
http://XXX/sites/all/libraries/jquery/jquery-2.0.3.js?mw5wsb
Line 1670

(where XXX is my sitename)

So I noticed on one of my other sites the same library loaded fine when it was included in the theme.info file.  So I tried it that way and sure enough jquery-2.0.3 loads fine when I do it that way.  (ie.    scripts[] = js/vendor/jquery-2.0.3.js

Does anyone know why a jquery include would not work with drupal_add_js and why it would work with the theme.info file?

Many thanks.

d

Generally speaking you should avoid adding third-party libraries directly from your module. If all modules would do that, your site would end up with multiple loads of jQuery/Modernizr/Backbone/etc.
First see if there is an existing module for that, and if not - use Libraries API to declare a dependency in your custom module and then load the script afterwards. This way if some other module depends on the same library and declares dependency through Libraries API, Drupal will load only one file automatically, avoiding conflicts.
For jQuery, check out jQuery Update module. Drupal itself uses jQuery for forms and other elements, so it is not enough that only your module or theme work on the latest jQuery. All core widgets, effects and AJAX calls need to be ported for specific version. That's why  jQuery Update module exists - it upgrades the version of jQuery and loads updated Drupal scripts instead of the original ones, so the site does not break.
Regarding the differences between drupal_add_js() and adding a script filename in the theme.info, here's a summary:

When you add a script to theme.info file, it will be automatically loaded for all pages displayed with your theme. This means that if you are using an administrative theme, such as Rubik, your script will not be loaded on pages where you use that theme.
With drupal_add_js() you can load a JS file only when you need it (e.g. only on certain pages, for certain roles etc.).
drupal_add_js() also provides you with additional functionality, such as inline JS for variables.

Hope this helps.


Passing a number via page arguments in hook_menu() I am generating the return value for a hook_menu() with values from a query.

 $items[$record->path_prefix . '/my_path/%'] = array(
     'title' => 'Topic Redirect',
     'page callback' => 'my_callback',
     'page arguments' => array($record->id,2),
     'access callback' => TRUE,
     'type' => MENU_CALLBACK
   );

This will automatically pass the argument that is the record id to the callback function. I would like it to pass the value. Is there an easy way to do this?

I normally just wrap the value in quotes, that should convince the router system to leave it alone:

'page arguments' => array("$record->id", 2)


Limit user (not role) publication of content to specific menu subtree We have several roles. Each user is allocated to one role only.

Each user has a separate menu area - e.g.

user 1 - Profile
       - Product
       - Press Releases - release 1
                        - release 2

user 2 - Profile
       - Product
       - Press Releases - release 1
                        - release 2

What this question is NOT about:

It is not about restricting access to post by role (that is too blunt an instrument)

It is not about restricting access to view by role or individual user.

What this question IS about:

As the number of members increases, the "pick list" of menu items will become unmanageable. It also, of course, means that it is possible, for whatever reason, for users to post to someone else's area. We therefore need to lock each user's posting access to his own user account (in menu terms  [user1]  or [user2] and its subtree). Each user should not see, in the select box, menus that he cannot post to.

We need to allocate users to specific menu subtrees, presumably through either restrictions or permissions.

What does not work:

module: Menu subtree (applies to roles only)

module: Menu access (it crashed the site resulting in forced database maintenance)

module: User Permissions (it applies the standard permissions module for individual users, it does not add additional permissions.)

Node/content type: inserting a field - we can't see any way of importing the specific menu subtree that we want and, even if we could, we can't see a way of making the correct menu subtree appear for that specific user.

Any and all ideas are welcome!

Drupal's menu module is pretty good thing, but written with simple cases in mind.

Solution without using menu system:

Create a taxonomy tree representing the part of menu that gets repeated for each user
On node creation, omit menu altogether, let user choose taxonomy term from a tree instead
Use Views to render it all as one big tree, theming it so it would look like a menu

Added benefit is that you can easily move elements from user to user, allow users to change their names etc and it just works, no need to edit same thing in 2 places. And you can rename "menu element" once, in taxonomy, instead of "once per user".


Programmatically impersonating another user without causing the currently logged-in user to log out How should a module change the value of the global $user, execute its own code, and restore the original value of $user without causing the current user to be logged out if an error happens?

The drupal_cron_run() function gives a perfect example for exactly this, since it changes the current user to anonymous whenever cron is run, then switches back after it is done.

// Prevent session information from being saved while doing funky stuff.
$original_session_state = drupal_save_session();
drupal_save_session(FALSE);

// Force the current user to anonymous to ensure consistent permissions on
// funky stuff runs.
$original_user = $GLOBALS['user'];
$GLOBALS['user'] = drupal_anonymous_user(); // Or use user_load() for a non-anonymous user.

// Do funky stuff here...

// Restore the user.
$GLOBALS['user'] = $original_user;
drupal_save_session($original_session_state);


Error when aggregation is turned on in Views I have a view for Organic Group (og) that displays a list of the groups, a picture, the language, the categories the groups fall into, and a summary of the mission statement. All of this is neatly organized in a grid.

I want to add a membership count for each group in the view. As soon as I turn aggregation on, I get the following error message:

  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
  error in your SQL syntax; check the manual that corresponds to your
  MySQL server version for the right syntax to use near 'AS
  node_og_field_data_field_group_image_, node_og.title AS node_og_title,
  node_' at line 1

Does anyone know what's going on and how to fix it?

I finally found the answer for this. My view had a group picture; removing the group picture, turning the aggregation on, and putting back the group picture field solved the problem.

It's a problem others have had and that's how they all fixed it; See https://drupal.org/node/1809584.


Missing video source with Video module I am running Drupal 6.22 and updated the Video module to version 6.x-4.4 and FFmpeg Wrapper to 6.x-2.0-alpha1. Before I was using the swftools to show the videos, but now I wanted to try the HTML5 way. So there are videos in mp4-format (placed in the folder "original") and the converted ones in flv-format (in folder "converted"). After the discribed updates unfortunately no video is showing up - the problem seems to be quite similar. When I edit the content type ("Manage fields" --> "Display fields") and I select "Generic files", everything works as expected. A link to the mp4-File is displayed. But when I choose "Video" the path to the file is missing (only the jpg thumbnail is working correctly), it outputs only this whitout any  tag:

<video width="600" height="338" preload="auto" controls="controls" poster="URL TO JPG HERE.jpg" autoplay="autoplay">
</video>

Do you have any idea on how I could find the problem?

This only works when you also have an MP4 output format. The original video is not used as a source.


How do I load a library using xautoload and libraries? I am trying to load the facebook SDK (drupal 7) but I am getting the error

Error: Class 'Facebook\Facebook' not found in
FbPageSyncProcessSubmission::fbpagesync_facebook_sdk_initialize() (

My method

First download the facebook api  Facebook API as recommended

cd web/sites/all/libraries
mkdir fbpagesync
composer require facebook/graph-sdk

Install xautoload

drush dl xautoload && drush en -y xautoload

In my custom module declare the library

function fbpagesync_libraries_info() {
  return [
    'fbpagesync' => [
      'name' => 'PHP SDK for Facebook APIs',
      'vendor url' => 'http://developers.facebook.com/',
      'download url' => 'https://github.com/facebook/php-graph-sdk/master.zip',
      'xautoload' => function ($adapter) {
       $adapter->composerJson('composer.json');
     },
      'path' => 'vendor/facebook/graph-sdk/src/Facebook',
      'version arguments' => [
      'file' => 'vendor/facebook/graph-sdk/src/Facebook/Facebook.php',
      'pattern' => "/const VERSION = '([\d.]*(?!-dev$))/",
      'lines' => 60,
    ],
  ],
  ];
}

It looks OK in libraries_load/libraries_detect

array (
 'name' => 'PHP SDK for Facebook APIs',
 'vendor url' => 'http://developers.facebook.com/',
 'download url' => 'https://github.com/facebook/php-graph-sdk/master.zip',
 'xautoload' =>
   Drupal\xautoload\Libraries\SerializableClosureWrapper::__set_state(array(
   'closure' =>
   Closure::__set_state(array(
  )),
 'moduleName' => 'fbpagesync',
 'libraryName' => 'fbpagesync',
)),
'path' => 'vendor/facebook/graph-sdk/src/Facebook',
'version arguments' =>
  array (
  'file' => 'vendor/facebook/graph-sdk/src/Facebook/Facebook.php',
  'pattern' => '/const VERSION = \'([\\d.]*(?!-dev$))/',
  'lines' => 60,
 ),
'info type' => 'module',
'module' => 'fbpagesync',
'machine name' => 'fbpagesync',
'download file url' => '',
'library path' => 'sites/all/libraries/fbpagesync',
'version callback' => 'libraries_get_version',
'files' =>
array (
),
'dependencies' =>
array (
),
'versions' =>
array (
),
'integration files' =>
array (
),
'callbacks' =>
array (
  'info' =>
array (
  0 => 'libraries_prepare_files',
),
'pre-detect' =>
array (
),
'post-detect' =>
array (
  0 => 'libraries_detect_dependencies',
),
'pre-dependencies-load' =>
array (
),
'pre-load' =>
array (
),
'post-load' =>
array (
),
),
'post-load integration files' => false,
'installed' => true,
'version' => '5.6.3',
'loaded' => 0,
)

The calling code is

use Facebook\Facebook;

...

public static function fbpagesync_facebook_sdk_initialize($reset = FALSE) {
 $settings = variable_get('fbpagesync_settings', []);
 $facebookInit = new Facebook([
    'app_id' => $settings['app_id'],
    'app_secret' => $settings['app_secret'],
    'default_graph_version' => 'v2.2',
  ]);
}

It was calling the wrong composer.json. Facebook api has it's own.

The fix is

$adapter->composerJson('vendor/facebook/graph-sdk/composer.json');


Drupal pages translated, but both translated and untranslated pages showing up on view I recently started working on adding translation to my Drupal 6 site.
I am using the modules
1)Translation Manager
2)i18n
3)Language Switcher Dropdown

It seemed pretty straight forward to me.
I read the multilingual drupal guide
http://drupal-translation.com/content/setup-multilingual-site

I sent all my content type/strings to one of my translators (using local translators).
My translator translated one of our pages for a certain content type, and finished the translation.

The only problem is that the content type she translated has both the english and the translated version showing up on the same page.

Here is the page
http://caribbeanenvirolaw.org/ngos
The duplicated page is "Jamaica Environment Trust (JET)

I notice when I go to the french JET page the Language dropbox shows "Francais",
and when I go to the english JET page the language dropbox shows "English".

I would like the french translated pages to only show up if the language select box
shows French, and have the English pages be the only ones that show up if the language selectbox is set to English.

The NGO page that is showing both french/english JET pages is a view, but I couldn't
find anything in the views section regarding translation and only showing the current languages pages.

Little help?

***Update****

The page in the picture is a drupal "view". The content type "Belize - ....."
is in English, and has been translated to spanish/french.  Those spanish and french
translations show up as separate content type's on the drupal page (the view).

Since the language dropbox is set to "English" you would think that it would hide the spanish/french versions, but it is not.

For each of the "Belize - ...." content types (english, french, spanish), I tried multiple configurations to get drupal to leave out language content that is not for the language currently selected.
In the last image you see I'm setting the url to be "belize".
I used this same value for each of the translated contents.

Scrolling over the links for each translated "Belize - ...." content shows

1)English url =  caribbeanenvirolaw.org/belize
2)Spanish url =  caribbeanenvirolaw.org/es/belize
3)French url =  caribbeanenvirolaw.org/fr/belize

When I open, for example the spanish translation of belize page from the view,
I see

Notice that the language dropbox now say Espanol, meaning it is recognizing that it is a spanish page, but still it shows the spanish/french translations (as well as english) on the view (first image) no matter what the Languages dropbox has selected.

Keep in mind that I have also tried to not edit the url path's manually (leaving them blank). I get the same results from doing it that way too.

ANSWER

Heya, found the answer.
The view needs to have the correct filter added to it.

Go to Adminstration->views
Click the plus button next to the Filters section.

You will then see a list of filters pop up.
Find "Node Translation: Language. Add it.
You will then see a section that asks what you want to do with the filter.

Choose "Is One Of: Current User's Language"
That is it. Your views should now NOT contain multiple translations of the same document.


Popups API - Drupal 6.x-2.0-beta0 - Popup is automatically closing I am trying to add the site contact form in popup using Popups API - Drupal 6.x-2.0-beta0  module. In popups_test.module popups/test page I am able to add the link contact like following

function _popups_test_popups() {
  popups_add_popups();
 $output .= '<li>'. l("Contact Us", 'contact',
               array( 'attributes' => array('id' => 'test-popup','class'=>'popups')));
return $output;
}

Everything is working fine.

The same thing I am trying to add in a block like following

<?php
popups_add_popups();
print l("Contact Us.", 'contact', array('attributes'=>array('class' => 'popups')));
?>

Using this the popup is opeing and facing following issue,
1. when I submit the contact form without enter any information the popup is disappearing.  Anyone came across the same issue? Any help will be appreciatable

I have did some analysys and changed the following code its started working

$settings['popups']['originalPath'] = $_GET['q'];

//Replaced with following code

$settings['popups']['originalPath'] = 'popups/test';

There is a function in popups.js which will check the end point of the form. Not sure exactly the cause of the issue.

 return done = (path === Popups.originalSettings.popups.originalPath);


How to use entityQuery to select if a multiple value entityReference field does not contain the id I have an entity with a user entityReference field, which may contain multiple values. I wish to select using EntityQuery the nodes that do NOT contain the uid in the query.

$query
  ->condition('field_shared_with_user.target_id', $uid, '<>');

This only works to exclude $uid if there is only ONE value in the field. If $uid is present but some other uid is also present, it incorrectly includes this node in the result.

What is the correct syntax for writing a condition for a multiple value field?

The most I can find about writing these queries is here:

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Entity!Query!QueryInterface.php/function/QueryInterface%3A%3Acondition/8

gapple put me on the right track (at least a solution for my specific problem), and its a combination of his two ideas.

I needed to query for all the nodes that reference my user, then query for all the entities that match my main query. that gives me two arrays of node ids, and if I array_diff the first from the 2nd, I end up with the array of node ids i want.

so, a separate entityQuery is needed, but its not too computationally expensive in my case, I think.

$my_contacts = \Drupal::entityQuery('node')
  ->condition('type', 'sc_card')
  ->condition('field_shared_with_user.target_id', $user->id())
  ->execute();
$public_contacts = \Drupal::entityQuery('node')
  ->condition('type', 'sc_card')
  ->condition('field_public_directory', true)
  ->execute();
$public_not_in_my_contacts = array_diff($public_contacts, $my_contacts);


How to create db table while installing a module? I want to create a table in Drupal while installing a module (custom module which is crated by me). I tried in the below way, but I could not able to create a table in Drupal db. what am I missing, what else I have to do?

function custom_agent_handler_install() {

if (!db_table_exists('demo_score')) {
  $demo_score_schema = array(
    'description' => 'To store unique number and other details.',
    'fields' => array(
      'score'    => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE),
      'timestamp' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => '0'),
    ),
  );

return $demo_score;
}

}

You should implements hook_schema() in your modulename.install file. In druapl 7, you do not need to use hook_install to create database table.

  A Drupal schema definition is an array structure representing one or
  more tables and their related keys and indexes. A schema is defined by
  hook_schema() which must live in your module's .install file.

Code Snippets:

/**
 * Implements hook_schema()
 */

function custom_travel_api_schema() {

  $schema['custom_booking'] = array(
    'description' => 'To store the booking flight.',
    'fields' => array(
      'bid' => array(
       'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'The booking id.',
      ),
      'source' => array(
        'type' => 'varchar',
        'length' => '255',
        'description' => 'The source city for the booking.',
      ),
      'destination' => array(
        'type' => 'varchar',
        'length' => '255',
        'description' => 'The destination city for the booking.',
      ),
      'bdate' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The date of the booking',
      ),
      'amount' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The amount of the booking',
      ),
      'status' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The status of the booking(0 -> In process, 1 -> completed)',
      ),
      'uid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The user id of the booking',
      ),
    ),
    'primary key' => array('bid'),
  );

  return $schema;

}

You can check this for more reference.


Dynamically adding a CSS class to a view row with template.php I've actually reached the bottom of Google trying to figure out how to add a css class to each row of a view.  The trick is that I need the class for each row to be dynamically determined based on some of the data from the node that the view pulls from.  The function that pulls this off neatly for the node is -

function pgc_preprocess(&$variables) {
  $node = $variables['node'];
  if ($node->type == "event") {
    $variables['event_class'] = '';
    $num_trainers = $node->field_number_of_trainers[0]['value'];
    $count = count($node->field_trainer);
    if($count < $num_trainers) {
        $variables['event_class'] = 'red';
    } else {
        $variables['event_class'] = 'green';
    }
    return $variables;
  }
}

The point of this is to color code an event that hasn't had enough folks sign up.  There will be a list of events on the front page, and I need  them to be color coded also.  I really hope there some simple solution along the lines of -

function pgc_preprocess_views_view_unformatted(&$variables) {
  // Magic here, preferably having something to
  // do with the function I already wrote.
}

Just dropping <?php print $event_class ?> in the view .tpl doesn't do it.

function pgc_preprocess_views_view_unformatted__home_listing(&$vars) {
  // Borrowed this bit from http://drupal.org/node/312220
  $view = $vars['view'];
  $rows = $vars['rows'];

  foreach ($rows as $id => $row) {
    $data = $view->result[$id];
    $event_class = get_the_classes($data->nid);
    $vars['classes'][$id] .= ' ' . $event_class;
  }
}

function get_the_classes($nid) {
  $node = node_load($nid);
  global $user;
  if ($user->uid != 0) { // Not for anon users.
    $event_class = '';
    if ($node->field_trainer[0]['uid'] == NULL) {
        $event_class= 'red';
    } else {
        $num_trainers = $node->field_number_of_trainers[0]['value'];
        $count = count($node->field_trainer);
        if($count < $num_trainers) {
            $event_class = 'red';
        } else {
            $event_class = 'green';
        }
    }
    return $event_class;
  }
}

Don't know if it's pretty.  Don't know how it performs.  But it works.

EDIT (02-01-2012): after working with Drupal for another year now, I'd have tried to find some other way to do this besides running node_load() on every row of the view.


taxonomy_select_nodes put order promote I tried to make order by promote when I call taxonomy_select_nodes. Like this:

$node= taxonomy_select_nodes(163, TRUE,10,array('t.promote' => 'DESC','t.created' => 'DESC'));

But I got an error! Is there any solution?
Thanks

The function you are using

taxonomy_select_nodes($tid, $pager = TRUE, $limit = FALSE, $order = array('t.sticky' => 'DESC', 't.created' => 'DESC'))

And Parameters

$tid: The term ID.

$pager: Boolean to indicate whether a pager should be used.

$limit: Integer. The maximum number of nodes to find. Set to FALSE for no limit.

$order: An array of fields and directions.

In your case we can see you are joining field 't.promote' it seems like the field not present, please review you code once and follow the stranded format  like https://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.module/function/taxonomy_select_nodes/7


How do I enable anonymous users to vote? I created a poll, and I am displaying it in a block on my site. The radio buttons are available, when I am logged in; when I log out, they aren't showing, and the vote results are instead displayed.

How do I enable the anonymous users to vote?

Looks like you need to enable the permission for anonymous users and also

Drupal core poll module only allows one vote per anonymous IP address. check this link https://drupal.org/node/866168

The Poll Enhancements Module modifies this behavior to allow multiple anonymous votes from the same IP address.

  This module enables anonymous users to vote on polls without page
  cache troubles or IP address restrictions. It is designed to work on
  top of core Poll module.


post editor with image upload I need a module or patch or something for a post editor that lets you upload images into the post

any help is appreciated.

The Media module might be a good solution to this, depending on your needs. It is still under development and still has a few issues, but it's probably stable enough to us (we are using it on several production sites without any problems). I think this module has the best approach to the problem of embedding images within node content.


How to theme specific taxonomy term page? Possible Duplicate:
  Theme specific taxonomy page

I have a taxonomy term page that shows all the related terms with their details ... i just need to show the list of the terms as links to node page. Which is the best way to do it?

EDIT: i tried to create taxonomy-term--VOCAB.tpl.php file, it is read but $content variable is empty .... so i don't understand how Drupal handles it.

The best way is to show it by Views module. You blocked default viewing of taxonomy and change it to Views. Video include.


the WYSIWYG editor doesn't show up, drupal 7 I installed the CKEditor in Drupal 7, following the steps in the documentation. I set up the right permissions and the text options and I cleared the caches, but when I want to add or edit some content, I have only the plain textarea.

However, when I navigate to Administration » Configuration » Content authoring » CKEditor. and edit the Filtered and Full HTML, the WYSIWYG editor shows up as it should when I expand the Editor Appearence tab, so I assume it's well installed.

What I find peculiar is that when I navigate to Administration » Structure » Content types, select a content type and click manage fields and edit for the body field
the area just below the text: "The default value for this field, used when creating new content." is still the old textarea. I don't find any option to change it, as if the WYSYWYG editor wouldn't exist.

Anyone has an idea, a solution? Is it something I miss here?
Thanks a lot for your help.

It sounds as if you've selected "Plain text" instead of "Filtered text" as your default text processing option.  To change this, navigate to Administration » Structure » Content types, select the content you experience problems with and click manage fields and edit  on the body field (and other text fields you want to use the wysywyg editor). Make sure that the preset text format for that text field is set to to one of the formats configured for wysywyg (e.g. Filtered HTML).

To make sure that Filtered HTML is selectable, you need to make sure that the setting for "Text processing" is set to Filtered text (not Plain text):

Press Save settings after changing this.

Make sure that when you create content, a text format that is set up to use use WYSYWYG (e.g. Filtered HTML) is selected.  The screen dump below shows how the pull-down menu immediately below the text field for content should look like:

Other thinks to try when debugging a CKEditor setup:

Here are some more tips on debugging a CKEditor setup.  They probably don't apply to you, but may help others that arrive at this question while searching for a cure for CKEditor blues:

Clear the cache:

Remember to clear the cache after you've changed any setting that has something to do with wysiwyg.  Not clearing the cache is probably the most common source for CKEditor not showing up as you would expect.
Check out that roles are configured correctly:

Navigate to your text formats: Administration » Configuration » Content authoring  » Text formats and ensure the roles are configured correctly.

Add the roles you want to use wysiwyg to Filtered HTML and Full HTML.

Check out that profiles are set up right:

Navigate to your ckeditor profiles: Home » Administration » Configuration » Content authoring » CKeditor

Go to the profiles, and verify that the text formats for the profile are set, and the editor appearance is set properly.

Under Basic Setup, check the text formats that apply
Under Editor Appearance, set default state to enabled, and show the toggle.

PS: For a  secure use of WYSYWYG, I recommend using a custom text format filtered with the WYSIWYG Filter.  How you do this is described in this tutorial. However, first get it working, then start tweaking to make it secure.


Drupal 7 db_query how to return regular array from varchar field I am attempting to combine two arrays - one is stored in the database in a varchar field. Something like this.

["0","1","2","68","69","95","96","97","98","99","100"]

I am bringing in a similar array that comes from the front end.

["0","1","2","45","66","95","97","98","99","100"]

I need merging the two and remove duplicates.

   //merge post data and stored data
      $merge = array_merge($arr1, $arr2);
      //remove duplicates
      $merge = array_unique($merge);

My problem is that when retrieving the varchar field, I am not getting a normal array but an associative. Here is my code.

$arr2 = db_query('SELECT stats FROM {my_db} WHERE uid = :uid AND nid = :nid', array(':uid' => $usid, ':nid' => $noid))->fetchAll(PDO::FETCH_ASSOC);

I need this to return a regular array, not an associative to combine the two and remove duplicates. Does anyone know how?

When I do a print_r() on $arr2 it returns the following.

Array
(
    [0] => Array
        (
            [stats] => ["0","1","2","68","69","95","96","97","98","99","100"]
        )

)

I can't seem to be able to merge it and pass it to array_unique() on.

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

$arr2 = db_query('SELECT stats FROM {my_db} WHERE uid = :uid AND nid = :nid', array(':uid' => $usid, ':nid' => $noid))->fetchCol();

print_r($arr2[0]);


How to display a message on login until a user fills out a specific Webform? Relevant modules installed:

Rules.
Webform.
Webform rules.
Conditional rules.
Permissions per Webform.

What I have tried:

Rule 1: activates on user login that displays a system message.
Rule 2: activates on Webform submission with the condition that the Webform's name is the required name. The rule executes PHP code to disable Rule 1 if true.

/**
* Implements hook_update_N().
* Disables name_of_rule rule.
*/
function hook_update_N() {
  $rules_config = rules_config_load('name_of_rule');
  $rules_config->active = FALSE;
  $rules_config->save();
}

However, this set of rules is NOT working at the moment.

Concerns:

If Rule 1 was working, how do I ensure that it permanently disables Rule 1 per user, and not globally?
Is there a better way to do this?
For example, all I should need is one rule: On user login + if a Webform has not been filled out, display a message. However, I have not been able to find a module that adds the "If Webform has not been filled out" rule.

I think the module you are looking for is 'Rules Webform Submitted'.

This module is similar to Webform Rules in that it supports integration between Webform and Rules, but different in that Webform Rules supports the Event "Webform Submitted", while Rules Webform Submitted provides a Condition which is typically triggered by a Node Event.

So, you can use the event 'On user login' and the condition that 'Rules Webform Submitted' offers to create your rule.


Do I have to create a module for just one _alter function? I want to write a hook_entity_info_alter function.

Do I have to create a module just for this one function?

No...

All alter hooks are also run for themes, so you don't have to create a module.

e.g.

function MYTHEME_entity_info_alter(&$info) {
  // ...
}


Extending existing menu/route in module_menu_alter Trying to extend Rooms (rooms_booking_manager):

Originally, there is an enquiry-page which takes arguments

"enquiry/[startDate]/[endDate]/[roomNumber]"

I want to write a more specific handler IF arguments persons and children are given as in enquiry/startDate/endDate/roomNumber/numberOfPersons/numberOfChildren; in that case my own handler should take precedence.

This is the code used by the module.

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

  $items['enquiry/%start_date/%end_date'] = array(
    'title' => 'Ask about availability',
    'page callback' => 'rooms_booking_manager_enquiry_page',
    'page arguments' => array(1, 2),
    'access arguments' => array('book units'),
    'type' => MENU_CALLBACK,
  );

  // …

  return $items;
}

This is the code I use in my module.

function netfactory_rooms_menu_alter(&$items) {
  $items['enquiry/%start_date/%end_date/%persons/%children'] = array(
    'title' => 'Ask about availability',
    'page callback' => 'netfactory_rooms_enquiry_page',
    'page arguments' => array(1, 2, 3, 4),
    'access arguments' => array('book units'),
    'type' => MENU_CALLBACK,
  );
}

Nevertheless, if I call enquiry/startDate/endDate/roomNumber/numberOfPersons/numberOfChildren rooms_booking_manager_enquiry_page() is called instead of netfactory_rooms_enquiry_page().

Coming from a .NET MVC background, I was thinking that the order (most specific first) is important; so I also tried setting weight=-1000 on my own route, but that did not help either.

How can I hook into a module to add a route which is MORE SPECIFIC than an existing route?

I would try netfactory_rooms_menu() (i.e. hook_menu() instead of hook_menu_alter()). You are effectively creating a new menu callback, not extending an existing one.

Also, CLEAR THE CACHE before trying the new path.


How to custom theme Inline Entity Form (IEF) - using a .tpl.php file Is there a way to theme the Inline Entity Form (IEF) for example creating a .tpl.php file for that form and just declaring it on the theme's template.php?

I wanted to create a .tpl.php specifically since I want to add in custom codes in the form like, views, a little html, jquery and css.

Any help would be greatly appreciated.

I don't think that Inline Entity form supports that. You could alter the behaviour of the form itself though with

 function THEMENAME_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
   // your alters
}


How to override a module theme function in a custom module but still allow themes to override the template file? I'm writing a fairly simple module which allows the removal of colons from field output on a per field basis and I need to override the core field module's theme_field function in my module.

I can modify the theme registry with hook_theme_registry_alter() and change the field function to point to my custom function. Unfortunately once I do that I'm no longer able to override field.tpl.php in a theme.

The cascade I'd like to achieve is in order of template preference (most important first):

Active theme's field.tpl.php
My custom module's field.tpl.php (or custom_field theme function)
Field module's theme_field function

Is this possible?

This answer comes close but requires a differently named template which I don't want. I'd like to keep things clean for the themer so if they override field.tpl.php in their theme the output is as expected, rather than having to copy a different tpl file from my custom module.

Think what you describe could work without falling back to the field module's function:

Add <?php function MODULENAME_preprocess_field($variables) ?> and set a $colon variable with either ':' or ''
Copy the theme_field function in your module and rename it <?php MODULENAME_field(&$variables) ?>
Replace the code that renders the label with: <?php $output .= '
' . $variables['label'] . $variables['colon'] . '&nbsp;
';?>

Might also just document for themers that in the template file they should use $colon for the module to work.


Filtering Content based on URL arguments from Calendar Module I have a page for the Calendar module on my site. Below the calendar, I have a table view that displays links based on taxonomy terms that correspond to the year-month format of the calendar module URL arguments (which change when the user changes the calendar month). I'm new to Drupal and can't figure out how to filter these results based on whether or not the content term matches the URL arg from calendar. Do I use contextual filters? Thanks for the help.

edit: I should mention I am using Drupal 7.

I am not exactly sure what you mean. Could your provide an example of what the URL looks like?  Off the top of my head I think that you would just want to use view arguments.


Is there a way I can display one image field if another one does not exist using visibility rules in node template? I can do something like this with a text field, because I can compare it to an empty string, but I can't figure out how to do it with an image field.

Visibility rules supports content:exists, but this only applies to the content the rule applies to, not another field.

Is there a way I can display one image field if another one does not exist?

I would suggest using views to create a block based on the filter criteria where the first image field is empty.


Showing more detailed error messages to user im making an app with titanium that connects to a drupal backend. im using the awesome library (https://github.com/jbeuckm/drupal-client).

how can i show more detailed error messages (e.g. email/username has already been taken)?

i only get a 406 error code in ios when i register a new user that has already been registered.

error: {"success":false,"code":406,"source":{"url":"http://domain/user/register.json","method":"POST","ondatastream":null},"type":"error","error":"HTTP error"}

i noticed that when i connect with android there are more detailed messages available (e.source.statusText for instance).

any ideas?

update:

in android i get the information that i would need (statusText). why cant i access it in ios?

error: {"code":-1,"source":{"autoRedirect":true,"status":406,"allResponseHeaders":"Date:Mon, 13 Jul 2015 10:09:47 GMT\nServer:Apache/2.2.15 (Red Hat)\nExpires:Sun, 19 Nov 1978 05:00:00 GMT\nCache-Control:no-cache, must-revalidate, post-check=0, pre-check=0\nContent-Length:259\nContent-Type:application/json\nKeep-Alive:timeout=15, max=100\nConnection:Keep-Alive\n","connected":false,"password":null,"validatesSecureCertificate":false,"tlsVersion":0,"responseText":"{\"form_errors\":{\"name\":\"The name editor83 is already taken.\",\"mail\":\"The e-mail address editor83@vodes.net is already registered. Have you forgotten your password?\"}}","username":null,"responseXML":null,"statusText":"Not Acceptable : The name editor83 is already taken. The e-mail address editor83@vodes.net is already registered. Have you forgotten your password?","apiName":"Ti.Network.HTTPClient","location":"http://editors-testdrupal.rhcloud.com/rest/v1/user/register.json","readyState":3,"domain":null,"responseData":{"height":0,"bubbleParent":true,"type":2,"mimeType":"application/json","apiName":"Ti.Blob","nativePath":null,"file":null,"text":null,"length":259,"width":0},"connectionType":"POST","autoEncodeUrl":true,"bubbleParent":true,"_events":{"disposehandle":{}}},"error":"Not Acceptable : The name editor83 is already taken. The e-mail address editor83@vodes.net is already registered. Have you forgotten your password?","success":false}
[INFO] :   ALERT: (KrollRuntimeThread) [47,17536] Not Acceptable : The name editor83 is already taken. The e-mail address editor83@vodes.net is already registered. Have you forgotten your password?
[INFO] :   [object Object]account was not created

update 2:

it seems to be more of a ecplise/android/ios issue, so ive posted the question on the main forum.

https://stackoverflow.com/questions/31381522/different-rest-object-output-in-android-and-ios

if i get an answer ill post it here as well.

You might want to check services.alter.api.php

As described in this post

<?php
/**
 * Allows alteration of error data before the status code or message are returned.
 *
 * @param array $error_alter_array
 *   An associative array with the following keys:
 *     - 'code': the HTTP status code.
 *     - 'header_message': the message returned as part of the error response
 *       (for instance, "404 Not found").
 *     - 'body_data': data that was passed to the thrown exception.
 * @param array $controller
 *   The current controller definition.
 * @param array $arguments
 *   Arguments passed to the current controller.
 *
 * @see RESTServer->handleException()
*/
function hook_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments) {

}


Create menu tabs with views How can create menu views tabs of node? In Drupal 7 i can create views like this:

when i visit node/1/teaser it's show good.

But with same setting in drupal 8.

when i visit node/1 show error:

  Symfony\Component\Routing\Exception\MissingMandatoryParametersException:
  Some mandatory parameters are missing ("arg_0") to generate a URL for
  route "view.menu_tabs.page_1". in
  Drupal\Core\Routing\UrlGenerator->doGenerate() (line 171 of
  core/lib/Drupal/Core/Routing/UrlGenerator.php).

and node/1/teaser show error:

  Symfony\Component\Routing\Exception\MissingMandatoryParametersException:
  Some mandatory parameters are missing ("node") to generate a URL for
  route "entity.node.devel_load". in
  Drupal\Core\Routing\UrlGenerator->doGenerate() (line 171 of
  core/lib/Drupal/Core/Routing/UrlGenerator.php).

This is a known issue in views.

The issue is that the route parameter for entities needs to be named:

  This view will be displayed by visiting this path on your site. You
  may use "%" or named route parameters like "%node" in your URL to
  represent values that will be used for contextual filters: For
  example, "node/%node/feed" or "view_path/%". The named route
  parameters are necessary when used within paths used by entities such
  as "taxonomy/term/%taxonomy_term" or "user/%user/custom-view

This is for the first error message.

The second one is caused by the devel module. If you still get this error after renaming the route parameter, you have to check the issue queue from this module.


How to check if the current page is a 404 error from a module/template? How to check, in D7, if the current page is returning a 404 error from a module/template?

In Drupal 7, you can use drupal_get_http_header().

In the template.php file, use this code.

$status = drupal_get_http_header("status");
if ($status === '404 Not Found'){
  // Do something.
}

In Drupal 8, you can use the following code in a hook.

$route_name = \Drupal::request()->attributes->get('_route');
if ('system.404' === $route_name) {
  // Do something.
}


How to handle separated stock for a product bundle? Following the scenario that I want implement in my store. There are three products: A, B, C. My purpose is to sell two bundle composed by AB and BC.
Each product has its stock: A x10, Bx5, Cx20. The bundle products are dependable by the stock of every single product so it will not possible to order more than 5 AB product (or BC product) because every time a bundle product is bought the stock of every single must descrease.

When a single product's stock runs out, every bundle product composed by that single product can't be sold.

Is there any way to achieve my purpose?

I am the author and maintainer of the Commerce Product Kit module which is close to your requirement.

  It provides a "field formatter" for the "product reference" or an
  "entity reference" fields to add all the commerce products referenced that
  field to the cart at once.

It also has support to the commerce stock module. If a product kit has 3 products in it (A, B, and C), and say one of them is out of stock (B), it is not added to the cart.

Not allowing any product to be added to cart even if one of the product from kit is not in stock makes sense and can be considered a good addition to the cart.

I have created a feature request in the issue queue for the same :
 #2821442 : Disallow adding product kit to cart if one product is out of stock.

While I do not have the time to implement it myself now, I would be happy to review any patches and make this a part of the module.


How to handle GET parameters in the proper Drupal way I am working on a module that will handle the email subscription functions for our newsletters.

Email newsletters are sent out to subscribers with a link on them for them to unsubscribe. This link is in the format http://www.site.com/opt-out?email={email_address}. This is how the links are formatted and I can't change that.

What is the proper way to deal with that parameter using Drupal? Of course I have access to $_GET['email'], but is this the proper way of accessing it in a Drupal module? What about input filtering? Should I just do a plain $email = filter_var($_GET['email'], FILTER_VALIDATE_EMAIL); ?

When faced with this url structure,  you can use $_GET in the usual PHP way. Drupal urls are usually generated with parameters separated by /, and as you probably know,  arg() is the right tool when this is the case.

As for the email validation, there are native functions that validate, but the validation is quite basic:

//check if this is a valid Drupal username
user_validate_name('USERNAME');

//check if this is a valid email address
user_validate_mail('test@test.com');

If you had to do this in a form, one can add validation functions where needed with hook_form_alter:

/**
 * Implementation of hook_form_alter().
 */function my_module_form_alter(&$form, $form_state, $form_id)  {
 if ($form_id == 'user_profile_form') {
  array_unshift($form['#validate'], 'email_check_validate');
 }
}

/**
 * Validate profile form
 * Force form error if new email address matches current email address
 *
 */
function email_check_validate ($form, $form_state)  {
  global $user;
  $old_email = $user->mail;
  $new_email = $form_state['values']['mail'];

  if ($old_email ==  $new_email) {
    form_set_error('mail', t('Your email could not be changed'));
  }
}

But this does not apply in your case, it was just an example for when you need to do validation through a form.

Hope this helps, cheers!


Displaying Content Flagged by User Name with Flag Module I'm using Drupal 7.38 with the Flag (v7.x-3.6) module, along with Views. I'm setting up a flag for content.

My goal is to display a list of users whom are flagging content (along with aggregated count of number of items flagged). With the desired ULTIMATE goal of being able to click on the user's NAME (not UID!) and seeing all the content that the selected user has flagged.

After much research and advice, I was able to eventually accomplish this! The solution was that I had to set up 2 views:

one being a content view.
and the other one being a user view.

Some more details about these views:

Each of these views with properly configured relationships and contextual filters).
Only after using 'Rewrite Results' field on the user view (shown below). - Redirecting the output field as a link to the path created by the content view displaying the correctly associated users flagged content.

Here is a screenprint of the 'Rewrite Results' in my User view:

MISSION ACCOMPLISHED, so I thought ...

However, this is all fine and dandy with 1 problem: when landing into the URL which contains a nice display of the content flagged by the user that was just clicked, I have no way (or 'know' of no way) to successfully migrate the user name into the header of this new page! Labeling & confirming the content now in front of them. So after clicking on a user name with flagged count of content, you land on a nice page of content, but it's unlabeled!

I need to somehow pass, to the new page, the UID (not logged-in!) of the user that was just selected by clicking on the user's name. I cannot figure out how to do.

I tried using the Token Filter module to place the variable into a custom block heading the new page, but it did not work (Token Type not supported).

Any help, hints or suggestions would be highly appreciated!

I had the same issue where I wanted to show the title of the content flagged with a certain flag by each user. I solved it as follows:

Created 2 views - 1 of users and another of content
In the user view, add 'Flags: User's flaggings' relationship (Refer attachment user_view)

In the content view, add 'Flags: Node flag' relationship and 'Flags: User uid' contextual filter (Refer attachment content_view)

Select 'Display contents of "No results found"' for 'WHEN THE FILTER VALUE IS NOT IN THE URL' in the contextual filter added in step 3
Set the format of the content view as 'Unformatted list' and uncheck 'Create a label' option for the 'Content: Title' field
Install Views Field View module
Embedd the content view inside the user view as a field by passing uid as a contextual filter to the content view

Hope this helps someone.

Regards,

Supriya Rajgopal


Forbid or autocorrect a certain term in a vocabulary I am looking for a way to prevent a certain term to be created in a vocabulary. I don't know if there exists a contrib module with this functionality yet. Searches on Google did not deliver so far.

In fact, what I am trying to accomplish is this. In my native language we say "Brussel" but the English version is "Brussels". We have 20 editors and the one uses "Brussels" as a tag, another one uses "Brussel", which ends up with 2 seperate taxonomy overview pages. Yes, I could make it a guideline to use only "Brussel" as a tag, but overtime, they probably forget.

So is there a way that I can 'block' the use of "Brussels" as tag or autocorrect it to "Brussel" when they use "Brussels"?

Thanks for the help already!

The autocorrection scenario is one the use scenarios covered by the Synonyms module. It's a general purpose tool that works with taxonomy term references (tags) as well as other entities. It also has other integrations with projects that help with mitigating complexities with  duplicate taxonomy terms (e.g. Term Merge).


How can I add a skip button above the webform (with multistep) I use webform with multistep for a quiz. I want to add a "skip" button (equivalent to the submit/next button in the bottom of the form) above the form so that people can go directly to the next question without having to scroll down the page like that :

"
Skip this question

My form

< Previous | Next >"

I succeeded to add an another submit button (check code below). But when I click on this button it returns to the previous step instead of going to the next step ... I don't understand why .. And I can not put it above the form.

function mytemplate_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
  case 'webform_client_form_13':
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('skip'),
    );
    break;
  }
}

Have you got an idea for help me ?

Thanks you for advance

PS : sorry for my bad english

It seems that basically, you want a copy of "next", but with different title and placed on top. To achieve it:

Examine structure of form you are alerting. Find where original "next" is defined.
Create a copy of it. Use code like:

$form['my_skip_button'] = $form['path']['to']['next']['button'];

You Don't really need to know or care what it is, you need a copy, so you go and make a copy, simple as that.
Set weight to something low to get it to top:

$form['my_skip_button']['#weight'] = -10;

You can alter the title in the same way you altered weight.


How to filter views results by value of profile field of currently logged in user? When I create a user a 'supplier' must be selected. When a user creates a product a 'supplier' must also be selected. Now I would like to show all the products with supplier = supplier logged in user. I now have a table with all my products listed, but now I need to add the filter. Is there a module for this or can this be done in another way? Because when I now want to add a filter only the product fields are shown.

Instead of listing products filtered by Supplier field. You want to build your View from Users and add a relationship to Products linked through your Supplier field -- see this thread with further documentation:
https://drupal.org/node/1111722

So its something like the following from my above link:

  Create a user view.
  Add a contextual filter on user: uid. If no filter value is present, build a default value using the currently logged in user. (This will
  give you exactly one user object in your view -- the logged in user.)
  Add a relationship, using the relevant taxonomy reference field on the user accounts. This will bring you information about the
  "interest" term for the logged in user.
  Add another relationship, called "term: nodes marked with term" (or something like that). This will bring you information about all nodes
  marked with the interest term for the logged in user.
  Either set the view to display node teasers, or select a number of fields to display.
  Add a display as usual. Done!

Alternatively you could use Views Global Filter to set a filter based on the profile value most likely.


How do I change the field title on the "Generate automatic URL alias" checkbox in pathautho? How do I change the title of the checkbox "Generate automatic URL alias" on the pathauto fieldset on the node add page?

In my hook_form_node_form_alter I don't see this anywhere in the $form.

One option is to utilize the String Overrides module. Depending on exactly what you are trying to do, it may be a bit easier to administer and manage this change via the admin rather than in code.


Migrating revisions from external data source We are trying to migrate content from an external data source into Drupal 8 using the core migrate modules.  This is a stripped down example of the data being migrated:
id     resourceId     articleId     version     title          body
---------------------------------------------------------------------------
1      10             10            1           Page title     Page content
2      10             10            1.1         Page title     Page content
3      10             10            1.2         Page title     Page content
4      11             11            1           Page title     Page content
5      11             11            1.1         Page title     Page content

The id field is the unique identifier, and is the field set in the getIds() method, when as you can see the resourceId and articleId are more a preferred representation for a node id to be migrated into Drupal.
From my understanding, after reading through the migrate_example modules, the query() method must only return a single row; so when our migration runs, all these records are migrated as new nodes when in the previous database they were just revisions of one piece of content.
If we are intended to only return a single row in the query() method, what is the best way to only migrate the most recent version of each piece of content?
My first attempt was to try and achieve this in the processRow() method, but then if the migration is going through the table row by row, then how can you remove/update a previous row if the next row is a more recent version?
We have an option to just run our own script on the table first, to filter out all most recent versions and then run the migrate script on that, but I would like to know if there is a way to achieve this using the core modules in Drupal.
Thanks in advance.

Yeah, this part is not documented at all, I had now also problems with it, so here is how I solved it:
When you want to migrate a content that has revisions, you need to migrate the first version with the entity:node plugin, then you migrate the next versions with the entity_revision:node. You don't do anything else, just change the destination plugin and when you migrate the revisions, you set the nid value to the first version of the node. So you keep the body and the file and other fields, you just add the nid field, so the revision plugin will know where to put the content. That's it at least from the yml part.
From the source, you have two one for the node plugin where you list only the first version of your content that you want to migrate and one for the revisions where you list everything EXCEPT the first version also, you have a new column which contains the first version's ID for every revision's it's own.

If you migrate the current publish one into the node table, and you migrate the rest into the revision, the IDs, the order of the revision and some other things will be messed up. At least my case was that.

By code (not 100% complette, just main parts):

migrate_plus.migration.node.yml:

id: my_node
source:
  plugin: my_node
process:
  title: title
  body: body
  langcode:
    plugin: default_value
    default_value: "und"
  status:
    plugin: default_value
    default_value: 1
  #other fields except nid.
destination:
  plugin: entity:node

Query for the source plugin (id = my_node):
SELECT id, title, body FROM content WHERE version = 1
in getIds() the id is the only id.

migrate_plus.migration.node_revision.yml:

id: my_node_revision
source:
  plugin: my_node_revision
process:
  nid:
    plugin: migration_lookup
    migration:
     - my_node
     - my_node_revision
    source: first_version
  title: title
  body: body
  langcode:
    plugin: default_value
    default_value: "und"
  status:
    plugin: default_value
    default_value: 1
  #other fields.
destination:
  plugin: entity_revision:node

Query for the source plugin (id = my_node_revision):

SELECT first_ver.id AS first_version, c.id, c.title, c.body FROM content c
  INNER JOIN (
    SELECT * FROM content c
    WHERE version = 1
  ) first_ver ON c.resourceId = first_ver.resourceId AND c.articleId = first_ver.articleId
WHERE c.version <> 1

in getIds() the id is the only id.

The above example will give new id's for the content.


Product page on brands block I created pages for brands that I sell on my shop. Each product is associated with a brand taxonomy term. I created a view block that displays pages of brands. The block is displayed throughout the store and displays the entire list of brands. How to display only those brands related to product pages?

I know we need to use contextual filters, but I do not know how to configure.

You can do this with the following:

Create a new View to display the Taxonomy Terms for Brand

In the Views UI, add a new Relationship Taxonomy term: Content with term, and uncheck "require this relationship".
Add a new Contextual filter : Content: Nid and choose the just-created relationship as the relationship. Provide default value > Content ID From URL under When the filter value is NOT available.


What database table can be emptied in order to make database lighter? Are log files in drupal take a lot of space? I want to create a dump file but it's over 1000mb. What tables can be harmlessly emptied from the database directly or through drupal interface?

Usually all tables with cache_ prefix are safe to be emptied.

The log table records can take a lot of space, depending on your settings on how many log messages you want to save. You can configure this at admin/config/development/logging.

How many nodes/users do you have on the website? Do you have enabled the core search module? What other modules do you have?

If your website has tens of thousands of nodes and users, 1GB is a normal size of the database dump.


How to specify the correct private file path in a block I have a Drupal site at http://example.org/xyz

Per the instructions here, I have set up a private file directory outside the web root.

So let's say the web root is at /home/public_html/example/xyz
The private directory is at /home/public_html/private

I have that private directory set in the settings.php file and cleared the caches. It shows up correctly here: http://example.org/xyz/admin/config/media/file-system

After clearing the cache, I can indeed confirm there is a valid .htaccess file in /atrium/admin/config/media/file-system

The directory permissions for the private directory are 755.

So now I specify the file location of a link in a block as "/xyz/system/myfile.pdf"

When I click the link, the home page simply reloads (instead of a download window), but the URL now reads:
http://example.org/atrium/system/myfile.pdf

I've tried many other variations, and they all fail.

What am I doing wrong?

drupal will not let you specify a direct link to a private file

If you upload the file using file field (core) then you can use views to display the file in a block using block display and use https://www.drupal.org/project/private_files_download_permission for fine grained permissions on who can download the file

if you want to program this behaviour then you have to look at using file_create_url in a custom module

$fid = 1; //set fid to your file's fid.
$downloadlink = file_create_url(file_load($fid)->uri);

and this link will hide the actual path where you private file is

for more details you can look at

How can I get the URL to the public files directory?

https://api.drupal.org/api/drupal/core%21includes%21file.inc/function/file_create_url/8.2.x


How do I add an external JavaScript file using a custom module? I am trying to add an external JavaScript file to my site using hook_preprocess_page().

In Drupal 7, I used drupal_add_js().

function mymodule_preprocess_page(&$vars) {
  $uuid = trim(variable_get('variable_id', ''));
  drupal_add_js('//cdn.cookielaw.org/consent/'.$uuid.'.js', array(
    'type' => 'external',
    'scope' => 'header',
    'group' => JS_THEME,
    'every_page' => TRUE,
    'weight' => -1,
  ));
}

What function/method should I use in Drupal 8?

Firstly drupal_add_js() removed in Drupal 8, check here.

So create library in your module folder as MODULE_NAME.libraries.yml and in this file if you want to add external js add code like below.

external:
  version: 1.0
  header: true
  js:
      https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js: {type: external, minified: true}

and in any of your module/Form/Controller you can call above library using "#attached"

  $build['#attached']['library'][] = 'MODULE_NAME/external';


Commerce: save quantity button removing products I've come across a frustrating issue after adding a cart view block on my page in the form of a "sidebar". When trying to update a quantity or just clicking the "save" button (at bottom of the view) itself will remove the first line item added to the cart. Finally, a message shows on the next page saying: "line item removed."

I have disabled all non essential and potentially problematic modules. There is no custom Javascript / AJAX written for this button. I've checked the error logs and there is nothing wrong there.

Oddly enough, the feature works fine on our live site using a different theme. I have exported the views and ensured they are both exactly the same.

Does anyone have a clue what might be causing this? Or, any debugging steps I could try out?

Note: I'm on Commerce Kickstart 2.x-2.19

The issue is that I had written some javascript to change the value attribute of the "save" input to "update". After changing it back to "save" the button works just fine and nothing is removed from the cart.

To confirm, I went to a different theme and changed the value attribute of the "save" button to "foo" and it started removing line items from the cart.


Overriding theme_item_list() not working I have the following code in the theme template.php file:

function MYTHEME_item_list(&$variables) {
  // my custom stuff done to theme_item_list
  return $output;
}

And also this:

function MYTHEME_theme($existing, $type, $theme, $path) {
  return array(
    'item_list' => array(
      'variables' => array(),
    ),
  );
}

I have cleared cache many times.

Looking at the theme registry I can see that my override is getting picked up:

[item_list] => Array
  (
    [function] => MYTHEME_item_list
    [type] => theme_engine
    [theme path] => profiles/eurostar/themes/eurostar
    [variables] => Array
      (
        [items] => Array
          (
          )
        [title] =>
        [type] => ul
        [attributes] => Array
          (
          )
      )
    [preprocess functions] => Array
      (
      )
    [process functions] => Array
      (
      )
  )

Unfortunately none of this works. Does anyone have an idea of what I'm doing wrong?

UPDATE:
So, this works: theme('item_list', $variables);

This does not: theme_item_list($variables);

You don't need to implement hook_theme() if you just want to override an existing theme function.

I've just tried this code in my template.php file:

function MYTHEME_item_list(&$variables) {
  // my custom stuff done to theme_item_list
  return 'test';
}

And all calls to theme('item_list') now return the string 'test', and nothing else.

You'll need to clear Drupal's caches once you've implemented the function, that might also be an issue.


How to use summary field conditionally for display? I have created a content type Band with a Description field (as Long Text and Summary). When I am viewing the Band page, I want to see the full description field. And when I am viewing a listing of bands, I want to see a summary description or the first hundred characters if the summary description is missing.

How do I show appropriate Description for the Band page and the listing pages?

The Description text field needs to be of type Long text and summary.

With view modes (admin/structure/types/manage/band/display) you can configure how the fields must be rendered.

In the view mode Teaser you could set the format to Summary or trimmed and in other view modes to Default.

When viewing the content type Band as a full page you can render the view mode Default. When rendering a list of Bands with views you can set the view mode to Teaser.


OnClick Event not Captured I was currently developing a module(myid) in Drupal. I made a button(#myid_registrar_button) that must alert whenever it is clicked. Below is my code:

myid.module file:

<?php

    function myid_init() {
        //Jquery Library
        drupal_add_js(drupal_get_path("module", "myid") . "/js/jquery-1.11.2.min.js");

        //Custom Javascript
        drupal_add_js(drupal_get_path("module", "myid") . "/js/myid.js");
    }

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

        $items['admin/settings/myid'] = array(
            'title' => 'myid Settings',
            'description' => 'Configuration options for the myid module',
            'page callback' => 'myid_admin_settings',
            'access callback ' => 'user_access',
            'access arguments' => array('administer site configuration'),
        );
        return $items;
    }

    function myid_admin_settings()
    {
        return drupal_get_form('myid_settings_form');
    }

    function myid_settings_form()
    {
        $form = array();
        $form['myid_registrar_button'] = array(
            '#type' => 'button',
            '#value' => '...',
            '#attributes' => array(
                'id' => 'myid_registrar_button',
            ),
        );
        return $form;
    }

myid.js file

$(function(){
    $('#myid_registrar_button').on('click', function(e) {
        e.preventDefault();
        alert("Eww");
    });
});

Whenever I click a button, it refreshes and doesnt alert something, which is supposedly will not refresh and will alert "Eww". It seems that the onclick event is not captured.The console throws no error. Where am I missing?

You shouldn't be adding JQuery like that.  It's automatically included in core, so you don't need to include it yourself.  To stay up with the latest JQuery version, install the jQuery Update module.

For your JS file, this should work:

(function ($) {
    Drupal.behaviors.myid.registrar_button = {
        attach: function (context, settings) {
            $('#myid_registrar_button').on('click', function(e) {
                e.preventDefault();
                alert("Eww");
            });
        }
    };
})(jQuery);


How do I get the logo path? I am creating custom theme for Drupal 8. I am uploading the logo from theme setting, but I am not able to print the path of that logo. What I am doing to print the full path of logo is using {{ logo }}, but it is not working.

In Drupal 7 we can get the full path of logo with the following code.

 <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" />

What is the equivalent for Drupal 8?

The class implementing the block showing the theme logo, in SystemBrandingBlock::build() contains the following code.

  $build['site_logo'] = array(
    '#theme' => 'image',
    '#uri' => theme_get_setting('logo.url'),
    '#alt' => $this->t('Home'),
    '#access' => $this->configuration['use_site_logo'],
  );

So, for the path of the logo, you can simply use theme_get_setting('logo.url'), which returns "/core/themes/bartik/logo.svg", in my test site.

If you want a relative URL for the logo file, for example because you want to use it for the src attribute of the <img> tag, you can do as template_preprocess_image() does.

$relative_url = file_url_transform_relative(file_create_url(theme_get_setting('logo.url')));

For an absolute URL, you can use the following code.

$absolute_url = file_create_url(theme_get_setting('logo.url'));

That code needs to go in a preprocess function, where it initializes a variable. For example, if I wanted the relative URL of the logo file in html.html.twig, I would use the following code.

function mytheme_preprocess_html(&$variables) {
  $variables['relative_logo_url'] = file_url_transform_relative(file_create_url(theme_get_setting('logo.url')));
}

And in the template, you would just use {{ relative_logo_url }} to get it.


Rule fetches only single taxonomy term from multiselect values I have created a Rule which is supposed to fetch all the selected term from a taxonomy term field (a field that holds a list of taxonomy terms). But when the rule is executed, it fetches only one taxonomy term instead of all. The field is set to hold "unlimited" values.

Rule is:

Entity type = taxonomy term
Condition => content-type = course
Data selector => node:field-autodealer:name

The rule is supposed to add all users from selected groups into a course.

What you included n your question (with "Rule is"), does nto really look like a rule to me, rather something that is part of your rule. However, since you're trying to process a multi value field, a crucial part of a working rule is a Rules Action to perform a Loop. If you're not familiar with such loops, then I strongly recommend to have a look at the tutorial titled "Lists and loops".

In your case, you should (at least) have a Rules Action to create a loop related to your field that holds the list of taxonomy terms. After you do, you should iterate over each item in that list. And for each iteration you should then perform the desired Rules Actions.

Done

PS: Refer to my answer to "How to set multiple values to an unlimited Term Refence field with Rules" for some sample rules that are like a variation of your question here.


How do I extend a configuration form without using hook_form_alter()? I want to extend some fields in a config form of a module with another module in Drupal 8. I created a config form in a module (e.g. custom_1) and now I want to add some more fields from another module (e.g. custom_2). custom_1 has a dependency on custom_2. I tried hook_form_alter() but it didn't resolve the issue.

Is there any other way to achieve this in Drupal 8?

Solution:

I came out to this solution:

I created a custom_1.routing.yml file and write the following code in it.

#Router settings for custom service page
custom_form.service_config:
path: '/admin/config/services/custom'
defaults:
  _form: '\Drupal\custom_1\Form\CustomConfigForm'
  _title: 'Custom Config Form'
  _description: 'Custom Configuration form.'
requirements:
  _permission: 'administer custom'

I created a CustomConfigForm.php file in custom_1/src/Form/CustomConfigForm.php.

    namespace Drupal\custom_1\Form;

    use Drupal\Core\Form\ConfigFormBase;
    use Drupal\Core\Form\FormStateInterface;

    class CustomConfigForm extends ConfigFormBase {
      public funtion getFormId() {
          return 'custom_form_service_config_form';
      }
      public function getEditableConfigNames() {
          return ['custom_form.service_config'];
      }
      public function buildForm(array $form, FormStateInterface $form_state) {
          // Form code here
         return buildform($form, $form_state);
      }
      public function submitForm(array &$form, FormStateInterface $form_state) {
         // Submit code here
      }
    }

Now, I have to merge some more form fields from another module custom_2. To achieve this, I followed the following steps.
I created a custom_2.routing.yml file and write the following code in it.

#Router settings for custom service page
custom_form.service_config:
path: '/admin/config/services/custom'
defaults:
  _form: '\Drupal\custom_2\Form\CustomTwoConfigForm'
  _title: 'Custom Config Form'
  _description: 'Custom Configuration form.'
requirements:
  _permission: 'administer custom'

I created a CustomTwoConfigForm.php file in custom_2/src/Form/CustomTwoConfigForm.php.

    namespace Drupal\custom_2\Form;

    use Drupal\Core\Form\FormStateInterface;
    use Drupal\custom_1\Form\CustomConfigForm;

    class CustomTwoConfigForm extends CustomConfigForm  {
      public funtion getFormId(){
          return 'custom_form_service_config_form';
      }
      public function getEditableConfigNames(){
          return ['custom_form.service_config'];
      }
      public function buildForm(array $form, FormStateInterface $form_state) {
           $form = parent::buildform($form, $form_state);
          // Form code here
         return parent::buildform($form, $form_state);
      }
      public function submitForm(array &$form, FormStateInterface $form_state) {
         // Submit code here
      }
    }

This resolve the issue for me without using hook_form_alter().

Thanks


Views Aggregation Problems I'm trying to work with aggregation in Views and I just can not seem to understand how to get it to do what it is supposed to be doing. First off, a simple example. I create a view with "Show" set to a parent table. (a list of accounts in this case). Next I add a relationship to a child table (a list of account entries). I add one field, the account name.

Finally I turn on aggregation and set the account name to "group by". The SQL statement it provides has no group by clause! The View says it is:

SELECT ledger_account.name AS ledger_account_name
FROM
{ledger_account} ledger_account
INNER JOIN {ledger_account_entry} ledger_account_entry_ledger_account
    ON ledger_account.aid = ledger_account_entry_ledger_account.aid

Where I would have expected

SELECT ledger_account.name AS ledger_account_name
FROM
{ledger_account} ledger_account
INNER JOIN {ledger_account_entry} ledger_account_entry_ledger_account
    ON ledger_account.aid = ledger_account_entry_ledger_account.aid
GROUP BY ledger_account_name

I know this is a simple example, but it's a piece to a larger summation with a few joins. However, if views isn't smart enough to do this correctly, or if I just fail to understand how to do this properly, my query will never work.

For a short tutorial about the "aggregation" features of the Views module, refer to Using aggregation in Views. As an alternative, have a look at the (free) set of 30 video tutorials about the Views module. Specific to "Aggregation", you may want to look at these episodes (quotes are from the linked pages):

The aggregation setting.

  ... makes Views return not one row per item in the database, but one row per aggregation group. Perhaps more importantly, it also makes it possible to count the number of items baked into each row, or sum them up, or calculate their average, or count the number of unique items, or…

Aggregation and relationships.

  ... shows how to use the aggregation setting in Views in combination with relationships.

Aggregation edge cases.

  ... shows some of the more rare use cases of aggregations in Views:

  Using aggregation on filtering
  Using aggregation on sorting
  Using aggregation on contextual filters (which is currently broken)
  NOT aggregation on relationships (since aggregation doesn't apply to this handler)
  Using aggregation on multiple-value fields


What are the limitations of the theming system? Can every theme function in include/theme.inc be overridden by a template (*.tpl) file?
Can preprocess functions be used to add variables to any theme function?

Theming hooks (templates and theme functions) defined in hook_theme() implementations are always overridable. But they have to be used properly, always use theme('foo', $bar), never theme_foo($bar).

In Drupal 6, (pre)process functions are only available for templates, not theme functions. Also, the templates must be be overriden in the theme otherwise the preprocess function from the theme is not used. So to have your THEME_preprocess_node(&$variables) function used, you need to have the node.tpl.php in your theme folder.

Another limitation (actually a bug) is that for a template to be overridable in a theme, the file name (without the .tpl.php extension) must be exactly the same as the theming hook name except for the _ that are replaced by -:

function MODULE_theme() {
  return array(
    'overridable_template' => array(
      'template' => 'overridable-template',
    ),
    'non_overridable_template' => array(
      'template' => 'nonoverridable-template',
    )
  );
}