How can I create a link, within a form, for a user to download a file? I'm new to Drupal.

I have a custom form, within a custom module, using Drupal 8.

I would like to provide a simple link (or button, whatever the correct terminology would be), that when a user clicks will download a file that I specify.

How do I create the clickable part in the first place? Is there something like '#type' => 'download', similar to the way '#type' => 'managed_file' is used for uploads? Or is using the 'type' => '#submit' route the best way to go?
Where do I place the file, and how do I make the clickable part grab that file?

The file will be a .xlsx in my case, but I've seen similar questions asking how to do this for a .pdf file, .doc file, etc., but none of them have a concrete answer.

I don't care what the user does with the file once they've downloaded it. It doesn't need to be protected or "read-only" or anything fancy. I just want someone to be able to download the file and save it to their computer.

Code examples would be extremely helpful. So far my best guess is something like this:

// Taxonomy Download
    $form['taxonomy_download'] = [
      '#type' => 'submit',
      '#value' => t('Download Default Taxonomy Terms'),
      '#submit' => array('::downloadFile'),
    ];

(...)

public function downloadFile() {
     //Get file from /file/path/
     //return $file
}

Okay, so I found a solution that works pretty well, though I'm sure there are better ways to do this.

I resolved on the submit button approach, as it seems all buttons in Drupal 8 turn into submit buttons anyway. Here's the code for the button itself.

$form['taxonomy_download'] = [
      '#type' => 'submit',
      '#value' => t('Download Default Taxonomy Terms'),
      '#limit_validation_errors' => array(),  //don't run form validation when this button is pressed
      '#submit' => array('::downloadFile'),  //call this function when the button is pressed
];

Then, for the downloadFile function:

public function downloadFile(array &$form, FormStateInterface $form_state) {

    // Creates a string of the file location. SERVER_NAME returns the
    // name of the host site, e.g. 'www.example.com' or '50.0.0.1'
    $buildUrl = 'http://' . $_SERVER['SERVER_NAME'] . '/sites/default/files/Example.xlsx';

    //drupal_set_message($buildUrl);    //uncomment this line to see what is getting passed

    $url = Url::fromUri($buildUrl);     //Creates a url from the file location

    $form_state->setRedirectUrl($url);  //Redirects the user to the file location
}

You will need to place the file that you're trying to download into the public files folder, found in your Drupal installation's sites/default/files/ folder. You can test that you have the file in the correct location by typing the full path (e.g. http://www.yoursite.com/drupal/sites/default/files/ExampleFile.ext) into your browser's address bar. The file should download when you go to that address.

Finally, you will need to include use Drupal\Core\Url; at the top of your code to make the fromUri() and setRedirectUrl() functions work.


How to restrict access to some nodes based on roles or users? I am using Drupal 8 and I am a little bit confused that there is no core functionality to restrict the access to some nodes based on roles or users.

I found PageAccess, which is marked as unsecure and ACL/Access Control which are both dev and not working on my system.

Isn't there any option to do so? I need the private sector on my site and can't believe there is no way in Drupal.

Hope you can help me, because if not I have to redo the whole site with another wcms.

The Group module is what you should be looking at.

It creates groups as entities, making them fully fieldable, extensible and exportable. For this specific question, you'd enable the gnode submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types.

For the private sector (as in your question), it seems that you would want to grant access to what, in Group, is called "Members". But you wouldn't allow access to that part of the website for:

"Outsiders" (=  logged in users who are not a member of a group).
"Anonymous" (site visitors that are not logged it).

More info

Refer to "What are the various roles supported by the Group module?" for more details about the supported roles.
Refer to my answer to "How to configure access to courses for teachers and students?" for a sample configuration.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


How to modify Drupal 8 Views "Rewrite..." field values later in code? In a Drupal 8.3 View, I am displaying fields. One of these fields is configured to "rewrite results" so as to "output this field as a custom link" with a custom link path.

I would like to modify these links in code (based on some later logic). However, I cannot find a place to actually modify this value in code. If someone knows how to accomplish this, please let me know. (This was much easier in D7.)

Here's what I've tried thus far.

theme_preprocess_views_view(): I found ...['#view'] -> field['name'] -> options['alter']['path'] in Drupal 8's endless arrays, but changing this value did not affect the output. I could not find my custom link anywhere else in this endless array.
hook_views_post_render(): This supposedly allows one to alter the output string, but doesn't actually give the output as a string (broken documentation).
I can see the output string in a twig template, but cannot easily substitute my link given that PHP doesn't run in twig. This would be a less desirable option in any case.

After more time and effort poking around, I found one possible solution, but perhaps not the best or most efficient.

What didn't work:

My original approach of changing the field path links in theme_preprocess_views_view() didn't work because this function is too late in the page build. ("Preprocess" is apparently contextual to the target function. In this case it comes before the final View, not the View's fields.)

I also tried using template_preprocess_views_view(), which was called before other View preprocess functions. While I was able to change the View rewrite values (e.g., $view -> field['name'] -> options['alter']['path'] = 'my new path'), this changed the links for all the fields, not allowing each field to be individually customized.

I was able to change the Views rewrite path value inside hook_preprocess_views_view_field(&$variables), but this affected the following field in the results array, not the current field.

My Solution:

I ended up using hook_preprocess_views_view_field(&$variables), and rendering my own custom links and saving them to $variables['output'].

$variables['view'] and $variables['row'] were available for finding data for the logic, as well as additional objects depending on what the View is displaying.

I also used template_preprocess_views_view() to re-organize all the Views rows before they were rendered in the twig template, but as mentioned before, I couldn't change the content of the rows inside this function because they were already rendered before this function was called.

I hope this saves time for someone. Feel free to post more eloquent solutions.


db_select subquery "In" condition causes PDOexception This source should get the 4 most popular top level categories.

The result query works fine when run in phpmyadmin so I must assume the problem is in db_select somewhere.

The resulting query should be: SELECT tid FROM taxonomy_index,name WHERE tid IN(SELECT data.tid FROM taxonomy_term_data AS data JOIN taxonomy_term_hierarchy AS hierarchy ON data.tid=hierarchy.tid WHERE vid=2 AND parent=0) ORDER BY COUNT(nid) ASC LIMIT 0,4

<?php
$vocab = 2;

$subquery = db_select('taxonomy_term_data','data')
  ->fields('data',array('tid'));
$subquery
  ->join('taxonomy_term_hierarchy', 'hierarchy', 'data.tid=hierarchy.tid');
$subquery = $subquery
  ->condition('data.vid',$vocab)      // vid of vocab we want to show
  ->condition('hierarchy.parent',0);  // tid of parent (We want toplevel terms)

$toplvlcats = db_select('taxonomy_index','index');
$toplvlcats
  ->join('taxonomy_term_data','data','index.tid=data.tid');
$toplvlcats = $toplvlcats
  ->fields('index',array('nid'))
  ->fields('data',array('name'))
  ->condition('index.tid',$subquery,'IN') // Sift through toplevel terms
  ->orderBy('COUNT(nid)','ASC')           // For the one with the most posts
  ->range(0,4)
  ->execute();
?>

The error message is:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'index INNER JOIN taxonomy_term_data data ON index.tid=data.tid WHERE (index.tid' at line 1: SELECT index.nid AS nid, data.name AS name FROM {taxonomy_index} index INNER JOIN {taxonomy_term_data} data ON index.tid=data.tid WHERE (index.tid IN (SELECT data.tid AS tid FROM {taxonomy_term_data} data INNER JOIN {taxonomy_term_hierarchy} hierarchy ON data.tid=hierarchy.tid WHERE (data.vid = :db_condition_placeholder_0) AND (hierarchy.parent = :db_condition_placeholder_1) )) ORDER BY COUNT(nid) ASC LIMIT 4 OFFSET 0; Array ( [:db_condition_placeholder_0] => 2 [:db_condition_placeholder_1] => 0 ) in eval() (regel 25 van /home/j/www/modules/php/php.module(80) : eval()'d code).

The only problem with your query is that you're using index as a table alias...this is a MySQL reserved word and although my instinct is that PDO should escape this, perhaps it doesn't.

The following code (with the aliases renamed) runs without error:

$vocab = 2;

$subquery = db_select('taxonomy_term_data','ttd')
  ->fields('ttd',array('tid'));
$subquery
  ->join('taxonomy_term_hierarchy', 'th', 'ttd.tid=th.tid');
$subquery = $subquery
  ->condition('ttd.vid',$vocab)      // vid of vocab we want to show
  ->condition('th.parent',0);  // tid of parent (We want toplevel terms)

$toplvlcats = db_select('taxonomy_index','ti');
$toplvlcats
  ->join('taxonomy_term_data','ttd','ti.tid=ttd.tid');
$toplvlcats = $toplvlcats
  ->fields('ti',array('nid'))
  ->fields('ttd',array('name'))
  ->condition('ti.tid',$subquery,'IN') // Sift through toplevel terms
  ->orderBy('COUNT(nid)','ASC')           // For the one with the most posts
  ->range(0,4)
  ->execute();


Get term value from user field and set that value to new field How to get term from user field and set that to the field in node?
When user is creating node I need to get term and set it to the node field.

I have field_term_reference in user fields and in node I have field_book_reference field. I need to get term from field_term_reference and set that term to the field_book_reference.

Both fields has autocomplete widget.

Here is my current non-working code:

function set_value_node_presave($node) {
global $user;
$user = user_load($user->uid);
$term = field_get_items($user, $account, 'field_term_reference');

$node->field_book_reference[$node->language][0]['value'] = $node->$term;

}

SOLVED Here is working code:

function set_value_node_presave($node) {
global $user;
$user = user_load($user->uid);
// Get field from user
$term = field_get_items('user', $user, 'field_term_reference');

$node->field_book_reference[$node->language][0]['tid'] = $term[0]['tid'];

}

$node->$term definitely isn't what you want. Taxonomy references are stored by tid, so

$node->field_book_reference[$node->language][0]['tid'] = $term[0]['tid'];

should work


How can I theme a form "checkboxes" element? I've got a checkboxes field displayed on the user profile form. I'm trying to restyle that field to put the description BEFORE the checkboxes. That seems like it should be a simple thing?

So far I've got:

function MYTHEME_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
    $form['my_field_id'][LANGUAGE_NONE]['#theme'] = 'checkboxes_description_before_element';
}

function MYTHEME_theme($existing, $type, $theme, $path) {
    return array(
        'checkboxes_description_before_element' => array(
            'render element' => 'element',
            'function' => 'theme_checkboxes_description_before_element'
        ),
    );
}

function MYTHEME_checkboxes_description_before_element($variables) {
    return "XYZ";
}

The checkboxes field is still stubbornly sitting on the markup generated by theme_checkboxes instead of "XYZ".

I know that the form element is getting the new '#theme' through checking with dpm().

The checkboxes description is not rendered in theme_checkboxes or theme_checkbox. It comes from theme_form_element.

If you want every form element on the site (not just checkboxes) to have the description first, then you could just override and modify theme_form_element.
If you want only specific checkboxes to have this, then you could override and modify theme_form_element to position the description based on a variable (similar to what it already does with #title_display). You could then set the variable when creating the FAPI array.
If you want all checkboxes (but only checkboxes) to follow this behaviour, then you could override theme_form_element as above, and use hook_element_info_alter() and change checkboxes to have the new variable you created appopriately set.

Let me know if you have any questions.


Can two drupal distributions co exist? I am working on a drupal site and One of the functionality of my site is to have an ideation platform. Can I make a distribution work seamlessly within my drupal instance ?

Seamlessly, probably not. However, what may work is to merge your own Drupal site's install profile with the code found in idea.install. Additionally, you'll want to enable all of the modules found here.


What is the best way to retrieve the current menu object, regardless of it's type? When you call menu_get_object(), the first argument defaults to 'node' if no arguments are passed to the function. The code uses the $type variable to check if the current object is of that type, using $router_item['load_functions'][$position] == $type . '_load'.

Sometimes, I just want to get the current menu object, regardless of it's type. In other words, when I'm looking at user/123, I want the user object, and when I'm viewing node/456, I want the node object.

Why does menu_get_object force a single entity type?

What is the best way to retrieve the current menu object, regardless of it's type?

As you can see in that function, it does nothing more than:

$router_item = menu_get_item($path);
return $router_item['map'][$position];

However, I'm not sure how that will help you, for pretty much all objects, you need to know what it is to work with it as there are just some attributes.


Will changing the value of $drupal_hash_salt in settings.php file break site I was looking through a list of steps to take when there is a risk that your site has been hacked.  It recommends changing the value of $drupal_hash_salt in settings.php.

According to the inline comments in settings.php:

  Salt for one-time login links and cancel links, form tokens, etc.

  This variable will be set to a random value by the installer. All one-time
  login links will be invalidated if the value is changed. Note that if your
  site is deployed on a cluster of web servers, you must ensure that this
  variable has the same value on each server. If this variable is empty, a hash
  of the serialized database credentials will be used as a fallback salt.

Can I simply replace the existing value with random string?  I am worried that changing this string may adversely effect some other aspect of site functionality.

Disruption should be minimal -- the salt value was designed to be changeable. As it says, it will invalidate one-time login links when the salt is changed. But if you suspect that you've been hacked, this is precisely what you want to happen.


Module development - Layout of dynamic content I am creating a drupal module that receives content from a Web Based XML API. The module takes some search parameters from a  user and embeds these into a XML command. I am at the point where I am receiving back a response and am able to process the returned data and display it on the page using a simple return statement. At the moment I am simply returning a html table that is created in the module.

What I would like to do is make content available to other Drupal modules such as Views or Display Suite. But as this data is not coming from the database but being created on the fly I am not sure where to start. Any help would be much appreciated.

Thanks
Simon

Some pointers:

Try getting the data in your database somehow. You could import the data into nodes or you could use the Entity API. That way, you could expose your data to modules such as Views. The only thing you'll need to do left is to synchronize the data in your database with the XML data that you're receiving.


How to give users access to the header or footer text in a view? I have a view with a "global text" header that changes once a month. It's not easy in Drupal to give users access to only certain fields in a view. And I wouldn't want to "scare" them with the views UI either ;-)

One option is to create a new Views "attachment" display, and give it different permissions than the other view.


How do I redirect users and show a message? I want to redirect users with RedirectResponse and display a message, but the message is not displayed.

$response = new RedirectResponse($url);
$response->send();

After little debugging I found that my initial (source) URL is loaded twice, and the messages (added with drupal_set_message()) are removed from the session in drupal_get_messages(). So I have no messages on my target $url.

How can I achieve this?

I'm doing it in hook_field_widget_form_alter().

Set the repeat parameter in drupal_set_message() to TRUE and it will work:

$response = new RedirectResponse($url);
$response->send();
drupal_set_message(t('My message after redirect'), 'status', TRUE);


Drupal webform with sortable report I want the webform submitted report to be sortable (or filtered), suppose there is the "Country" field in the form with selectlist of Countries,

I must be able to filter the reports with specific value,suppose "USA" or something else.

Thank you.

You could use Views to render a table view of fields (for Country, etc) and set the content filter of that view to pull only submitted webforms.


How to update path alias using MySQL command line Many words have been renamed in the node using the below code:

update node set title = replace(title,'Apple','Orange')
update node_revisions set title = replace(title,'Apple','Orange');

But now I need to know how to update the path aliases using the MySQL command line; using the Drupal administration interface is very tiring, for thousands nodes.

I don't think you will have much success using mysql, the quickest way is likely to write a script that bootstraps drupal, loads each node and then saves the node, I think this should update the aliases.


Rules - anonymous users redirected to user/login prevents request new password link from working I'm using the rules module with drupal 7 in order to redirect anonymous users to the login page.

Events: Drupal is initializing
Conditions: User has role(s) - Parameter: User: [site:current-user], Roles: anonymous user
NOT Text comparison - Parameter: Text: [site:current-page:url], Matching text: user/login
Actions: Page redirect - Parameter: URL: user/login

My problem is I need the "request new password" to work. How do I tell Rules to ignore clicks to user/password?

This is the current setup for the Actions but it doesnt work.

When a user gets to the login page I want them to be able to click Request New Password and not be redirected back to user/login.

Try adding a condition to your redirection rule like this :

Path has url alias
Value : user/password
Negate : True

Edit :

It must be something like this :


After upgrading, the autoloader is not working Recently, I updated from 8.1.8 to 8.1.10 (via composer update). In my local environment (running scotchbox, PHP 5.6.14), it runs fine. When deployed to the staging server (running CentOS 6.7, PHP 5.5.17), the site returns a 500 and writes the following to error_log:

  PHP Fatal error:  Class 'Drupal\Core\Site\Settings' not found in /home/[site]/public_html/drupal/core/lib/Drupal/Core/DrupalKernel.php on line 964

I copied basically everything except the /sites/ directory, so I don't think I'm missing anything.

I tried restarting httpd to no avail.

It seems like a problem with the autoloader and possibly due to the PHP version mismatch. There are many layers between autoload.php and the DrupalKernel.php bootstrap process. I'm at a loss as to what's going on here. Any help would be appreciated.

It sounds like the changes that composer made to your local environment weren't carried over. Without knowing any of the details of what might be different, you'll have to do some introspection. You can test the autoloader in both your dev/staging environment to tease out what's occurring differently in each environment.

There a few things you can do to test the autoloader:

Within index.php you can use the statement var_dump($autoloader) to dump the autoloader; it should have a classMap property which should have a keyed array that maps classes to PHP files. It should include a value for Drupal\Core\Site\Settings.
Within vendor/composer/autoload_real.php is the logic that registers the autoloader and includes other autoload_*.php used to build the autoloader object. You can various var_dump() statements to follow the path of execution to make sure the autoloader is being built correctly.
Within vendor/composer/ClassLoader.php you use the var_dump($class) statement in the ClassLoader::loadClass($class) method to have PHP spit out classes as the autoloader is including them.


How to add query parameters to a CacheableJsonResponse's cache? I have an API which returns various json, like terms of a vocab, nodes of a type, with specific fields and so on.

Now, in my API I am getting the requested language like so:

$request = \Drupal::request();
$lang = $request->query->get('lang', 'en');

And load the respective translations of the entities.

Now, how can I add that $lang parameter as a cache indicator? So that:

/myapi/nodes?lang=en

creates another cache than:

/myapi/nodes?lang=klingon

Also, is that the right way to deliver language specific content in an API?

Add a cache context for the query parameter to the response:

$cache_metadata = (new CacheableMetadata())->addCacheContexts(['url.query_args:lang']);
$response->addCacheableDependency($cache_metadata);

About the second question, when this issue is resolved you can use core REST to deliver translated entities: https://www.drupal.org/node/2135829


Moving SQLite-D7 Installation to other Server throws Uncaught exception in shutdown function When I move my Drupal7-Website (with SQLite Database) from my XAMP to another Computer also running XAMP I got the following error message.

  Uncaught exception thrown in shutdown function.

  PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a
  readonly database: DELETE FROM {semaphore} WHERE (value =
  :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0]
  => 192200923514edf6a15a484.46864520 ) in lock_release_all() (line 269 of
  /Applications/XAMPP/xamppfiles/htdocs/myd7site/includes/lock.inc).

How comes? And how to fix?
Thnx!

It seems that the PDO SQLite driver requires that if you are going to do a write operation (INSERT,UPDATE,DELETE,DROP, etc), then the folder the database resides in must have write permissions, as well as the actual database file.

The above information is taken from another answer: https://stackoverflow.com/a/3330616/2171489

I don't use SQLite, but given the error from the PDO driver and the fact that you moved to a different server, it does seem like it could be a file permission problem.


entire teaser as link to node I would like to use the whole tease as a link to the node. I could google (and adapted) the following code but still not working.

following line:
scripts[] = js/new_teaser.js is added in the ".info" file of my theme (Business)
and this code to the "new_teaser.js":

$(document).ready(function(){

    $(".node-teaser").click(function(){
      window.location=$(this).find("a").attr("href"); return false;
    });

    });

the class of my teaser is ".node-teaser" and the "NoScript" addin of my browser is switched off. I assumes that the problem is in the JS code.

Drupal 7, theme Business

Could someone help me please?

EDIT: as far as I can see, there is no link to the new_teaser.js file in the source code of the page... (even if the file is in the js/ folder and in the theme .info file

Something like this should work. Add it to your template.php file. Using preprocess_node gives you a little more control so you aren't just arbitrarily loading the script on every page.

function THEMENAME_preprocess_node(&$variables) {
  if ($variables['type'] == 'blog' && $variables['view_mode'] == 'teaser') {
    drupal_add_js($theme_path.'/js/new_teaser.js');
  }
}


Views3 date field (filter) treated as string I am used to getting int operators(like less then) in views when using date api fields but now I'm getting string operators so I can't filter on dates(like now).
When creating a filter on 'post date' for ex. it works just as usual.
It actually just looks like when you turn off date views.

It's a drupal 7 installation with views3 and the latest date api.

I don't know what went wrong or this is a bug but I can't seem to fix it.

In the Date project there is submodule called "Date Views". Enable this and the operators you're looking for will appear.


Customise Views PDF export I am using Views PDF to export some of my pages as PDF files. So far I can get it to export the files .
I am however getting challenges in trying to adjust the styling. I have looked at the module for any tpl files and they are not there. Anybody with a headstart on this?

In the pdf view under "PDF SETTINGS" you can add a css file for styling. Note that it only supports basic css.


How to refresh/update a Block or View after a form submit? I have a View of created entities displayed as a block. On the same page I have a form with which new entities can be created, and this form submits through AJAX because I do not want a page reload after submission. The issue of coarse though is that after submission, the View on the same page is not updated which makes it look like that the submit has done nothing. I could set a Rule to reload the page after submission, but I would like the View to update without reload.

What I have tried (Drupal 7)

I have experimented with the Views Auto-Refresh module, but constantly refreshing a View seems a bit of overkill since for performance reasons it would be better to only have this triggered on a form submit. The module Views Flag Refresh does exactly what I need but because it is a Flag and not a form element I am not sure how I could use a flag to submit the contents of a form. The following module does exactly what I need and refreshes a View after a form submit, but there is only a D6 version (Ajax Views Refresh) with no plans for a D7 port. The final possibility I have considered is Node.js integration (Views Node.js), but this seems hugely complex for such a small feature and I am not that confident in my ability to pull this off.

So at this point I'm not quite sure in which direction to go. How could I do a refresh after a form submit?

I think this might be the module you are looking for:-
https://www.drupal.org/project/views_nodejs

I has a few dependencies, and you will need to setup a node.js server, but aside from that it's pretty straightforward.


Render alternative content if user is logged in instead of redirecting to user/uid I have a menu router with type MENU_CALLBACK and it's 'page callback' property points to a function that implements render API, as follow:

 /** Implements hook_menu **/
function custom_render_menu() {
  $items['register-profile'] = array(
    'page callback' => 'custom_render_register_profile',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/** Implements callback page for register-profile **/
function custom_render_register_profile() {
  $user_register_form = drupal_get_form('user_registration_form');
  $markup = user_is_logged_in() ? t("Alternative Content") : drupal_render($user_register_form);
  $output = array( '#markup' => $markup);
  return $output;
}

If the user is not logged in, the registration form displays correctly, but if the user is logged in, the page was redirected to user/uid router, showing user's profile. How can I display an alternative content instead of redirecting the user to their user page?

function custom_render_register_profile() {
global $user;
global $base_url;
$uid=$user->uid;
if($uid)
{
drupal_goto('url where you want to take login user..like $base_url./node/1');
}
else
{
  $user_register_form = drupal_get_form('user_registration_form');
  $markup =drupal_render($user_register_form);
  $output = array( '#markup' => $markup);
  return $output;
}
}


Can a module provide a default block with editable content? (editable through the standard block interface) I have multiple blocks I'd like to include in a module/install profile; (containing markup) but need to be editable through the standard block UI? What's the best way to implement this?

Drupal adds custom blocks in a form submit function using database queries directly, it doesn't expose an API for that particular function unfortunately, so you'll have to write/copy the code manually.

You can find all the code you need in block_add_block_form_submit().

You insert the custom block into the database like so:

$delta = db_insert('block_custom')
  ->fields(array(
    'body' => '
Some markup
',
    'info' => 'Block description',
    'format' => 'full_html',
  ))
  ->execute();

Then you need to make this block available to all installed themes:

$query = db_insert('block')->fields(array('visibility', 'pages', 'custom', 'title', 'module', 'theme', 'status', 'weight', 'delta', 'cache'));
foreach (list_themes() as $key => $theme) {
  if ($theme->status) {
    $query->values(array(
      'visibility' => 1, // visible
      'pages' => '', // list of pages
      'custom' => 1, // This is a custom block
      'title' => 'Block title',
      'module' => 'block', // The block module handles custom modules
      'theme' => $theme->name,
      'status' => 0,
      'weight' => 0,
      'delta' => $delta,
      'cache' => DRUPAL_NO_CACHE,
    ));
  }
}
$query->execute();

You'll want to put that code either in hook_install()/hook_enable() if you plan to do this in a custom module, or hook_install() if you're doing it in an install profile.


Different "Asc" and "Desc" labels for different Views exposed sort fields I have a view of Commerce products that, as is standard for e-commerce product listings, can be sorted by price or by date. I'm having trouble with the sort direction labels:

In the context of dates, "Ascending" or "Descending" is confusing unless you are used to thinking about time in terms of UNIX timestamps. Labels like "Newest" and "Oldest" are much more user-friendly to average users.
In the context of prices, labels like "Highest" and "Lowest" are most user-friendly.

"Newest"/"Oldest" is clearly nonsense in the context of price, while both "Ascending/Descending" and "Highest"/"Lowest" are confusing to average users in the context of dates. I need both highest and lowest options for the prices sort because it's a luxury goods store and some users want to browse the most premium options.

The trouble is, even with Better Exposed Filters module, I can only have one custom ascending or descending label.

Ideally, I'd like something like this:

  Sort by

  Date - Newest
  Date - Oldest
  Price - Highest
  Price - Lowest

...but I'd also accept something that switches the labels in the sort order based on the selection in sort type.

I could roll my own javascript, but surely I can't be the first person to have this use case. Is there an existing solution?

There's a feature for this in using the Better Exposed Filters module through certain combinations of BEF settings:

Set "Display exposed sort options as" to anything except Toggle links, which seems to give strange results
Under "Advanced sort options", tick "Combine sort order with sort by"
Save, and see what strings it outputs by default for the labels. For example:

  Price Highest
  Price Lowest
  Date listed Highest
  Date listed Lowest

Copy these into the "Rewrite the text displayed" field, then for each one put a | then the intended label, for example:

.

Price Highest|Price - Highest
Price Lowest|Price - Lowest
Date listed Highest|Date - Newest
Date listed Lowest|Date - Oldest

It then outputs as intended

  Price - Highest
  Price - Lowest
  Date - Newest
  Date - Oldest


Making a custom theme and want to know how to style first post different from the rest After months of figuring out how to upload a background image, I decided to scrap that and use a solid color with the color picker.

Now I moving on making a custom theme and it's very different from making a WordPress theme. So I need help with the following:

On my page.tpl.php, is there a way to have the first post different from the rest of the posts? Example: First post has a title, date, time and a description. The rest just have a date and title.

Also I don't want to use view module as it looks complicated to setup and I want to use as little of modules as possible.

All help is greatly appreciated and thanks for understanding my annoying questions for help,
Gregory S.

UPDATE: Looks like I'll have to do views after all.

What you can do is:

Create a custom page using hook_menu.
Use Drupal's Database (DBTNG) to get your list of contents. You can do two separate queries for this. The first one would just return one result with more fields than the second. Also you could add the Drupal's pager functionality right out of the box here since you will be using db_select.
Use hook_theme to create the template for your "node teaser" so that it makes your raw data manipulation separate from your presentation hence the need for a custom template.

Your main code would somewhat look like:

function YOURMODULE_page_view() {
  $special_node = db_select(...);
  $nodes = db_select(...);
  $output = array();

  // do stuff here for $special_node_fields
  $output[] = theme('custom_node_theme', $special_node_fields);

  // look through all remaining nodes
  while($nodes) {
    // do stuff here for $node_fields
    $output[] = theme('custom_node_theme', $node_fields);
  }

  return $output;
}

This gives you better view on the data manipulation you need to get the list you need.

Also don't forget to replace the Default front page value with your custom page in the Site Configuration page.


Is there a way to restrict access to a particular node? One of my teammates created a simple page that displays links to important contents. However, since it is simple content, the page itself is restricted but the link still shows up in the main menu.

I'm looking for a way to add a permission such as custom_module.permission.yml where the client will be able to define who can access this page.

Is there a way to do so without installing any external module?

You can use this module Permissions by Term

Frontend Features

Restricts users from accessing the nodes related to specific taxonomy terms by their roles and/or specific user accounts.

Restricts users from access to forbidden nodes in views.

Tag the node to the specific taxonomy term and restrict access to nodes tagged with that specific node.


How can I return actual JSON using Drupal? I'd like to implement a simple AJAX function locally that allows me to autocomplete node titles of already existing nodes as the user types. To that end, I need the ability to have an API that I can search on node titles. The problem is that when I output raw JSON, it comes surrounded by tags. So, no matter what I do, I keep getting...

 {json here}

I've tried implementing a custom page template that only outputs content already, that produced the same results. Here is how I am currently doing this, in my module file...

<?php

/**
 * Implementation of hook_menu()
 */
function content_relation_menu() {
    $items = array();
    $items['api'] = array(
        'title' => 'Search',
        'page callback' => 'content_relation_get',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );

    return $items;
}

function content_relation_get($term = '') {
    drupal_add_http_header('Content-Type', 'application/javascript; utf-8');
    $var = json_encode(
        db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" => $term.'%'))->fetchAll()
    );
    echo $var;
    exit(0);
}

How can I return JUST raw JSON?

For Drupal 6, you can use drupal_json

function content_relation_get($term = '') {
    $result = db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" => $term.'%'))->fetchAll()
    );
    drupal_json($result);
    exit;
}

For Drupal 7, change it to use drupal_json_output

function content_relation_get($term = '') {
    $result = db_query("SELECT nid,title FROM {node} WHERE title LIKE :title LIMIT 5", array(":title" => $term.'%'))->fetchAll()
    );
    drupal_json_output($result);
    drupal_exit();
}

It would also probably be safer to parse out the query to sanitize, error check, etc, instead of just trying to return the result.


Change account settings in db All sites on our server is currently getting spam users registering for new accounts.

Since none of the sites needs the option available for user to sign up, we would like to change the account setting "Who can register accounts?" being "Administrators only" for all sites.

The issue is we have around 800 sites, and i would rather not do this manually for all sites.

Is it possible to change this setting directly through the database?

Like one sql command that update alle databases and set the setting to being "Administrators only"?

You want to modify a user_register variable and set it to 0.
You can set it in code:

variable_set('user_register', USER_REGISTER_ADMINISTRATORS_ONLY);

by drush:

drush vset user_register 0

or directly in database (note that in variable table are stored serialized values):

UPDATE variable SET value = 's:1:"0";' WHERE name = 'user_register';

but this requires cleaning cache.

DELETE FROM cache_bootstrap WHERE cid = 'variables';


How to detect if form-building function is called for the first time? In my form building function I need to render some things basing on user's actions. But if the form building function is called for the very first time I want to put a form deliberately in slightly inconsistent state (I have my reasons, long story).

How can I reliably detect if the form building function was called for the first time, or if the form was already presented to the user and now it's built due to AJAX call or to allow user to fix input errors?

Currently I'm using empty($form_state['input']) but I have this feeling there is a better, more reliable way and I forgot it.

You can add our own value to $form_state in a hook_form_alter().  If it doesn't already exist (eg., !isset($form_state['my_var'])), then you know it is the first build.


Content Type Layout for Users I have a content type with fields that I want to customize for my clients to look more professional that it does in the current layout. Is this possible?

You could use Display Suite to create custom layouts of your forms and content displays.

  Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!

A combination of Display Suite and css will allow you to really tweak the standard layout of your theme.

Otherwise Panels is another module that allows you to customize the layout, among many other features.


How do I render sub-menus? I have a Drupal 7 installation that, for the purposes of this question, has just the core modules.

Using the Structure->Menus->Main Menu form, I added some items to the menu and, using a Mytheme_links__system_main_menu($main_menu) in the template file, dumped the menu items using print_r, just to check what is being passed through.

So far so good.

Now, in the Structure->Menus->Main Menu form, I add some child items beneath one of the top level items by dragging these items to the right one space under the parent. Then I clicked "Show as expanded" on the parent item and saved the configuration.

When I dump the $main_menu variable again, only the parent items are shown. The child items are never shown.

Can anyone help me understand how to ensure that the child items are rendered to the $main_menu array?

I don't really want to add pre-themed menu modules as there is a very simple but very specific layout that I need to achieve. Can the default Drupal menu module handle sub-menu items?

It may be caused by the "Show as expanded" unchecked checkbox by default on your menu items edition page. Check 'admin/structure/menu/item/{mid}/edit'

By the way, devel's module dpm(object) function is the Drupal way of print_r / var_dump inspecting things.


Using two arguments in a panels page? Here's what I want to do, for context:

I want to go to mysite.com/groups/%gid/%nid and see the node specified by %nid with an OG menu and a header pane that get their context based on the %gid. So if I have, say, a "person" nodetype, I can show a person node that belongs to multiple groups with the header and menu of different groups based on the URL. This is useful because then I can change the links that I use in each group's "people" list to keep the header and menu the same after the user clicks on the person.

I am not able to get the two arguments to work together, though.

I have been able to create a Views pane that displays the node by taking nid as a contextual filter, and gets it from the URL via panels. However, when I try to add the %gid first, I get all lost. I can't figure out how to use it to tell OG Menu which menu I want, I don't know how to use it to pass the appropriate context to the header minipanel that I've created (that works when a valid context is passed in), and I get "page not found" instead of a person node.

What am I doing wrong? How do I get two arguments in a URL to work together to tell Panels what the context and content should be, respectively?

The problem is in this:

  $page->arguments = array(
    // Array key must be unique.
    'node' => array(
      'id' => 1,
      'identifier' => 'Node: ID',
      'name' => 'entity_id:node',
      'settings' => array(),
    ),
  );

I found workoroud for this problem. Create custom load hook that will be the similar to node or some else you need. Like this:

/**
 * Duplicates node load callback because panels can't have two same entities arguments.
 */
function mymodule_custom_load($nid) {
  return node_load($nid);
}

So to solve tis, you need to use %mymodule_custom instead of %node.
Hope this will help somebody, because I search the answer for very long time.


Order confirmation with attachment I'm sending order confirmation messages via the module message-notify. As mail system i'm using MimeMail.
Is there a possibility to add an attachment to the email with the key: commerce_order_order_confirmation?

I tried to add the attachment in hook_mail()

function mymodule_mail($key, &$message, $params) {

    if(isset($key)) {
        if($key == 'commerce_order_order_confirmation') {
            $attachment = array(
                'filecontent' => file_get_contents(DRUPAL_ROOT . '/sites/default/files/pdf/myattachment.pdf'),
                'filename' => 'myattachment.pdf',
                'filemime' => 'application/pdf',
            );

            $message['params']['attachments'][] = $attachment;
        }
    }
}

You want to change the email before it is sent.
So try this as a starting point (put together with the help of:
1. your post
2. https://drupal.stackexchange.com/a/98559/34326
3. https://www.drupal.org/node/2057703#comment-8343071):

function mymodule_mail_alter(&$message) {

    if ($message['id'] == 'message_notify_commerce_order_order_confirmation') {
        $file = file_create_url(file_build_uri('path-to-file-relative-to-your-files-folder.pdf'));
        $attachment = array(
            'filecontent' => file_get_contents($file),
            'filename' => 'test.pdf',
            'filemime' => 'application/pdf',
        );

        $message['params']['attachments'][] = $attachment;
    }
}

The file should be located in sites/default/files or whatever applies to your site.
You should also change filemime to what matches your file.

I am getting errors "realpath() expects parameter 1 to be a valid path" and "is_file() expects parameter 1 to be a valid path", but the email with the attachment is sent anyway, which is why I am posting this.The errors seem to be related to the 'filepath' parameter which is mentioned in the 3rd link, because depending on what I define, the results vary:
eg. 'filepath' => $file,, which gives me no attachment and no error or 'filepath' => $file->uri,, which gives me an additional error about a "non-object" and no attachment.

http://passivemanagement.net/blog/2014/01/let-drupal-send-email-attachment-using-mimemail-module uses a different markup for the file, but right now I can't figure out, how to adapt it to the task at hand.


Functions in template.php not working So I am new to Drupal and I am trying to create a new theme for a site. I am trying to create a page template for a specific custom content type. Research has led me to adding this to my template.php file:

function yourthemename_preprocess_page(&$vars) {
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

However, it is not working. I know the template.php file itself is being pickup up because a simple echo test works, but putting one in the function above does not fire. So I have to assume this function is not being called. I changed the 'yourthemename' to what I think is my theme's machine name. The folder name and .info name is FWMurphy. I tried that and fwmurphy and neither worked. I am stumped.

In your instance the hook should be (based on what you said your theme name is):

function FWMurphy_preprocess_page(&$vars) {
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

After you implement that, clear the drupal cache. For drupal to pickup your page--{node type}.tpl.php , you need to make sure your theme also contains a default page.tpl.php


How to show a secondary vertical axis to the right of a chart when using charts module? I have created a chart of two variables, using Charts module. To do so, I used the Views integration of the charts module, and selected 'Chart' as the views style.

The result I got so far is that the chart is shown using the same vertical axis (y-axis) on the left (one for each variable).

Question: Is it possible to use two vertical axes, so that the primary axis is shown on the left of the chart, and the secondary on the right?

See the answer here: https://www.drupal.org/node/2208461 (Courtesy of Quicksketch)

It is now incorporated in the (brand new) Charts community documentation, within Use sub-charts to create dual-Y-axis charts, which details the 4 steps to create such charts.


Newbie Question - How do I add content to this page? I'm very new to drupal, and I've been put on this project.

So I wanted to create a custom page to display the privacy conditions, which is just a word file I have to copy (so just plain text).

I created the custom page, used the template they gave me and now I want to add the plain text, however I have no Idea where I can do that. Normally I should be able to do it on this page they told, but I can't figure out why I can't change the Main Content.

Sorry for this very silly question, but I can't find anything about this on the internet.

Am not clear about your requirement, right now you are trying to display it using a panels. If your requirement is just to show a custom page with custom text.. then just add a basic page as a content and place the text in body field. Then call the page using the given path.


acquia cloud - images in content break, different path local vs cloud/server On my local dev environment, my images are stored in (relative to server root) /sites/default/files/images/

On the server, acquia cloud implements a virtual directory and the end result is that images are stored relative to root in /files/images

In my content nodes, I'm using root-relative paths for my images.  But this means any time I migrate my content between the local environment and the server, all images break.

I don't want to have to take any manual steps to change image paths every time I migrate content (I migrate content "down" from server to lcal periodically so that I am developing against "real" content).

Shouldn't there be some simpler way to configure things so that the root-relative image paths can intelligently choose the correct path based on which environment is being accessed?

Implement a directory redirect on your local environment's web server so that any request for /files/*  gets redirected to /sites/default/files/*

For example in Apache,  edit the httpd-vhosts.conf

<VirtualHost *>
  ServerName yourservername
  DocumentRoot "pathtoyourdocroot"
  Redirect /files /sites/default/files
</VirtualHost>


Update existing field collections with Migrate module How can I update existing field collection entities using Migrate module? I wasn't able to find any examples at the official documentation page, nor anywhere else.

When I'm migrating nodes, I can do something like:

$this->addFieldMapping('nid', 'nid');
$this->systemOfRecord = Migration::DESTINATION;

What's the alternative in this case?

There's no current support in field_collection for this (a destination plugin must explicitly support Migration::DESTINATION, merging mapped fields with pre-existing values for the unmapped fields). I'd suggest submitting a feature request at https://www.drupal.org/project/issues/field_collection.


SQL select data from more than one table I've constructed a nice query in drupal 7:

SELECT og.label AS title, og.gid AS gid
FROM og
LEFT JOIN field_data_field_group_category
  ON og.etid = field_data_field_group_category.entity_id
WHERE ( (field_data_field_group_category.field_group_category_value IN  ('1')) )
ORDER BY title ASC

This works but actually I want to remove the WHERE clause and instead put field_data_field_group_cat.field_group_category_value in my result. But when I try:

SELECT og.label AS title
  , og.gid AS gid
  field_data_field_group_category.field_group_category_value AS cat
FROM  og, field_data_field_group_category
LEFT JOIN field_data_field_group_category
  ON og.etid = field_data_field_group_category.entity_id
ORDER BY title ASC

This won't work.. How do I get a value of another table in the result object?

Greetings!

You second query is incorrect because you have the table field_data_field_group_category two times, so it would generates duplicates and there's a missing coma in your SELECT clause. If you want your column in the result without filtering it, just put it in the SELECT clause and that's it.

SELECT og.label AS title
  , og.gid AS gid
  , field_data_field_group_category.field_group_category_value AS cat
FROM og
LEFT JOIN field_data_field_group_category
  ON og.etid = field_data_field_group_category.entity_id
ORDER BY title ASC


How to make submenus appear on hover regardless of what page you are on? I am using CorporateClean theme for this site and I want the submenus dropping down from the main menu tab "gallery" to appear on hover no matter which page you are on. How to achieve this?

Edit your Menu Link and make sure Show as expanded is checked.

  If selected and this menu link has children, the menu will always
  appear expanded.


Is it possible to use the Forena module in conjunction with the Flot module? I need to plot based on some data that will be fetched from an external (non-drupal) database. I have found the Forena module, but in the part I do not like about the graph utility it uses by default.

Is it possible to use the Flot module in conjunction with Forena?

The Forena module says: "Virtually any JavaScript library may be used with Forena to produce amazing displays".

How is it implemented?

I'm not aware of a way to use the Flot module in conjunction with the Forena (disclosure: I'm a co-maintainer) module.

About "Virtually any JavaScript library may be used with Forena ...": have a look at the feature request # 2364427, especially these comments in it:

Comment nr 7, which is about a module for using Forena data with the d3js library.
Comment nr 15, which is about a related sandbox project.
Comment nr 18, about the D3 strategy.

Another approach is to write your own "renderer", as a variation of the FrxSVGGraph renderer (which extends FrxRenderer), and which is how the current support for the PHP SVGGraph library is implemented.


how to override the timeline-twitter css I embedded a feed from twitter into a block and I am trying to override the size of font by adding this to my css , but it still only picks up the css that is coming from twitter.  is there any way to override this on my drupal site without logging into their twitter page?

.timeline-Tweet-text {
       font-size: 18px; !important;
       line-height: 24px;
       font-weight: 300;
   }

In order to be able to style it, you'll need to stop using the standard twitter embed code and use another solution.

I suggest using the Twitter (https://www.drupal.org/project/twitter) and Oauth (https://www.drupal.org/project/oauth) modules for this.

This will allow you to create a view of your feed which you will be able to style easily.

There looks to be a pretty good recipe here: http://polso.info/integrating-twitter-feed-your-drupal-site

Good luck!
Anne


Alter form value in submit_preprocess How do I change a value, in this case the title field of a node object form, in the preprocess function of the form_alter hook.

$form['actions']['publish']['#submit'][] = MODULE_submit_preprocess';

function MODULE_submit_preprocess($form, FormStateInterface $form_state) {

   $form_state->setValue('title', 'Updated Title'); //not working...

   $fstate = $form_state->getFormObject()->getEntity();
   dsm($fstate);
}

dsm result

stdClass Object
(
    [__CLASS__] => Drupal\node\Entity\Node
    [in_preview] =>
    [values] => Array
        (
            [title] => Array
              (
                  [x-default] => Array
                    (
                         [0] => Array
                          (
                             [value] => Old Title

To change Entities fields its better use MODULE_ENTITY_presave() function (more info in docs).

In this case that you need change a node field use this function:

function hook_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity->set('title', 'Updated title');
}


Autocomplete views exposed textbox for Entity reference field I've got 2 content types "Equipment" and "Machine" , "Equipment" content type consists of an entity reference field targeting "Machine" content types.

My goal is to provide an exposed filter for user so he/she can filter equipments based on Machine's model. If "- Enable Render Views filters as select list" is checked in field settings exposed filter type changes to "select list" but cause I've got more than 11000 different models of machines , this is not an appropriate tool for selecting the proper model.

so the question is how can I provide an autocomplete textbox widget for this field (like what is provided in node creation form)?

I found an answer here : Drupal 7 Views Autocomplete Filter | Code Karate

Following this solution I installed Views Autocomplete Filter module and then in the view, I added a relationship based on field machine model and then a filter of type title of machine was provided .

Everything works great now.


Modifying download behaviour of drush By default the command:

drush dl <drupal-version>

will download the specified version of drupal from the internet. Is it possible to reconfigure drush so that dl looks to a local repo for the require drupal version?

You can use  the --source flag to provide your own xml release history file containing paths to your own gzips. (drush dl drupal defaults to http://updates.drupal.org/release-history/drupal/7.x.)

Sadly I don't think you can specify a local repo, or even a remote repo as the source of a project for dl. Drush expects a gzip file to download and unpack. You could however write your own drush command that takes a local repo path, gzips it, and passes the gzip to dl.


Website returning 404 and not 403 for forbidden pages My site is returning a 404 error for users who have tried to access a restricted page. I understand that this can be seen as a useful security features, however, I would like to return a 403 error instead.

I note that drupal is recording "access denied" in the logs, but somehow this is getting converted to a 404 for the user.

I have tried changing theme to see if that helps, and had no success. I have also removed custom 404 and 403 pages but this did not help either.

Googling the problem found the following file, drupal/core/lib/Drupal/Core/Controller/ExceptionController.php. This does not seem to exist in my installation of drupal.

I am not confident (or competent!) at altering php files.

Any help that can be provided would be greatly appreciated, as I am at a loss on how to proceed.

I've found a workaround using the "redirect 403 to login" module. It is not yet in alpha for D8, but seems pretty stable.


How to theme "My Results" (quiz module) tab that´s inside the user´s profile? I´m using quiz module in Drupal 7, and need to theme the output in "My Results" (wich is a tab in the user profile page).
Here´s the module´s function :
// THEME FUNCTIONS

/**
 * Theme the user results page.
 *
 * @param $results
 *  An array of quiz information.
 * @return
 *  Themed html.
 *
 * @ingroup themeable
 */
function theme_quiz_get_user_results($variables) {
  $results = $variables['results'];
  $rows = array();

  while (list($key, $result) = each($results)) {
    $interval = _quiz_format_duration($result['time_end'] - $result['time_start']);
    $passed = $result['score'] >= $result['pass_rate'];
    $grade = $passed ? t('Passed') : t('Failed');
    $passed_class = $passed ? 'quiz-passed' : 'quiz-failed';
    if (!is_numeric($result['score'])) {
      $score = t('In progress');
    }
    elseif (!$result['is_evaluated']) {
      $score = t('Not evaluated');
    }
    else {
      if (!empty($result['pass_rate']) && is_numeric($result['score'])) {
        $pre_score = '';
        $post_score = ' %
' . $grade . '';
      }
      else {
        $post_score = ' %';
      }
      $score = $pre_score . $result['score'] . $post_score;
    }
    $rows[] = array(
      'title'       => l($result['title'], 'node/' . $result['nid']),
      'time_start'  => format_date($result['time_start'], 'short'),
      'time_end'    => ($result['time_end'] > 0) ? format_date($result['time_end'], 'short') . '
' . t('Duration :  @value', array('@value' => $interval)) : t('In Progress'),

      'score'       => $score,
      'evaluated'   => $result['is_evaluated'] ? t('Yes') : t('No'),
      'op'          => l(t('View answers'), 'user/quiz/' . $result['result_id'] . '/userresults'),
    );

  }

  if (empty($rows)) {
    return t('No @quiz results found.', array('@quiz' => QUIZ_NAME));
  }

  $header = array(
    t('@quiz Title', array('@quiz' => QUIZ_NAME)),
    t('Started'),
    t('Finished'),
    t('Score'),
    t('Evaluated'),
    t('Operation'),
  );

  $output = theme('table', array('header' => $header, 'rows' => $rows));
  $output .= '
' . t('@quizzes that are not evaluated may have a different score and grade once evaluated.', array('@quizzes' => QUIZ_NAME)) . '
';
  return $output;
}

Now, all I need is to theme the output, and maybe add some special header before the results.
I´ve tried this at my template.tpl.php file, without any success:
function mythemename_quiz_get_user_results($variables) {
print "This is some information";
print "
";
print $variables;
print "
";
}

Now I know that print $variables; isn´t the way it should print an array, but the way to do this in Drupal 6 was this (I´ve took this code from an issue in Drupal´s forums):
function phptemplate_quiz_get_user_results($results) {
  // $results - An array of quiz results.
  // overriding statements
  print_r($results);
}

The function´s name changed, but the process shouldn´t be similar?
Thanks for your help!

Copy and paste (and rename) the original theme function to your template.php file, than just change what you need. Remembering that $variables is an array. Use the dpm function of the devel module to look at what values are in $variables that you can use.


How do I change the order of the Views row fields programmatically? How do I change the order of the Views row fields (programmatically) not by Views UI?

E.g: the last field should come up first in the list.

Any hooks available?

Note:
I can not use the Views UI, as I don't own the code for feature re-create, so I'm looking for some hooks.

Go with one of Views API hooks, e.g: hook_views_pre_render

You can access Views rows by $views->result.


How can one run drush from project root when using multiple site configurations? I have projects configured with multisite configuration, with folder structure as follows: sites/local.domain,sites/staging.domain.com, sites/domain.com.

All is well, except for one detail: I cannot run drush from project root directory anymore.  I need to cd up to the current configuration folder.

Is there a  way around this?

Try drush --uri=http://local.domain status from the root directory.

Also, you can create a file $HOME/.drush/aliases.drushrc.php, and define site aliases for each of your site. Then, drush @local status can be used.

Your aliases file would look something like this:

$aliases['local'] = array(
   'root' => '/path/to/drupal',
   'uri' => 'http://local.domain',
);
$aliases['staging'] = array(
   'root' => '/path/to/drupal',
   'uri' => 'http://staging.domain.com',
);
$aliases['live'] = array(
   'root' => '/path/to/drupal',
   'uri' => 'http://domain.com',
);

However, although it is off topic for your question, I must also mention that the multisite configuration you have set up here fails to meet the basic requirements for a viable dev -> test -> live workflow. In this configuration, your code is shared between all three environments. This means that when you update Drupal core on your dev site, the updated code will also be immediately applied to the live site, which affords no opportunity for testing. A propper dev -> test -> live workflow should use completely separate codebases for each environment, so that you may publish code on a controlled schedule.

Multisite can be useful in certain environments where you have a very large number of copies of the same code, e.g. separate live sites that want to share the same opcode cache.  For simpler setups, it's easier to stick with single codebases for each environment.


How to create view of referenced nodes with fields? I have node reference field which can take multiple values in it and I want to create a view of fields of these referenced nodes.

How do I achieve this?

Adding node reference field to contextual filter and select "Provide a default argument" in it and select "Content ID from URL". This will do the needful.


Drupal 7. Webform textarea with a html editor I am using drupal 7.56
I used the webform module to create a custom form which contains a textarea.

I want to add a html editor to my textarea.

I tested webform_html_textarea but it's not what I need.

How can I configure CKEditor module for this issue?

This is fixed by enabling wysiwyg, ckeditor and webform_html_textarea

Thank you


Page cache maximum age Please  advise me on the correct value to choose for “Page cache maximum age” as a cachin strategy (I’m running a medium Drupal 8.5.3 website).

As others have said, there is no "correct value". But if you are really stuck; a fairly simple way to choose is to consider how often content on your site will change, and then divide that by 2.

So if you expect your content to update every 24 hours: 24 / 2 == 12 hours. So set your cache to 12 hours. If you aren't sure how often content will change, set it to a slightly lower value. Is performance is very important, or if your site will be getting a lot of traffic, set a higher value.

You may also want to look at non Drupal caching options such as Cloudflare, varnish cache & memcache. But that's a whole other thing.


Use views as radios (or check-box) options in drupal forms Here is the scenario:

There is a multistep form for creating a content type "Support request".

Step 1: In this step, the user enters his/her device model and click next.

Step 2: In the next step, a list of technician (technician is a content type) whom has knowledge about that certain device will be shown, in this steps some information about technician is shown (from node) and user can decide which technician to hire.

Step 3: In the last step, some information about device problem is submitted by user and the form is submitted.

Now the question :

  Is there any solution to use views in second step? How can a view like this (note that the view output should be filtered based on the device model selected in first step) can be passed as radios options in drupal forms?

You can do it using one of listed module :

Views attach

  This module provides two additional Views display plugins, "Profile"
  and "Node content". These displays do not display on a page but get
  "attached" to either a user page or nodes of specified types.

Entity Views Attachment

  "Eva" is short for "Entity Views Attachment;" it provides a Views
  display plugin that allows the output of a View to be attached to the
  content of any Drupal entity. The body of a node or comment, the
  profile of a user account, or the listing page for a Taxonomy term are
  all examples of entity content.

View field

  View field provides a field that holds a reference to a View and
  renders it whenever the entity containing the field is displayed.


Redirect node type to a view I have created a view that lists all the nodes of a certain type. If you go to view the node on it's own page I would like it to forward to my view. I tried doing this using rules but as I display the full nodes in my view it created a loop. I could give all my nodes a /nodetype/title path if I can set up some wildcard redirect.

Assuming you have a pathauto setting, such as, "the-base-from-the-auto-setting/[nid]", and all of these nodes use the automatic alias and not a custom alias, you can implement hook_init() in a custom module:

function mymodule_init () {
  $path = drupal_get_path_alias(request_uri());

  if (strpos($path, "/the-base-from-the-auto-setting/") !== false) {
    drupal_goto("/the-path-of-the-view/", NULL, NULL, 301);
    exit;
  }
}

Note that drupal_goto() calls exit on its own, but I keep the exit there as a reminder.

The above is untested, but modified from a code snippet that I frequently use that does a drupal_not_found().  See http://drupal.org/node/846930#comment-3451328 for more details.


Deleted content returns over and over again I have a situation where I can delete (update options > delete selected content) in admin > content...and it says it deletes all the selected records.

But then later on all those records will return again. After I delete them they are not showing at all in (admin > content). But then later, they will show up again there and the links will be clickable etc. It will be like I never deleted them. I can do this over and over again and they keep re-appearing. We're talking about 50 nodes here.

I haven't updated the database otherwise. I've gone to a page (such as search) where those used to appear and they appear again there...and sometimes it seems like maybe that has something to do with it. But I still don't understand what or why.

Is there a better way to delete content to ensure its completely gone?

Did you check the error log? is there any warning or error in there?

If not then you should manually delete it from database. just look for their ID and remove them from DB


Ajax form only works the first time I have this simple ajax form with some ajax taxonomy checkboxes and a function that renders the content when the users changes the selected checkboxes. Everything work fine, the first time. The second time the user changes a checkbox I get this error:

Undefined index: form_build_id in ajax_get_form() (line 320 of /var/www/mf/includes/ajax.inc) and Invalid form POST data.

The only strange thing I've seen is when I inspect the request, there are a settings command, and ok insert command and another empty insert:

{command:insert, method:prepend, selector:null, data:, settings:null}

And in my html there is an empty .

My form:

function courses_lists_form($form, &$form_state) {dd(date('l jS \of F Y h:i:s A'));
  $terms = taxonomy_get_tree(1); // 1 = courses taxonomies vid
  $terms_array = array();
  foreach ($terms as $term) {
    $terms_array[$term->tid] = $term->name;
  }
  $form['taxonomias'] = array(
    '#type' => 'checkboxes',
    '#options' => $terms_array,
    '#title' => t('TEMÁTICAS'),
    '#ajax' => array(
      'callback' => 'courses_lists_form_ajax',
      'wrapper' => 'courses-lists-ajax',
    ),
  );
  $form['block'] = array(
    '#prefix' => '
',
    '#markup' => mf_form_commons_courses_lists_gen(0, 0, TRUE, 'matrix', array(0 => 9), ''),
    '#suffix' => '
',
  );
  $form_state['redirect'] = FALSE;
  return $form;
}

function courses_lists_form_ajax($form, &$form_state){
  $taxs = array();
  foreach ($form_state['values']['taxonomias'] as $tid) {
    if($tid) $taxs[] = $tid;
  };
  $outp = '
';
  $outp .= mf_form_commons_courses_lists_gen(0, 0, TRUE, 'matrix', $taxs, '');
  $outp .= '
';
  return $outp;
}

There was an error in the generated markup. A missing closing div was messing everything. Now everything work as expected. Thanks.


Composer packages changed, even though same version used I'm sorry, but in my project, composer update is changing files in my vendor directory even though I'm getting the exact same version of the libraries before & after.  I just want to ask, is this because the packages on packagist are changing, like a branch which is receiving new commits?  Or, is it that something is going wrong in my project?

I thought that if you use composer.lock to keep the versions exactly the same, no files should be changed.

We have kept our libraries versioned, is it possible that a developer modified them incorrectly?

composer update without any argument tries to update everything.

If you want to use the packages specified in composer.lock, run composer install instead.


Geofield Map marker NODE ID I have on Drupal 7 a Geofield Map Views that show a list of "Source" content on a Google Map.

I want to add on my marker on the map the information about the NID of the "Source" and I don't know how to do that.

The goal is to have my map and when I click on the marker, I get back the ID of the node and scroll down on the page to show the information about this Source.

Thanks in advance if anyone can help.

You can add a relationship, "Content" and make it available in fields.

If you can provide more details regarding your content type, I can provide a better answer.


Search api & solr search => no results found Configuration: I am using Drupal 7, search api and search api solr.

Description & problem: I am trying to use search api and solr search(as a back end) to search for nodes. I have a solr server running in localhost:8983/solr/admin/. I create a solr server inside drupal configuration, then I create a node index using this server and I index the field: title. The index runs successfully and indexes my 11 articles.

Then i create a search page using search_api_page to test out the searching functionality. Result: I get "Your search yielded no results" when searching for a word in the title of the articles (the word exists in the titles)

I am starting to become desperate here. The index is working correctly but neither through a search page nor through a view can I access the results. It says there are none :O Any ideas?

EDIT: I can query by hand, if i go to localhost:8983/solr/select/?q=spell:test then I get all the articles with the word "test" in their title. Also a ?q= will show all the indexed articles

There is a 'solr-devel' module to help http://drupal.org/project/solr_devel.

Make sure that the query works directly in the solr native search page. Isolate the drupal side this way.

Make sure that you have updated schema.xml and solrconfig.xml with the ones that come with the module as per the module README.txt. Reindex.

  Move apache-solr-1.4.1/example/solr/conf/schema.xml and rename it to
  something like schema.bak. Then move the solr-conf/solr-1.4/schema.xml
  that comes with this Drupal module to take its place.

  Similarly, move apache-solr-1.4.1/example/solr/conf/solrconfig.xml and
  rename it like solrconfig.bak. Then move the
  solr-conf/solr-1.4/solrconfig.xml that comes with this module to take
  its place.


What happened to the "menupath" token in the URL aliases for Drupal 7? Again, am I blind? If my "Widgets" page is under "Products," I want the auto-alias to be /products/widgets. I can't seem to find that in Drupal 7.


Use drupal #states to check a radio I would like to translate some jquery .change functionality to use #states in the form api.

var radio1 = jQuery('input:radio[name=radio_1]');
var radio2 = jQuery('input:radio[name=radio_2]');

radio1.change(function() {
if (radio1.filter(':checked').val() == 0) {
  radio2[1].checked = true;
}
else {
  radio2[0].checked = true;
}
});

radio2.change(function() {
if (radio2.filter(':checked').val() == 0) {
  radio1[1].checked = true;
}
else {
  radio1[0].checked = true;
}
});

Logic:
If radio1 value 0 is selected then radio2 value 1 will be selected.
If radio1 value 1 is selected then radio2 value 0 will be selected.
if radio2 value 0 is selected then radio1 value 1 will be selected.
if radio2 value 1 is selected then radio1 value 0 will be selected.

Looking at form_example_states_form() shows that the syntax is:

'#states' => array(
  'action_to_take_on_this_form_element' => array(
    'jquery_selector_for_another_element' => array(
      'condition_type' => value,
    ),
  ),
),

What's missing for me is "action_to_take_on_this_form_element". I don't know how to select value 0 or 1 of the radio button; all I have in terms of viable options is checked/unchecked (see drupal_process_states() for a list).

What I currently have

'#states' => array(
  'checked' => array(
    ':input[name="radio_2"]' => array(
      'value' => 0,
    ),
  ),
  'unchecked' => array(
    ':input[name="radio_2"]' => array(
      'value' => 1,
    ),
  ),
),

and this doesn't seem to work. I need something like checked[0] in order to select the value 0 radio button.

Edit: Here is the working code. Would like to not use inline js.

function your_form(&$form, $form_state) {
  $form['radios1'] = array(
    '#type' => 'radios',
    '#title' => 'Radios 1',
    '#options' => array(
      0 => 'zero',
      1 => 'one',
    ),
    '#default_value' => 0,
  );

  $form['radios2'] = array(
    '#type' => 'radios',
    '#title' => 'Radios 2',
    '#options' => array(
      0 => 'zero',
      1 => 'one',
    ),
    '#default_value' => 1,
  );

  $form['#attached']['js'][] = array(
    'data' => "var radio1 = jQuery('input:radio[name=radios1]');
var radio2 = jQuery('input:radio[name=radios2]');

radio1.change(function() {
if (radio1.filter(':checked').val() == 0) {
  radio2[1].checked = true;
}
else {
  radio2[0].checked = true;
}
});

radio2.change(function() {
if (radio2.filter(':checked').val() == 0) {
  radio1[1].checked = true;
}
else {
  radio1[0].checked = true;
}
});",
    'type' => 'inline',
  );

  return $form;
}

Demo video: https://www.youtube.com/watch?v=lXfMFaTTVes

You can use the form_api #after_build property to set a callback where you can manipulate the individual radio button elements (not the grouped "radios" element).

function your_form(&$form, $form_state) {
  $form['radios1'] = array(
    '#type' => 'radios',
    '#title' => 'Radios 1',
    '#options' => array(
      0 => 'zero',
      1 => 'one',
    )
  );

  $form['radios2'] = array(
    '#type' => 'radios',
    '#title' => 'Radios 2',
    '#options' => array(
      0 => 'zero',
      1 => 'one',
    )
  );

  $form['#after_build'] = array('your_form_after_build_function');

  return $form;
}

function your_form_after_build_function($form) {
  $form['radios1'][0]['#states'] = array(
    'checked' => array(
      ':input[name="radios2"]' => array('value' => 1),
    ),
  );

  $form['radios1'][1]['#states'] = array(
    'checked' => array(
      ':input[name="radios2"]' => array('value' => 0),
    ),
  );

  $form['radios2'][0]['#states'] = array(
    'checked' => array(
      ':input[name="radios1"]' => array('value' => 1),
    ),
  );

  $form['radios2'][1]['#states'] = array(
    'checked' => array(
      ':input[name="radios1"]' => array('value' => 0),
    ),
  );

  return $form;
}


How do you handle static HTML forms saved in a "Basic Page" in Drupal 7? I am a Drupal newbie and have been asked to help with some issues on a Drupal implementation. I have been asked to handle HTML forms that have already been designed and saved in "Basic Page" as either "full html" or php.

I have googled but could not find an references to such form handling. Almost every piece of code I have seen generates forms using Drupal Form API. There is enough documentation to work with forms generated using the Form API.

I would like to know if there is a way to handle these static(ally generated) forms and if so how.

I think the reason you can't find any documentation is because doing this sort of thing is very much discouraged in Drupal.

Drupal's form API exists for a good reason:

It allows theme/module developers to build up a form very easily
It provides a unified approach for themes and modules to add elements/validation/logic to any form that exists in the system. A good example of this in action is the Captcha module, which has the capacity to hook into any form in the system and add CAPTCHA protection.
It provides automatic protection against Cross Site Request Forgeries (CSRF).

If you're not up for coding your forms you should instead check out the Webform module which has an easy to use UI allowing you to build up nodes with forms on them, and it has very powerful administration features.

If you really want to do it without using the Form API or Webform modules, though, you could probably try something like this in a custom module:

function MYMODULE_init() {
  if (isset($_POST['my_post_var'])) {
    // Do something with the $_POST data
  }
}

Be warned that your forms will not be protected from CSRF, nor will they have the ability to be changed by other parts of the system. It's also just not the 'Drupal' way to do things :)


How can I protect development sites with Basic Auth module enabled? During development phase a dev site should be protected from being browsable by unauthorized visitors. Usually I use Basic Auth configured in the web server. This way the only information an unauthorized visitor gets is the domain name.

Drupal 8 uses Basic Auth or OAuth for REST (no Cookie method).

If you want to protect dev sites and use REST with Basic Auth you have a problem. Usually, you setup the webserver to use Basic Auth, as said above. But with Basic Auth module enabled Drupal triggers a 403 Access Denied because Drupal tries also to process the Basic Auth header.

Problems:

The header goes also to Drupal, that tries to use it, giving you a 403 because webserver Basic Auth doesn't match with Drupal users.
If you use two Basic Auth headers (one for the webserver or external layer, another for Drupal when consuming the REST services) you have you tweak your REST service consumers to send those two headers. Also, your webserver or external layer should remove the right header and pass header that Drupal should use.

Obvious solutions

(Use always OAuth for REST services) It seems that OAuth uses Authorization header too so not a solution.
Use other method to protect the dev site than Basic Auth.

Any other way to accomplish this?

NOTE: Clients have no static IP and can't use a VPN to connect (this is mainly because customers must be able to check the dev site).

The steps are as follows:

Modify .htaccess to read DirectoryIndex index.html index.php
Construct your index.html file to show whatever you need.
Modify your robots.txt to disallow any search engine robots to index your site.

Clients can check http://www.example.com/index.php whenever they like, and you can revert your .htaccess and robots.txt when you are done.


How to change the logo image dynamically when user change language? How to change the logo image dinamycally when user change language by clicking in the flag?
Exist an easy way to resolve this problems?

paste in page.tpl.php some condition like

if ($user-> language == 'ru') $logo_url = '../rus.jpg'

etc


Views report for Ubercart Order product totals for date range? I have been trying to create a view that will provide me with the total number of each product SKU ordered within a specified date range. Let's say there were three orders within the specified date range:

Order 101
Product ABC - Qty 1
Product XYZ - Qty 3

Order 102
Product ABC - Qty 1
Product XYZ - Qty 0

Order 103
Product ABC - Qty 10
Product XYZ - Qty 2

The View result would look something like this:

Total Number Ordered Per SKU for (date range)
Product ABC - 12
Product XYZ - 5

It is important for the results to be based on the SKU of the product, not the product title.

I have played around a bit with Views Aggregation on a "Type: Orders" view, but I am not knowledgeable enough to make it do what I need to do. Perhaps there is an easier way?

The purpose of this view will be to have an "at-a-glance" of which products need to be prepared for fulfillment, and how many of each, for the filtered date range.

Thanks!

I found my answer. I used the Views Aggregator Plus module (https://www.drupal.org/project/views_aggregator). I applied "Group and Compress" and "Tally Members" in the "Group Aggregation" column within the Views Aggregator Table options for the SKU field, and I applied "Sum" in the "Column Aggregation" column for the Quantity field. This provided me with the exact result I was looking for.


Is it possible to inherit a cck into another CCK and assign multiple values to it I have been searching stackoverflow, drupal forums, drupal.stackexchange for how to create multiple values for a group. I came across several posts regarding the issue mainly Drupal Custom CCK field with multiple child fields
 and cck multiple groups but I din't find (may be) the exact solution. I even tried Groups module but din't understand how to organize fields.

Is it possible to inherit a cck and call that cck into another cck and assign multiple values to it
I know that node reference field type will do this but can i assign multiple values ?
To be brief:

Now I want to call Asset cck in Events and assign multiple values to it just like eventname- Launching a new iphone

assetname(title of the pdf)-- iphone 5 introduction   Text field
               pdf(link) -- www.mysite/flder/iphone5intro.pdf   File type
assetname(title of the pdf)-- iphone 5 user manual    Text field
               pdf(link) -- www.mysite/flder/iphone5manual.pdf  File type
etc

It can have multiple values and it should also support views

help, and please ignore for any mistakes made, I will be very thankful for any alterations made.

From the first look at this, it seems you are wanting to create a cck content type with a multiple value filefield field so you can upload multiple pdfs per node.

If that is the case, make sure you have the FileField module installed if D6 (it's in core in D7) and then you can, after creating the content type, add a field, select it's type to be File, and then in configure, allow it to have 1,2,...10 or any number of values.

After that, everything "just works," including Views.


Drush 8x working from directories above web root, but not in web root I need some help trouble shooting Drush. I'm on a shared server, Hostgator, running Linux and PHP 5.6.3.

My install looks something like home/public_html/websites/MyDrupal

I have installed Composer globally as well as Drush
.bashrc includes:

# .bashrc
export PATH=$PATH:~/.composer/vendor/drush/drush
[ -z "$PS1" ] && return

# Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi

# User specific aliases and functions
alias composer="/usr/bin/php-cli ~/bin/composer.phar"
alias drush="~/.composer/vendor/drush/drush/drush"

Composer runs from any directory within my host space.

Drush will run, using the directory hierarchy example above, from 'home', 'public_html' and 'websites' but if I run drush status within 'MyDrupal' I get an error:

Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: syntax error, unexpected 'finally' (T_STRING), expecting catch
(T_CATCH) in
/.../public_html/bhsu/vendor/symfony/dependency-injection/ContainerBuilder.php,
line 452

Parse error: syntax error, unexpected 'finally' (T_STRING), expecting catch (T_CATCH) in /.../public_html/bhsu/vendor/symfony/dependency-injection/ContainerBuilder.php on line 452

Would appreciate pointers... thanks

Fixed: we figured out that composer and drush were using an older version of PHP which wouldn't work w/ Drupal 8. I still don't understand how the webserver can run one version (phpinfo.php showed the site running the expected 5.6 version) while Drush is set to another. Anyway, finding and aliasing to the proper version fixed the issue. The fix was adding this to .bashrc: (your path might be different).
    alias php='/opt/php56/bin/php'
    alias composer='/opt/php56/bin/php ~/bin/composer'
    export DRUSH_PHP='/opt/php56/bin/php'


user_register_form not give pre filled form I have created a module for user listing. when I edit any user then call drupal_get_form('user_register_form', $existing_account);, its not give me form with user data.

I used Profile2 module to add some custom filed in user registration page. Now in admin , I need those custom fields with user data in it.
for that I used drupal_get_form('user_register_form', $existing_account); function where $existing_account = user_load($uid, $reset = TRUE);

  function mymodule_create_subscriber() {
  ....

  $existing_account = user_load($uid, $reset = TRUE);

  .......
  $extra =drupal_get_form('user_register_form', $existing_account);

   $form = array_merge($form,$extra);

     $form[actions]['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Update Subscriber'),
      '#weight' => 30
$form['#validate'][] = 'mymodule_create_subscriber_validate';
  $form['#submit'][] = 'mymodule_create_subscriber_submit';
....
}

function mymodule_create_subscriber_validate(&$form, &$form_state) {

 ....some code

  return;
}

function mymodule_create_subscriber_submit(&$form, &$form_state) {
$account = array();
  $account = $form_state['values'];

......
 $account = user_save($existing_account, $account, $category);
   .....
}

Please help me where I am doing wrong or what should I do?

You are trying to hack user registration instead of extending the feature in a right way.

If your requirement is additional validations on user registration form try using hook_form_alter.

More about hooks here.


facets do not display on my search page I've setup apache solr and the facet api for my drupal 6 site, however I can't seem to get my facets to show up on my search page. The only time they show up is when I enable 'show enabled facet blocks under the search box' when there are empty results.

I tried to add my facet block to a region, but it remains blank.

I would think the facets should display on the search page automatically?

You should put your facet blocks into a regions and also you should be sure that they are rendered after the search is executed.


Display link after complete countdown time I am using Field Timer module.

Is there any option to display a link after finishing countdown ?

Alternatively you can achieve that using the jQuery Countdown module

Example for development usage:

In this example, we display an alert box saying "You are done!" after counting down from 10...

<?php
  echo '
10 seconds!
';
  jquery_countdown_add(".countdown", array("until" => 10, "onExpiry" => "finished"));
  drupal_add_js("function finished() { alert('You are done!'); }", 'inline');
?>


Views and external DB Oracle my Drupal 6 installation is on a MySql server, while my own custom database is on Oracle.
I have made a custom module that can read and write data into my external database, but i would like to use Views module to handle the data to show. I know that I can programmatically build views, but i don't know if I can build one for Oracle DB while Drupal is on Mysql.

You can create a view to a non-drupal table/database but you need to create a connection to it first using either one of the two connector modules: the Data module or the Table Wizard module.

You can also set it up using the Views API with views_hook_data(). (See documentation on views/help/api-tables.html.)

You'll need to add your new database connection settings in your settings file.

// In settings.php for your site
// Your drupal (site) database needs to be called 'default'
$db_url['default'] = 'mysqli://user:pass@host/drupal_db';
$db_url['oracle_db'] = 'mysqli://user:pass@host/other_db';

Then, in your view hook, define the tables the view should have access to.

$data[$table]['table']['base'] = array(
    'field' => 'Primary key',
    'title' => t('Field name'),
    'help' => t('Field description'),
    'database' => 'oracle_db',
    'weight' => -10,
);


How do I set the private file system path's permissions? There is an option in Configuration > File system which let you  define a path for private files. After setting a path in this field, the access for all users is restricted (including admin). I need to give the permission of accessing this directory and its files to some users. How?

Your module has to implement hook_file_download(). By default all private files will give access denied.

If your access rules are not complex, you can also use one of contrib modules, ex. Private files download permission


Drush one line command to create field I want to create field with name img for content type announcement

From the documentation, I can type drush field-create announcement. After that typing the field name img, after that type 2, lastly type 1.

Is there any ways achieving this through one line command?

just type :
    drush field-create announcement img,image,image_image

the last two are field_type,widget_name


How to I get rid of "Error with menu entry.... " in recent log messages? I have Taxonomy used to get a menu structure by using the module Taxonomy_menu. Since a couple of weeks I get "Error with menu entry "Activity" in menu "menu-products" in my "recent log messages" when somebody visits (even myself) our homepage.

Taxonomy_menu is the type of the report.

I've already tried to "Select to rebuild the menu on submit." via /admin/structure/taxonomy/products/edit and rebuilding taxonomy Menu.

More details added:

The lines "Error with menu entry "xxx" in menu menu-products" in the "recent log messages" appears multiple times, for every time the homepage is accessed.
I have made a Taxonomy list with 8 productgroups. One of the productgroups ("xxx") appears 6 times each time, another 3 times and a third one 2 times. The other 5 productgroups do not appear in the recent log message so seems to be working ok.

I've also noticed that the sequence of the 11 lines of error messages are exactly the same every time. Also strange that the productgroup that is referenced twice, is not directly repeated but appears later again in the logging.

I have an (almost exact) test version of the same website which doesn't show these message which lead me to the conclusion that this error message is caused by some kind of setting mistake for these 3 productgroups. However I have no idea where to change this so that these messages will be gone nor an idea why the number of times the message appears differs for 3 of them?

So far the website users are not be bothered by this message, but I like to get rid of it, as it fills my log messages very rapidly.

Can somebody please give me some directions?

Same problem here:

I just created a Vocabulary and set to sync with the Main Menu. When saving the Main menu doesn't show the terms of the vocabulary.

I get this error in the logs: which is fired by the line 1190 of taxonomy_menu.module

  Error with menu entry "" in menu "main-menu"

The vocabulary is set to:

  Translate. Different terms will be allowed for each language and they
  can be translated.


How to theme a field group (with div output and css class set)? I would like to theme a group of fields that belong to a content type. For example to position all of them at a certain area in the page.

I want to do this in conjunction with the field_group module

I know that it is possible to theme an individual field, by overriding field.tpl.php in your own theme, along with CSS as required. And I have done this successfully.

However I'd like to know if there is something like field-group.tpl.php which I can override in my own theme, similar to how I have done for field.tpl.php.

When editing the field group settings in the Content Type, <div> can be specified for a field group, as well as CSS classes. So I create a field group and specify these things and then add some fields to belong to my field group. However, when I look at the html source output for content of this content type, I cannot see anywhere this extra div is defined nor its groupname. Therefore I don't know how to theme it. Please advise.

I know you mentioned wanting to use the field_group module, but I don't immediately see the need.

If the goal is to position a set of fields all together, why not override your node.tpl.php file, calling it node--my-content-type.tpl.php and then somewhere within it do something along the lines of:

<div id="field-group">
  <?php print render($content['my_field1']); ?>
  <?php print render($content['my_field2']); ?>
  <?php print render($content['my_field2']); ?>
</div>

That way they can A) be positioned by positioning #field-group, as well as allowing you to theme each field in their own field.tpl.php file.


Module WYSIWYG with the 4.4.7 Ckeditor library stopped working What I got in Drupal 7:

WYSIWYG module 7.x-2.2

CKEditor library 4.4.7.3a35b3d

Changes I made:

1. This get's ckeditor library to work with WYSIWYG:

In .../modules/wysiwyg/editors/ckeditor.inc change line from function wysiwyg_ckeditor_version($editor)

if (preg_match('@version:\'(?:CKEditor )?([\d\.]+)(?:.+revision:\'([\d]+))?@', $line, $version)) {

to

if (preg_match('@version:\"(?:CKEditor )?([\d\.]+)(?:.+revision:\"([\d]+))?@', $line, $version)) {

This changes version number search from single quotes version: '4.0' to double quotes version "4.0"

This changed error in console log about jquery version.

2. In .. Wysywig .../modules/wysiwyg/wysiwyg.js change function

$('.wysiwyg', context).once('wysiwyg', function () {

to

 $('.wysiwyg:not(.processed)', context).addClass('processed').each(function() {
       if (!this.id || typeof Drupal.settings.wysiwyg.triggers[this.id] === 'undefined') {
         return;
       }

3. Iv'e cleared caches.

4. Added Full HTML format to /admin/config/content/formats

5. Added buttons at /admin/config/content/wysiwyg

6. Tried to "downgrade" to the 3.6.x version of CKEditor

7. Tried Ckeditor module https://www.drupal.org/project/ckeditor without wysiwyg module

8. Tired TinyMc library with wysiwyg

9. !Solution! need lines of kode at sites/all/templates/html.tpl.php to load wysiwyg.js .:

<?php print $page_top; ?>
<?php print $page; ?>
<?php print $page_bottom; ?>

I would "downgrade" to the 3.6.x vrsion of CKEditor (such as CKEditor version 3.6.6.1.7696), since the WYSIWYG module does not support the 4.x version yet ...). In this case, you may also want to experiment with the various 'cleanup and output' options within /admin/config/content/wysiwyg/profile/your_txt_fmt/edit (with 'your_txt_fmt' the text format you're using, eg 'filtered_html').

Another option is to switch to the CKeditor module (which is in core in D8 now ...), and no longer use the WYSIWYG module in combination with the CKEditor library.


Prevent users from editing a node if a CCK field has a specific value I would like to redirect users to an access denied page, if they try to edit a page with a specific CCK field value.

Any tips?

What you want is probably a custom node_access module - just remember that permissions in Drupal are additive, so your custom module is granting permission, rather than taking it away. So, for instance, a user should not already have the "edit this content type" permission or they'll have it for ALL nodes of that content type.

Also, why even assume they can attempt to edit? If they don't have permissions to edit that page, short of them manually hitting the /edit URL for a node, they're not going to have a chance - no edit button will be visible.