Product category pages I've had experience creating product catalogues in Drupal 7, but this is my first time using Drupal 8.

I have some categories defined as a taxonomy, and I simply want to create category pages that show the products in that category, with a friendly URL, e.g.:

/products/my-category-name

I'm not expecting anyone to explain the full process, but I'm hoping someone has a link to a decent guide/tutorial as so far hours of Googling hasn't uncovered anything.

The official Commerce documentation goes into making search pages and using facades and filters, but I don't need anything that complicated.

The easiest way to do this is just create a view using a page display
if you did not know you can use dynamic replacement in your views page urls

aka
"This view will be displayed by visiting this path on your site. You may use "%" in your URL to represent values that will be used for contextual filters: For example, "node/%/feed". If needed you can even specify named route parameters like taxonomy/term/%taxonomy_term" - copied direct from views (page) PAGE SETTINGS - path.

so you would set the path to be "/products/%taxonomy_term"

then in views "ADVANCED", CONTEXTUAL FILTERS you would add taxonomy term filter
you can look at "yoursite.com/admin/structure/views/view/taxonomy_term" . for a better idea on how to do this...

if all this sounds hard please look into creating filters:
example https://www.youtube.com/watch?v=aVwclF9TfBo

NOTE:  this will use the term_id as there is no default filter for term name
if you want to use the term name ... then follow
https://evolvingweb.ca/blog/how-create-custom-views-argument-plugin-drupal-8

or In a nutshell with no code:

Add a new field to your term and call it URL To Access of type plain text
and make it required.
Edit your terms and in the URL To Access field you would enter for a example "t-shirt" or "pants" or "what-ever-you-are-selling".
On your product type add the term reference field such as "Category"
Edit products to make sure they have a value for the "Category" field
Make New View of type product with page display and  url "/products/%"
Add RELATIONSHIPS of the field "Category" and require that relationship
Add a CONTEXTUAL FILTER for the field field URL To Access. Inside the settings do the followin:
a From the 'WHEN THE FILTER VALUE IS NOT IN THE URL' section
b Click on 'Provide default value'
c Then from the 'Type' dropdown select "Raw value from URL"
d And from the 'Path component' dropdown select "2"

then save it.

You can now go to : /products/t-shirt and see the products under this category.


"Page not found" or "Forbidden" when submitting form Is it a problem with Apache? I have some reseller hosting and I am running Drupal 7 sites on several different accounts there.

I recently noticed a problem when updating one of them. It happens when I am editing content or changing admin settings.

I go to an admin page - e.g. my.site/admin/people/permissions.
I make a change and hit "Save".
The page submits and reloads. The address
bar still says my.site/admin/people/permissions, but the page content
is:

  Page not found
  The requested page "/admin/people/permissions" could not be found.

I tried changing .htaccess files, disabling modules, etc, but nothing worked. In the end I did the following:

Created a new hosting account on my reseller hosting
Installed a fresh copy of drupal-7.58
Created a new database

When I repeated the actions above, I got the same results, except this time the error message was the following.

  Forbidden
  You don't have permission to access /drupal-7.58/admin/people/permissions on this server.

  Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

I then checked another account on the same reseller hosting. It's running Drupal 7.54 and showing Page not found.

I didn't have the problem a few weeks ago, so I am wondering if my hosting company has changed something in Apache which is causing this problem (really clutching at straws here).

I am using:

Apache 2.2.32
PHP 5.6.30
MySQL 10.0.34-MariaDB

Can anyone help?

Based on the given error message, the issue is definitely about file and/or directory permissions or ownership. Make sure all the files and directories belong to the username under which your website runs. Also fix the permissions per https://www.drupal.org/node/244924.


How can I get the $delta of block created using UI? I have a created a block using UI .I want to change the content of the block programmatically.
For this I am using hook_block_view_alter(&$data, $block) for it as follows:
I have just created a block using UI and I am going to assign certain pages which will be able to see that view..

function hook_block_view_alter(&$data, $block) {
if ($block->delta == 'HOW CAN I GET THE $DELTA here') {
$data['#markup'] = 'Google';

}

}

If you go to admin/structure/block and mouseover the "configure" link you'll see something like this for blocks added through UI:

/admin/structure/block/manage/block/1/configure

something like this for blocks created with views:

/admin/structure/block/manage/views/81e6b321879efa58ba9e546521c14467/configure

something like this for blocks created with webform:

/admin/structure/block/manage/webform/client-block-50/configure

something like this for blocks created by the system (core):

/admin/structure/block/manage/system/main/configure

I've bolded the deltas and italicized the modules in each example.


Update views result after unset() in views_pre_render In hook_views_pre_render(&$view) I have a simple code:

foreach ($view -> result as $key => &$result) {
    if('some condition') {
        unset($view -> result[$key]);
    }
    if('some condition') {
        unset($view -> result[$key]);
    }
}

Above works OK. it unsets result row of the view. Now, in my view I am displaying 2 results per page. Currently have it outputs 10 node which means there are 5 pages.

The problem is, as you might suspect that if, for example, 2 unset results happened to be on page number, say 2, of the view, this page is still displayed in the pager. So what I have now is 2 results on page number 1, no results on page number 2 and 2 results on page number 3.

Similarly, if only 1 result is unset, I have 2 results on page number 1, 1 result on page number 2 and 2 results on page number 3.

is there a way of letting the view know that it needs to update it's structure? There is a query_alter possible solution but I would like to avoid it if possible.

I do realise that this might not be the best way to unset results and I am open to suggestions, however i would like to keep the code in my custom module (not being fore to alter template.php).

You may want to look at doing this in Views' hook_views_post_execute():

  This hook is called right after the execute process. The query has been executed, but the pre_render() phase has not yet happened for handlers.

as the paging happens in the handler phase, and hook_views_pre_render()

  This hook is called right before the render process. The query has been executed, and the pre_render() phase has already happened for handlers, so all data should be available.

All about the various Views hooks is available here:

https://api.drupal.org/api/views/views.api.php/group/views_hooks/7

Also, some interesting conversation about this process and potential alternate suggestions is available here in a drupal.org issue queue "update pager count after chaning results in hook_views_pre_render" as well.


Avoid access denied page after user logout I am using Drupal 7. It is good that when user is logged out and again he access the

user/logout

link he is redirected to Access denied page.

Now I want that instead of Access denied page, i want to redirect to the specific page.

Can i achieve it using rules module or i have to write the code for that

What you want is something called 403 redirect to Login:
https://drupal.org/project/r4032login

403 access denied messages will get redirected to the login page. I've used this before and it works nicely.


How to add a simple online payment transaction? My client ask me to add a simple online transaction system to his drupal 7 site. Payment amount for his users are actually fixed for example 100$, 250$ and 350$. Also he wants link that transaction with his local bank and as optional he wants add the pay-pal also.

Could anyone please tell me how can I start to integrating this? I checked the drupal-ecommerce kicksart but I believe thats more advanced to this. However if anyone can instruct me to optimize it's requirement my client needs then it would be helpful.

I also checked Drupal https://drupal.org/project/simple_payments but since it's not supporting for the drupal 7 I've not much read on it.

I agree that Commerce Kickstart is too advanced for what you need. You'd end up spending a lot of time configuring "off" a lot of stuff just to give your users a simple checkout.

I've setup several simple custom payment solutions for Drupal sites using Webform and Stripe.com.

Here's an example of a Stripe/Webform component: https://drupal.org/sandbox/jlyon/1472346

Basically you'd build out the component that captures their CC info and submits it to Stripe via javascript, then run the charge on the server side using the token that Stripe gives you. This gets you out of the bulk of PCI compliance (you just need to have SSL enabled and ensure that you don't let any CC info be sent to your server). Since Webform is easy to use and you can add whatever form elements you'd like, you can quickly capture the right customer info and set the "product" or dollar amount in a dropdown field, then run the charge in a _validate() function.

Not quite plug and play but also not a lot of development time to get a solid working solution.

Edit: You mentioned PayPal – you could provide that as an alternate purchase opition and use a simple paypal button to send them on their merry way; also https://drupal.org/project/webform_paypal

Edit 2: After thinking about Ryan's comment a bit, I would suggest you first grab Commerce module and tinker with it for a while. You may find that it gets you what you need. I have really enjoyed implementing some custom, lean payment systems using Stripe where a traditional "checkout" workflow wasn't appropriate, but there's no need to reinvent the wheel if it fits.


How do I get clean output with indented structure How can I create a clean theming markup so that the output uses the same indented structure as in my static html template? E.g. when I insert $head;  Drupal uses it’s indenting format.

How can I control the ouput?

snippet from the html.tpl.php

<head>

  <title><?php print $head_title; ?></title>
  <?php print $head; ?>
  <?php print $styles; ?>

</head>

The output looks like this

<head>

  <title>Lorem Ipsum | mothership</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="Generator" content="Drupal Mothership" />
<link rel="canonical" href="/d7-demo/node/1" />
<link rel="shortlink" href="/d7-demo/node/1" />
  <style media="screen">
@import url("http://localhost/d7-demo/modules/shortcut/shortcut.css?nmdogy");
@import url("http://localhost/d7-demo/modules/toolbar/toolbar.css?nmdogy");
@import url("http://localhost/d7-demo/sites/all/themes/mothership/mothership/css/mothership.css?nmdogy");
@import url("http://localhost/d7-demo/sites/all/themes/itsgoodtobehere/bootstrap/css/bootstrap.min.css?nmdogy");
</style>

</head>

instead of

<head>

  <title>Lorem Ipsum | mothership</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="Generator" content="Drupal Mothership" />
  <link rel="canonical" href="/d7-demo/node/1" />
  <link rel="shortlink" href="/d7-demo/node/1" />
  <style media="screen">
    @import url("http://localhost/d7-demo/modules/shortcut/shortcut.css?nmdogy");
    @import url("http://localhost/d7-demo/modules/toolbar/toolbar.css?nmdogy");
    @import url("http://localhost/d7-demo/sites/all/themes/mothership/mothership/css/mothership.css?nmdogy");
  </style>

</head>

HTML Tidy can do what you're wanting, but this is designed as text format, Configuration » Content authoring » Text formats which are used in fields rather than the whole site.

Is should be possible with some work to pass the entire theme though HTML Tidy


Node is not created, but nid is returned I have this code in my module.

  $node = new stdClass();
  $node->title = "YOUR TITLE";
  $node->type = "page";
  node_object_prepare($node);

  $node->language = 'it';
  $node->uid = 1;
  $node->status = 1;
  $node->promote = 0;
  $node->comment = 1;

  $node = node_submit($node);
  node_save($node);

  return "Nodo 222: " . $node->nid;

When I execute this code, it returns "Nodo 222: XXX," where XXX is an integer. If I execute it another time, I get XXX+1. When I try to load node/XXX or node/XXX+1, Drupal give me a Page not found error.

I have seen the "node" table in MySQL (via PHPMyAdmin), and nids XXX and XXX+1 are not present. When I create a page via node/add/page, the new nid is XXX+2 and it is saved in the "node" table too.

I have some modules installed (commerce, rules, logintoboggan and others), but this is the first time that I see this strange behavior.

So, where is my error?

Hope this will help you,

In Drupal 7, The $node object you pass to node_save() wouldn't get it's nid member populated unless the node has been successfully saved to the node table in the database.

The auto-increment ID actually comes from the database table so if the $node object has a nid, you can pretty much guarantee the record has been successfully inserted into the table.

Im just guessing check for "node" table paging.

Clear drupal cache and check again.

I have used the below code and it is working fine for me, you can refer this.

  $node = new stdClass();
  $node->type = "page";
  node_object_prepare($node);
  $node->title = 'test node';
  $node->language = 'it';
  // Set node body details
  $node->body[LANGUAGE_NONE]['0']['value'] = 'test body';
  $node->body[LANGUAGE_NONE][0]['summary'] = text_summary('test body');
  $node->body[LANGUAGE_NONE][0]['format'] = 'filtered_html';
  //.. other fields goes here
  $node->uid = 1;
  $node->status = 1;
  $node->promote = 0;
  $node->comment = 1;
  if ($node = node_submit($node)) {
    node_save($node);
    drupal_set_message('NODE : ' .$node->nid);
  }


Drupal 8 get cart item programmatically I need to create pdf of user's cart items with custom header & footer. I decide to create custom module in which I can get cart items details. But I have no idea about how to do this? I have tried:

$store_id = 1;
$order_type = 'default';
$cart_manager = \Drupal::service('commerce_cart.cart_manager');
$cart_provider = \Drupal::service('commerce_cart.cart_provider');
$entity_manager = \Drupal::entityManager();
$store = $entity_manager->getStorage('commerce_store')->load($store_id);
$cart = $cart_provider->getCart($order_type, $store);
foreach ($cart-> getItems() as $order_item) {
    foreach($order_item->getPurchasedEntity() as $purchased_entity){
        print_r($purchased_entity);
    }
}

But it gives an array like

Drupal\commerce_product\Entity\ProductVariation Object
(
[values:protected] => Array
    (
        [variation_id] => Array
            (
                [x-default] => 432
            )

        [type] => Array
            (
                [x-default] => product_variations
            )

        [uuid] => Array
            (
                [x-default] => 87d27a77-4bc1-40ff-b3cf-ad3e949ce1b3
            )

        [langcode] => Array
            (
                [x-default] => en
            )

        [status] => Array
            (
                [x-default] => 1
            )

        [uid] => Array
            (
                [x-default] => 9
            )

        [product_id] => Array
            (
                [x-default] => 65
            )

        [sku] => Array
            (
                [x-default] => xx-uua
            )
        [price] => Array
            (
                [x-default] => Array
                    (
                        [number] => 22.000000
                        [currency_code] => USD
                    )

            )
        [field_order_no] => Array
            (
                [x-default] => Array
                    (
                        [0] => Array
                            (
                                [value] => PE-5070
                            )

                    )

            )

And many more protected objects.
I know I can get quantity, title & price easily using drupal function but how can I get few custom details from above array like field_order_no in above array, I have some unique attribute assigned to variation that I need to display in pdf?

As the top line suggests $purchased_entity is of of type "Drupal\commerce_product\Entity\ProductVariation" which is basically an entity.

All entities have a ->get('field_name') method.

So for your example to get 'field_order_no' you would do

$order_no = $purchased_entity->get('field_order_no')->getValue();

You can retrieve the value of any field via the ->getValue() method which returns an array.


Can't install modules in Drupal 8 Ubuntu - Should I change owner? Its not the first time I install Drupal 8 on Ubuntu 15.10 (which I'm very new to) but it is indeed the first time when I can't install modules at it.

I ran the error at Google and After reading this document regarding to a similar problem in Drupal 7, and a few other docs, It seems I should do in terminal:

sudo chown -R www-data sites

Since I am new to Linux and I also know that Drupal 8's folder hierarchy has been changed a bit, and I'm not sure if its the right move (I'm afraid to make mess); Thus, I dedicate this question to senior developers which are also Linux veterans...

go to the folder where you installed Drupal 8. Ex:

cd /var/www/drupal

In you case, it looks like it's:

cd /var/www/html/benia

then

sudo chown www-data -R modules

Now try installing again.

To prevent other conflict, I would www-data all of your Drupal

cd /var/www/html/

sudo chown www-data -R benia


How do I append a country to a views exposed filter field geofield proximity? Using Geofield with Google's API, when a user enters "Vancouver", it assumes I mean "Vancouver, Washington", when I actually want "Vancouver, BC". Is there any way to append "Canada" to the location info submitted to google?

It would be nice if I could do this with some override but will accept a hack to the module and I will just keep track of the modified module.

Here is a link to Geofeild's code that covers this. http://pastebin.com/Diwj5deE

Note: That I just need the country appended to the info sent to google. I don't want the filter to have a default of "Canada" and it can't prefilter the view with "Canada". It is not until the user actually uses the exposed
filter.

As with any form, a custom module can modify the #submit array to put a submission handler in front of the views exposed filter form to preprocess the data.

Here we're just modifying the submitted origin value so that " Canada" is appended if any text is entered by the user:

/**
 * Implements hook_form_views_exposed_form_alter().
 */
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  array_unshift($form['#submit'], 'MYMODULE_form_views_exposed_form_submit');
}

/**
 * Modify submission value if given origin has been supplied.
 */
function MYMODULE_form_views_exposed_form_submit($form, &$form_state) {
  if (isset($form_state['values']['field_geofield_distance']['origin']) &&
      strlen($form_state['values']['field_geofield_distance']['origin']) > 0) {
    $form_state['values']['field_geofield_distance']['origin'] .= ' Canada';
  }
}


Inline images of body is not getting migrated I am migrating a drupal6 site to drupal7. I am using migration and migrationd2d_ui module for this. Everything is working fine except wysiwyg inline images in body. path is getting migrated for wysiwyg images . But in content [[wysiwyg_imageupload:15:]] is appearing. In drupal 6 wysiwyg with tinymce editor is running. I am using same wysiwyg with tinymce editor in drupal 7. In drupal6 wysiwyg_imageupload module was used for inilne images in body.

How can i migrate these images in drupal 7 ?

Looks like the Drupal 6 site which you are wishing to migrate was using the wysiwyg_imageupload module for uploading the images to the content region.
If you have a look at the Repository viewer of the module, you'll see that the module defines certain input filters : Drupal Wiki inline images to be precise which converts the images saved in format [[wysiwyg_imageupload:15:]] into the real path when the page is rendered.

To resolve this, you'll have to implement the prepare function and actually change the value of the content and replace the filter formats with src and then run the migration.


Is it possible to make a patch that modifies a module's composer.json? I want to confirm some behavior of Composer to see if this is a limitation of Composer or something I did wrong.

This is based on an issue in the Markdown module queue.

Basically, here's the issue.

The Markdown module requires ^0.15 of a library.
I wrote a patch to require ~0.15 of the library. (to allow 0.16, 0.17, etc.)

But, when I apply this patch via Composer, and then try to update the library, I still get a drupal/markdown  1.2.0  requires  league/commonmark (^0.15.0) even though the module's (patched) code on my site requires ~0.15.

So, is there no way to "patch" a composer.json so that it will be picked up for composer update?  Am I reliant on the module maintainer to commit the patch?

This issue is actually addressed in the composer-patches documentation:

Because patching occurs after Composer calculates dependencies and installs packages, changes to an underlying dependency's composer.json file introduced in a patch will have no effect on installed packages.
If you need to modify a dependency's composer.json or its underlying dependencies, you cannot use this plugin. Instead, you must do one of the following:

Work to get the underlying issue resolved in the upstream package.
Fork the package and specify your fork as the package repository in your root composer.json
Specify compatible package version requirements in your root composer.json

If you want to follow option #2, you can fork the project's git repo, modify it, and add the forked repo to your project's repositories property:
    {
        "type":"git",
        "url": "https://github.com/vendor/module"
    }

So you can reference that dependency until the upstream has resolved the issue.


How do I add an ajax item on the submit button? I created a form using the module "Webform". Now I want to add an #ajax item to the submit button.

Here's what I already did:

use \Drupal\Core\Form\FormStateInterface;

function mytheme_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
  $form['#submit']['#ajax'] = array(
    'callback' => '\Drupal\mymodule\Controller\DefaultController::process_form_submission'
  );
}

The '#submit' field of the form now looks like this:

'#submit' => array(2)
    '0' => string(12) "::submitForm"
    '#ajax' => array(1)
        'callback' => string(72) "\Drupal\mymodule\Controller\DefaultController::process_form_submission"

But the process_form_submission function is not called. Instead the page reloads on submit as before.

Try this:

$form['actions']['submit']['#ajax'] = array(
        'callback' => '\Drupal\mymodule\Controller\DefaultController::process_form_submission',
'event' => 'click',
      );


Passing values from EntityFieldQuery to db_select Checked for this, but don't seem to be any specific answers to this question.

I'm trying to pass results from EntityFieldQuery to a db_select query, via a string. However, although debugging both queries with set values shows that they are operating correctly and providing the desired results, when using the string in db_select I am getting null results.

The purpose is to get certain node ID's as an integer value and pass them as an array of Entity_ID integer values, so the db_select function only selects table rows which match a certain Entity_ID.

I presume I'm making a output format error for the EntityFieldQuery, but can't work out what exactly it is.  Code is as follows:

// EntityFieldQuery
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
                   ->entityCondition('bundle', 'contenttype1')
                   ->propertyCondition('status', 1)
                    ->fieldCondition('field_field', 'value', $contenttype2, '=')
                   ->fieldOrderBy('field_field', 'value', 'ASC')
                    ->execute();

// Debugging functions only, return correct values when tested
$show = array_keys($entities['node']);
echo 'this is show: ' . $show;

$print = var_dump($show);
echo 'this is print: ' . $print;

// db_select function, returns correct sum when '$entities' is replaced with integer value for entity_id
$dbquery = db_select('tablename', 't')
  ->condition('t.entity_id', '$entities', '=');
$dbquery->addExpression('SUM(value)', 'value');

$result = $dbquery->execute()->fetchField();

// Debugging function only
print 'this is result: ' . $result;

The EntityFieldQuery is producing the correct values, but it isn't clear that they are in the correct format. The $print output is:

array(2) { [0]=>int(213) [1]=>int(214) }

At present, the SUM result works correctly when I replace '$entities' in the db_select with (e.g.) '213', but returns 0.0 when I use '$entities'.

EDIT: using

dpq($dbquery);
dpr($result);

Gives the confirm message:

SELECT SUM(value) AS value
FROM
{votingapi_vote} v
WHERE  (v.entity_id = )

And the error message:

Warning: PDO::quote() expects parameter 1 to be string, array given in dpq() (line 1835 of /var/www/html/sites/all/modules/devel/devel.module).

What is the output format code / function I should be using for EntityFieldQuery?

Try this approach. after getting your entities using EntityFieldQuery, create a for loop in order to check the val that was stored in your variable $entities. Then use dsm or dpm to check if it returns a result.

$results = '';
for ($i=0; $i < count($your_entity) ; $i++) {
    $query = db_select('yourtablename', 't');
    $query->fields('t');
    $query->condition('t.entity_id', $your_variable);
    $results = $query->execute()->fetchAll();
}
dsm($results);

Hope this helps you.


How to switch language on pages containing charts created using Forena? I have created a chart using Forena Reports. I have created a menu with this chart as one of the links.

I have also installed the Language Switcher Dropdown module for choosing between 3 languages. When I choose between any of the languages, the page will get refreshed and I will be able to see the transalated version.

But this is not happening when I am in the chart page. When I choose other language page is not even getting refreshed also language is not getting changed. When I go to other pages and try the same, everything is working as expected.

Note: When I go to the chart page I can see this error in console:

  Uncaught TypeError: $(...).dataTable is not a function

which is coming from the datatables.js file inside the forena report.

As per the "uncaught TypeError: $(...).dataTable is not a function" you mentioned, it sounds to me that what your language problem is actually not a language problem, but some installation issue related to what's required to Enable Data Tables support. I'd recommend you to first try to resolve that error (as explained in the documentation in the mink I mentioned before, which you can also find in your own site located at /reports/help.setup#datatables.

You may also want to look at my answer to the question about "How to translate the title, axis labels and legend of a chart?" for the typical steps required to correctly translate a chart create with Forena (just to make sure such translation exist for each of your languages, and that the URL for each translation of the report is correct, and does exist).

If neither of this helps to sort out what's happening, then please further enhance your question by including your report/chart specifications (= what's called the "frx"-source in Forena). After doing so, I'd be happy to try to further enhance my answer also.

Disclosure: I'm a co-maintainer of Forena Reports.


Create view gallery, with page for every image I have a node "Event Gallery" that has a multiple unlimited image field that I load up to 50 images into for each event.

In manage display, I set the image field as hidden, and instead, I use a views block with a content by ID filter, and the block visibility set to all node type > Event Gallery.

In the past I have used something like colorbox to let users scroll through the gallery, which looks nice, but does not function well when you want visitors to be able to "share" or "like" an individual photo, and for that individual photo to have its own url.

In the image field settings, you can make each image in the gallery link to its file, but I want the file to be shown in the theme, and have its own url.

How do I attach a page to my block view, to show every image of the gallery on its own page, with previous & next links (pager), and for every image to have its own url?

If I understand the question properly, something like this should work...

if the url is user defined, create a field using URL. If not, the answer depends on the requirements of the URL.

1 per page: set the pager to limit 1 per page

Link:

add the link field, set to exclude from display
add the image field as normal, exclude from display
create a Global Text, with  tag, using the image field and link field as replacement patterns


How to create multiple blocks for blog teasers from a single view automatically I have created a site whose home page is built in a way that it will display 4 latest blog posts in separate blocks all the time.

I have created a view and successfully created a single block displaying one latest blog post, but I am not sure what to do to get the other 3 blocks generated automatically. Any idea?

If I understand the question correctly - In views, create a new block for each instance of the block you want by clicking on +Add:

You could also create a completely new view, but this keeps things organized.

Where you put in the number of items to display, you can change the offset of the item:

In this way you can set the second block to have an offset of 1, the third 2, and so on. You can then create 4 blocks that each contain one of the most recent 4 items.


Restrict core to generate taxonomy terms' URLs I'm working on very large existing Drupal site that has thousands of nodes, user in it and bunch of Taxonomies as well.

I understand very well that Drupal core generates default URLs (taxonomy/term/tid) as we create a taxonomy term but my requirement is not to so is there a way we can control it?

Updated

Actually, I'm working on SEO of the site so according to the SEO report there are more than 10K redirections to 404 page from the Location taxonomy term pages (URL aliases generated by pathauto module and redirected by custom code to 404). So the owners want to reduce 404 redirections.

I was thinking I can achieve this

By deleting URL aliases of terms so aliases URLs'll not be listed in the google search (would be less SEO friendly) and user'll not try to access, by this way we can reduce 404 redirection.
By deleting taxonomy/term/tid, path to such terms will permanently removed so I'll also help to reduce 404.

What do you suggest?

My approach to this previously has been to ensure that there are no links within the site to taxonomy terms and that they are removed from the XML sitepath (using https://www.drupal.org/project/xmlsitemap) so they don't get into the search engines' database in the first place.

I would also recommend a module such as https://www.drupal.org/project/rabbit_hole which can force either a redirect, page not found, or access denied for taxonomy pages (and others) automatically.

I don't think there's any sense in trying to remove taxonomy links from the system when you can use the modules above to achieve this automatically for you.


What is the best way to stop a node from loading in a node hook? I want to use hook_node_view to stop a node from loading if it was not created by the user trying to access it. What should I include in the following code to kill the loading of the node?

function hook_node_view($node, $view_mode, $langcode) {

    global $user;
    $currUser = $user->uid;
    $nodeUser = $node->uid;

    if ($currUser != $nodeUser){
        drupal_set_message('kill page');
  }
}

You can't prevent a node from loading but you can deny/grant access to it. Write a custom module and implement hook_node_grants($account, $op) && hook_node_access_records($node). Here is a good example.

or, you can implement hook_node_access($node, $op, $account) but this hook will not be invoked  for node listings (e.g., RSS feeds, the default home page at path 'node', a recent content block, etc.)


Override webform confirmation and email message if token data is missing I have a webform in which I am using tokens to display data in the form submission confirmation and in a sent email.

Some of this data is pulled from a web service, and sometimes no data is returned by the API. This can result in the confirmation and email not being populated with data.

Form submission confirmation:

REPORT COMPLETE
Thank you for your report, which will be forwarded to: .
If you need to contact us about your report, you can do so at:
A confirmation email has been sent to: someone@example.com.

Email:

Thank you for reporting a problem at: Acme Inc.
Your report has been forwarded to .
Please do not reply to this email.

In this event, I'd like to override the confirmation and email message with a different message (that does not rely on data being available).

What is the best way to achieve this? Use hook_form_alter to test for missing values and then override the webform's #confirmation element? And how to override the email message?

Thanks.

The Settings handler allows you conditionally override the confirmation message and any other webform setting.

The Email handler support conditional logic and now also supports custom Twig template which allows you to use if/then (conditional) logic in the email message.


Taxonomy term translation I am working on a multi lingual site. I had installed the i18n (Internationalization). I wanted to get the taxonomy terms translated. But I was not able to do so.
In the translation mode I had chosen " Localize. Terms are common for all languages, but their name and description may be localized. "
Can anybody help me please...

It's not like, it's un-translatable. You have to render it on some page and then clear your cache and search in "{you-domain}/admin/config/regional/translate/translate" interface.


Adding different classes to menu item list I'm trying to override the way that menu items are displayed. I have the following function :

 function newtheme_item_list($items = array(),$title=NULL,$type='ul',$attributes=NULL)
 {
 $positions = array("","second","third","forth");
if (!empty($items)) {
$output .= "<$type" . drupal_attributes($attributes) . '>';
foreach ($items as $item_key=>$item) {
  $attributes = array();
  $children = array();
  if (is_array($item)) {
    foreach ($item as $key => $value) {
      if ($key == 'data') {
        $data = $value;
      }
      elseif ($key == 'children') {
        $children = $value;
      }
      else {
        $attributes[$key] = $value;
      }
    }
  }
  else {
    $data = $item;
  }

  if (count($children) > 0) {
    $data .= theme_item_list($children, NULL, $type, $attributes); // Render nested list
  }
  if ($item_key > 0)
  {
    $attributes['class'] = ' nav_separator '.$positions[$item_key].'-nav';
  }
  if($item_key == 0) {
    $attributes['class'] = 'first-nav';
  }
  elseif($item_key == count($items)-1){

    $attributes['class'] = ' last-nav';
  }

  $output .= '
'. $data .'
';
}
$output .= "</$type>";
}
$output .= '
';
return $output;

}

In the page.inc.php i have the line:

print theme('links', array('links' => menu_navigation_links('main-menu'),'attributes' => array('class'=> array('links', 'site-menu'))));

This it should add some different classes to my menu but instead i get this error:

Recoverable fatal error: Argument 1 passed to drupal_attributes() must be an array, null given, called in D:\EasyPHP-5.3.5.0\www\drupal\themes\newtheme\template.php on line 12 and defined in drupal_attributes() (line 2301 of D:\EasyPHP-5.3.5.0\www\drupal\includes\common.inc).

Your function signature is off, it should be like this:

function newtheme_item_list($variables) {
  $items = $variables['items'];
  $title = $variables['title'];
  $type = $variables['type'];
  $attributes = $variables['attributes'];
  ..
}

You should check the docs, when creating theme functions.


Keeping development database in sync with production database Here is my process for developing, this is more of a MySQL question then Drupal.

Have a local dev environment.  This includes a local mysql and a copy of the drupal site.  all under version control.
When the site is ready, I dump my database and set up a production database, I then create a production instance of the site from my repository.

So the issue I am running into is a user is adding content to the production site.  And I am creating database changes on the development version of my site.  The two versions are now out of sync.  One solution for this is every time I want to develop on my local version I dump the production's database and load it.  So I am wondering how this problem is usually approached.  Is there something like mysqldiff that will only load data that is not reflected in the database?? Are there any drush tools that will help with keeping drupal databases in sync?

It really depends on what you're changing in the development environment. If you're adding/removing modules, content types, custom fields, etc.. I can't think of a really good way to do this in any sort of trustworthy automated way.

Also I am SURE there must be modules for exporting Drupal content.  A quick search turned this up: http://drupal.org/project/node_export


Fetch Total Cost of Today Orders I am using Drupal-6 . i am using ubbercart module here. In Content type Product I have a field named Actual Amount.

Now i want to get total of Actual Amount by Datawise only .

Can Anybody tell me how to do this ?

Thanks

Views could do this and you might also want to use views calc, setup a view to display all orders with a filter to show only last day, then add the field for amount and use views calc to sum the total.


Alter node before render or after save I need to alter the content of a node either before it is viewed or after it is saved. In order alter the fields I will need the create date of the node. I am currently attempting to do this via hook_node_view, but is there a better way?

hook_node_presave() can help you making the changes

  Act on a node being inserted or updated. This hook is invoked from node_save() before the node is saved to the
  database.

so inside this hook you can get the created time and can change the title.

As an example code: Here I am making node title as the time article node is created.

function mymodulename_node_presave($node) {
  if($node->type == "article") {
    $node->title = $node->created;
  }
}

Make sure you do not call node_save() inside this function, else this will turn out to non breking recursion.


Field values of nodes available as tokens we would like to habe a node type only for side wide available values. We think we have a title and a 'value' field. When we need one of these values in text areas/fields we would like to type [title_of_the_node] and in the output we get the value of the value field displayed.

Does anyone know a solution for this?

Have you looked at the Token API? With the API one can define custom tokens. The functions you should look at are:

hook_token_info()
hook_tokens()

With hook_token_info() you define new tokens. In your case you could retrieve all nodes of your configureation node type (with an EntityFieldQuery for example), loop over the entries and create a token for each of them.

In hook tokens you define what your tokens are replaced with - just load the node entity for the given token and retrieve the content of your value field.

Here is a tutorial I found useful when writing some custom tokens a while back: http://www.fredparke.com/blog/create-your-own-tokens-drupal-7


Best way to search and replace text from blocks Is there a module or some other method to find and replace text from all existing blocks?  I've come accross Search and Replace Scanner Module but it looks like it only does search and replace on nodes.

Much Thanks.

Are you referring to custom blocks, not those provided by modules? If so, the main data is in the body column of the block_custom table in MySQL.

You could use an SQL query to perform the replacement.

UPDATE `block_custom` SET `body` = replace(body,"findstring","replacestring");

Credit: ChrisBrunner.com


What is the meaning of views displays? I know how to create a view as a page or block and etc.

But The Displays seems meaning I can create lots of views?

This following is my guess:

Is it will group all kind of views to a single page?
Does Displays just easily use the previous view configuration and
just Put similar view together to manager easily?

Views displays helps you manage your views that are similarly the same.

Basic example is articles:

On your home page, you want a simple block that shows 5 articles, no pager.
At the bottom of this block, you want a link "read all articles".
It redirects you to a page with all the articles, 10 per page, with a pager at the end.

Instead of creating 2 views, which is a waste of time, you'll create one view with 2 displays.

For this example, you will create two views displays, one "Block" and one "Page".
First you create your "Page" display (or "Block", as you want), set it to filter only articles content type, show the title and the date of publication.
Then you can create the other view display, and you only need to override the "Pager" settings.

Tomorrow, if you add an image to your articles, and you want them to appears on both the block and the page, you just need to add the image in the fields, and it will appear on both views display.

Beware that each views display has its own purpose, for example "Feed" will all you to create Rss display, "Page" needs it's own URI, etc.


Drupal 7 Search Redirect (similar to the old AOL keyword search) I've searched around for any pre-existing solutions to tackle this problem but so far nothing obvious. Here is basically what I'm after:

1) User enters keyword(s) via core search box

2) If user enters a specific keyword from a list of pre-determined keywords, redirect them immediately to a specific URL/node, e.g:

switch ($keyword) {
    case 'brand a':
        drupal_goto('brands/brand-a');
        break;
    case 'brand b':
        drupal_goto('brands/brand-b');
        break;
    default:
       do a regular keyword search . . .
       break;
endswitch;

3) If their keyword doesn't exist in the pre-determined list, shuffle them off to the standard Drupal search

Any ideas on how to best accomplish in Drupal 7?

If there is only a few you and you don't need any advanced matching you can add a path alias for the search path pointing to the preferred page.

E.g. searching for brand a gives you the path search/node/brand a. This path you can add as a path alias at admin/config/search/path/add pointing to a node of your choice.

For more advanced matching (and a more solid solution) you should probably hook into hook_search_preprocess() and do something along the lines of your example code.


Do not include certain pages from Search I have 3 pages I wish to exclude from search. Is there a way to exclude them from coming up in the search results? Incidentally, is it also possible for other content types other than Pages alone?

I haven't tried this in Drupal 7, but it doesn't seem to have changed much. There is an easy "hack" and a "better" way to do this:

The easy way is to override search-result.tpl.php. You can copy the default search-result.tpl.php file from the core search module into your theme. Then, inside the template you can use code like this to exclude results based on node ID:

 if ($result["node"]->nid != <excluded nid>) {
      // search result display code
 }

The only drawback with this approach is that you will have certain pages of search results that have less results than others (if you show 10 results per page and you don't display 3 on one page, then you will only have 7 results). You could also do similar hiding in template_preprocess_search_result with the same drawback.

The right/"better" way to do this is to actually exclude the list of nodes from ever being indexed. To do that you'll have to implement hook_query_alter. You can check out a post describing exactly how to do this over on Phase2's blog.

As you can see in the blog entry, you can also exclude by content type.

Note that the Drupal 6 way was to use hook_db_rewrite_sql. There is a post over at Lullabot on that.


How to include the comment page number in views "rewrite results"? I built a custom "new comments" notification system that doesn't rely on the history module (and the super slow queries when viewing nodes with new comments).

When I show nodes with new comments I need to rewrite the link to jump to the first new comment. "node/[nid]#new" does that. However, when I have a lot of comments and the first new comment is on the 2nd page (or higher) the link doesn't work. It would need to be "node/[nid]?page=1#new", etc.

I don't think the "page" value is available in views. Any tricks I can use?

I used a "Global PHP" field and added this code:

<?php
$new = $row->comment_count - $row->nc_count;
$page = floor($new / 50);
$link =  'nid;
if ($page > 0){
  $link = $link . '?page=' . $page;
}
$link = $link . '#new>' . $row->nc_count . ' new' ;
print $link;
?>

I don't like to use PHP in a view since it prevents caching. This view won't be cached, so it's not a problem this time. The other issue is that it doesn't generate the "pathauto" urls and requires an additional 301 redirect. I tried to use a "node link" variable but they don't seem to get changed to a pathauto link before the PHP field runs.

Any idea how I can render the /node/123 link to a pathauto link?


can you view a view in a table? I loaded a db to see settings of a view but can't access the site so wondering if I can view it via mysql?

OR can you reset the username and pass for admin in mysql?

Can you access the command line? If so, try to use Drush (the drupal shell command-line interface) to export the view settings.

If you use Drupal 6, this is possible once you install the Drush Views module so it won't help you since you can't access the site.

But if you use Drupal 7, you can use this patch.


Lat/Long not getting imported into Geofield via feeds importer I am working on a Drupal 7 website where I have a content type with geofield
I am importing a .csv file with lat/long (title and lat/long(geofield))

the node gets created with title, but no location coords.
How do I fix it?

Thanks

There is a bug in the Geofield module. When lat/long are set via Feeds, the Geofield module assumes the field to be empty because some other properties of the field are not set.

There is a patch available that could fix the issue:
https://www.drupal.org/node/2534822


How to get an anonymous user session id? I am writing a chat module where anonymous users are able to chat with a logged in user via an external websockets connection.

I need an ID to uniquely distinguish the anonymous users and assign them to different connections and keep track of the status of the connection.

How do I (securely) get a unique user id or session id for an anonymous user ?

You're looking for PHP's session_id():

  session_id() is used to get or set the session id for the current session.


Overhead of using Panels Panels is one of the most useful modules for Drupal and many websites make use of it.
However I always have been cautious using it because of its processing overheads.
I want to know is there any benchmark or article about Panels efficiency on the net?

Thank you.

This is the only thing I recall seeing, at DrupalCon San Fran in 2010. Sam Boyer, a maintainer of Panels, discusses benchmarks a bit in this video:  http://sf2010.drupal.org/conference/sessions/state-panels-3-and-more-what-you-love  at about the 29 minute mark.  It's not really a great benchmark test, but gives some idea into what page manager is running/processing.


500 (Service unavailable (with message)) on login or register Effectively the same as this (Drupal 500 Internal server error on login page) but i am unable to bump or comment so resorting to adding my own question.

The site is running Drupal 7.54 php version 7 and uses LoginToboggan module with login.

I am receiving "500 (Service unavailable (with message))" on the user and register pages, this occurs against user/login and ?q=user/login equivalent. Otherwise the site operates normally. There are no PHP errors in the log or browser console so i have nothing to try and trace.

I have amended the .htaccess file to use Rewrite as suggested elsewhere (this was already enabled anyway as the site sits in a subdomain).

Clean URLs are enabled.

I have added error reporting to settings.php to try and pick up on errors i've otherwise missed, nada.

I have used phpMyAdmin to clear the sessions table as suggested on another old thread. This resulted in me being kicked out and unable to get back in.

I can now only access the site db via phpMyAdmin and the site files via ftp (unable to log in as admin as login throws the error)

I tried to run update.php (removing login requirement from settings) out of sheer desperation but this had no effect.

Again in desperation i removed the LoginToboggan module (via ftp, i know) to try and revert the login to core but this had no effect.

I thought the main domain was conflicting in some way so i removed it (it wasn't actually used for anything and had an independent db so i just uninstalled it. No effect.

I really am at a loss, i can't figure out the cause and so have no way to implement a fix..

As you have access to the database through PhpMyAdmin, have a look in the watchdog table for any errors.

Disable anything causing an issue ;)


Fatal error: Call to undefined function db_transaction() I am new to drupal. In an attempt to achieve transaction, I get this fatal error. I am using drupal 6.22 and MySQL. db_query() and all the other database related functions are working fine, but db_transaction() alone fails. What am I doing wrong here? Any help is appreciated.

$transaction = db_transaction();

try {
       $result = db_query($query);
}
catch (Exception $e) {
       $transaction->rollback();

}

There is no fuction db_transaction() for Drupal 6 (see Drupal 6 API search).

It is available for Drupal 7 though: db_transaction()


Esign field in Webform I am attempting to add a signature field with validation to a webform.  The validation fields show up, the signature field seems to be there (cursor changes to +) but no field for signature is there.

Esign's documentation says to "
    Did you set the field to display?
    Does your CSS allow the field to display?
"
I'm suspecting that one of these may be my issue.  However, I have no idea where to set the field to display.  I should note that I added the esign field by adding the field in "form components" and not "form builder" as the field esign did not show up in the "form builder" tab.

Any help would be most welcome!

This is for Drupal 7.

You can set the field to display in this page:
admin/config/content/webform

For whatever reason the e-sign field doesnt appear for me under form builder it appears when i go to form components under type there should be an option called E-sign.


Software testing and regression testing My company has taken maintenance of a Drupal website where there are some modules that have been specifically developed for this site.

I have to answer to a question that most software do: how can we do "software testing" and "regression testing" with Drupal?

Drupal 7 comes with a Testing module, and for Drupal 6 you can download http://drupal.org/project/simpletest.

It doesn't do anything automatically (how could it..) but it allows you to write automated tests that test the functionality of your custom modules.

I wrote a blog post about this a while ago: Writing automated tests for Drupal 7. Even though the title says Drupal 7, most of it applies to Drupal 6 too. See Simpletest documentation on drupal.org for more information.


How to add a link to an image in a view I have a view that is showing a single image, and I need the image to link to a specific URL, but when I try using Rewrite Results on the field it will still show the image but doesn't add the link.

I have tried both "Rewrite the output of this field" putting in [field_file] and "Output this field as a link" putting http://example.com in the field and neither of those ways worked.

How can I rewrite the field to have the link on the image?

You can use the image url formatter module to output the path to the image.  Then do like you tried before to Rewrite Results and add the markup.


How do I hide static media file URLs? I have developed a website in Drupal 7. Right now I have a requirement: A page should display a PDF file (already generated). Only authenticated users should have access to view or download this file, but anyone with direct access to this static file link can view it and download it.
Is there any method I can use to prevent this and redirect them to the login page? What kind of logical programming needs to be applied in this case?

As @Clive and @prkos mentioned in comments above, Drupal has different stream wrappers for public and private file systems:
https://www.drupal.org/node/15368
I know you are using Drupal 7, but the Drupal 8 docs on the topic mention:

In Drupal 8, you can no longer set private file system via UI. You set it in your settings.php file.

So you might find it convenient that you can configure this in the Drupal 7 admin UI ( "Private file system path" under admin/config/media/file-system) without any edits to your site's codebase.
If you have configured the private stream wrapper correctly, you can prevent anonymous users from downloading those files and instead respond to their attempts with an HTTP error 403.
The remaining desired functionality is provided by the community-contributed module that @Clive mentioned:
https://www.drupal.org/project/r4032login
The module is available for Drupal 7, 8, and 9. Its project page will explain its usage, but basically it redirects users to the login page when they ask to access a restricted resource, and redirects them to their intended destination once they log in successfully.


For someone who is not a programmer or is starting how can he/she contribute to Drupal.org? I have been talking to people who are starting in the university about Drupal. But they are beginners in programming. so they told me how they can contribute to Drupal or being more involved.

What would be the best advice for them to contribute..or how they can start if they have limited program skills? Do you have any advice?

Both @David and @Patrick have put it well, on the ways to contribute to the Drupal community. I think a good place to evaluate yourself and then start contributing would be at Drupal Ladder.
It was a result of the work from the guys from Boston, who came together and started something called Boston initiative where they come together and work on contributing.

You can look at the ladder screenshot below :

If one wishes to contribute, s/he is suggested to follow this steps starting from bottom and climbing the ladder one step at a time.

For more, you can also view the session about Drupal ladder at DrupalCon Denver.

P.S. : The Drupal Ladder was designed to encourage users to contribute to Drupal core and not did not focus on contribution towards the modules (contributed).


How to list similar products using views in Commerce Kickstart? I am trying to list other products in the same category using the Views module when browsing a product.

For example, I am browsing drinks/drupal-commerce-wake-you; I want to list all other products in the "drinks" category, to build similar, or related products.

How can I achieve this?

Try this

Create view (block)
Add fields (title, a small image, date, whatever you like). Or teasers, what works as well.
“Arguments” is from now on called “Contextual filters”, so go there.
Add the filters: “Content: Has taxonomy term ID (with depth)” and “Content: Has taxonomy term ID depth modifier”
Configuration on this filter: → When the filter value is NOT in the URL: → Provide default value → Type: Taxonomy Term ID from URL → under that, check the box “Load default filter from node page, that’s good for related taxonomy blocks.” → now check the boxes of the taxonomies you want involved here
Now you need to add the second filter in order to exclude the current node from the list. Click [+] button of the contextual filters section.
Select Content: Nid
Set the ‘when argument is not present’ to ‘Provide default argument’
Set the ‘Default argument type’ to ‘Content ID from URL’
Go to “MORE” , and check the “Exclude” box.
Move the filter “Content: Nid” to the top position.
Add a block to your view and embed the block on your node pages
Save your view


Filters as rewrite results link path parameters I am currently using this approach to link lists view's rows to detail pages in Drupal 8

I would like to pass the entity title of the row to the receiving page and use that to select view blocks having that title.
In this case something like www.mysite.com/VenuePage?Name="Mikes"
This argument would then be used to select blocks with Title "Mikes"

Can someone point me in the correct direction? I'm a bit new to Drupal and may be thinking about this incorrectly.

If the entity title of the row is a field on the view you can use the Override the output of this field as a custom link option and then create a link yourself using replacement patterns. So long as the field you are referencing the entity title of is beneath the field you are referencing in the field list.


How can I override a link in the language menu? I'm using the i18n module and Views. I have a separate view for each language and the language menu obviously doesn't line up for each of those views. I want to be able to adjust the links for the language menu when I'm on each of those view pages so they map to the corresponding view in the other language?

Where/how would I adjust those links? Would it be something in the template.php file for the theme or should I do it in a custom module?

I'm certain there is a better way to do it than this...it's a little brute-force, but it gets the job done for me:

function THEME_preprocess_page(&$variables) {
  $markup = $variables['page']['my_region']['locale_language']['#markup'];

  // Do some string replaces on $markup to adjust the URLs

  $variables['page']['my_region']['locale_language']['#markup'] = $markup;
}

I know this isn't the Drupal way to do this. Part of the problem is that I only need to adjust the language links on a few Views pages, so figuring out how to do this in hook_menu_alter or in a module was too complicated...I needed a quick solution.

I'm hoping someone can pos the Drupal way of achieving this.


problems with entity translation insert hook I'm using the entity_translation_insert() hook to set the value of a field when a node is translated.
I can successfully edit the $entity from within the implementation, but how should I save the resulting node?

I can't call node_save because it would start an endless loop. I tried field_attach_update but the result is the same (i.e. loop).

I've tried following this article, with no luck: http://anthonypower.com/notebook/assigning-node-field-values-hook-insert-and-update-right-way

A trick to bypass this could be to use a static variable to process nodes only once per request, e.g.

/**
 * Implements hook_entity_translation_insert().
 */
function yourmodule_entity_translation_insert($entity_type, $entity, $translation, $values = array()) {
  static $processed = array();
  if ($entity_type == 'node' && !isset($processed[$entity->nid])) {
    // Do something
    $processed[$entity->nid] = TRUE;
  }
}


How do I create an AJAX filter for a view? I have created a page using Views and it works fine. I want to add an AJAX filter to this page to allow visitors to filter the contents based on PubDate or by Taxonomy/Vocabulary for this content type. How can I accomplish this?

Edit the view, and add a filter to the page:

Drupal 6: Third column, section is called Filters
Drupal 7: First column, section is called Filter Criteria

When you configure the filter, you want to expose it:

Drupal 6: Click the Expose button in the top right of the configure area
Drupal 7: Check Expose this filter to visitors, to allow them to change it

Enable AJAX:

Drupal 6: Use AJAX is under Basic settings in the first column
Drupal 7: Use AJAX is under Advanced → Other in the third column

When the view is saved, there will now be a form that'll allow users to filter the view dynamically via AJAX.


Cannot find installed ffmpeg I installed ffmpeg according to the ffmpeg instructions I found on d.o.

When I do which ffmpeg it tells me /usr/local/bin/ffmpeg but when I search in Finder for it (installing with MAMP) it tells me it's at /Applications/MAMP/bin/php/php5.3.6/bin/ffmpeg/ffmpeg .

I've tried pasting both of those paths into the field in Video configuration that says "Absolute path to FFmpeg executable. When you install a new FFmpeg version, please clear the caches to let Drupal detect the updated codec support." but then I get FFmpeg not found at [either of those paths].

I have tried removing the extra copies, to no avail. I've tried setting the document root in settings.php, to no avail. I've tried installing and building it manually as well as with brew. No dice.

That message error is returned also when the FFmpeg executable is found, but its output is not the module is expecting.

TranscoderAbstractionFactoryFfmpeg::adminSettingsValidate() contains the following code.

  if (!$ffmpeg['ffmpeg-found'] || ($version = self::getVersionFromOutput($ffmpeg['raw'])) == NULL) {
    form_set_error('video_ffmpeg_path', t('FFmpeg not found at %path. To convert videos and create thumbnails you have to install FFmpeg on your server. For more information please see the !documentation.', array('%path' => $ffmpeg_path, '!documentation' => l(t('documentation'), 'http://video.heidisoft.com/documentation/ffmpeg-installtion-scripts'))));
  }

PHPVideoToolkit::getFFmpegInfo() contains the following code.

$formats = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -formats');
$codecs = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -codecs');
$filters = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -bsfs');
$protocols = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -protocols');
$pixformats = $this->_captureExecBufferFallback($this->_ffmpeg_binary . ' -pix_fmts', $this->_ffmpeg_binary . ' -pix_fmt list');
$help = $this->_captureExecBuffer($this->_ffmpeg_binary . ' -h');

self::$ffmpeg_found = $data['ffmpeg-found'] = !empty($formats) && strpos($formats[0], 'not found') === FALSE && strpos($formats[0], 'No such file or directory') === FALSE;

The message error could be returned when:

The module is not able to detect the FFmpeg version from its output
The module finds the string "not found," or "No such file or directory" in output returned from ffmpeg -formats
The command line fails for any reason

In the latter case, the first condition of !empty($formats) && strpos($formats[0], 'not found') === FALSE && strpos($formats[0], 'No such file or directory') === FALSE; is FALSE, and $data['ffmpeg-found'] is set to FALSE, causing the error message you see.

For trouble shouting, you can:

Execute ffmpeg -formats and check the output doesn't contain not found, nor No such file of directory
Test FFmpeg works perfectly when running from the command line
Execute the following code, and verify $buffer is not an empty array

$command = "ffmpeg -formats"; // Use the full path of the command line you are testing.
$buffer = array();
$err = 0;
exec($command . ' 2>&1', $buffer, $err);

if ($err !== 127) {
  if (isset($buffer[0]) === FALSE) {
    $tmp_file = '/tmp/_temp_' . uniqid(time() . '-') . '.txt';
    exec($command . ' &>' . $tmp_file, $buffer, $err);
    if ($handle = fopen($tmp_file, 'r')) {
      $buffer = array();
      while (!feof($handle)) {
        array_push($buffer, fgets($handle, 4096));
      }
      fclose($handle);
    }
    @unlink($tmp_file);
  }
}

I would execute the code I shown in the last point with both the executables, just to see if there is a difference. To be sure the problem is not file permissions, I would execute the code using the same user that runs PHP code, which means I would put the code in a PHP file on the server, and run it as http://example.com/test.php. (Replace example.com with the domain name of the site you are testing.)

If the output of the command contains not found, or No such file of directory, but it works perfectly for you, it could be the module is being too cautious about what the command returns, and it assumes it would not work even if it effectively works. In this case, there is few that can be done, if not changing the code used from the module to detect when FFmpeg would not work.

In the case you get an empty $buffer array from the test code I described, it means the user used to run PHP doesn't have the necessary permissions to execute the command. In this case, you need to change the permissions.

As you have FFmpeg installed in two different directories, I would also check there aren't some conflicts between the commands, just to be sure. I am thinking, for example, to some files the command copies in another directory, and that is version dependent; if you have two versions of FFmpeg, that could be an issue.


How do I set the Views Plugin handler path different from the theme path? The file path of the module is set up like this:

addressfield/views/addressfield.views.inc
addressfield/views/addressfield_plugin_row_jmappingfields.inc
addressfield/views/addressfield_plugin_style_jmapping.inc
addressfield/theme/addressfield-jmapping-view.tpl.php
addressfield/theme/addressfield-view-jmappingfields.tpl.php

The problem is I can not figure out how to set the path in the plugin definition for the View. If I set the 'theme path' key to drupal_get_path('module', 'addressfield'). '/views' the handlers will register but the themes can not be found and vis versa.

/**
 * @file
 *  Provide the Addressfield plugin definition.
 */

function addressfield_views_plugins() {
  $path = drupal_get_path('module', 'addressfield') . '/views';
  return array(
    'module' => 'addressfield',
    'style' => array(
      'jmapping' => array(
        'title' => t('jMapping'),
        'help' => t('Display a view jMapping map.'),
        'handler' => 'addressfield_plugin_style_jmapping',
        'theme' => 'addressfield_jmapping_view',
        'theme path' => $path,
        'uses row plugin' => TRUE,
        'uses options' => TRUE,
        'uses grouping' => TRUE,
        'type' => 'normal',
        'parent' => 'default',
      ),
    ),
    'row' => array(
      'jmappingfields' => array(
        'title' => t('jMapping Fields'),
        'help' => t('Choose the fields to display in the jMapping Map.'),
        'handler' => 'addressfield_plugin_row_jmappingfields',
        'theme' => 'addressfield_view_jmappingfields',
        'theme path' => $path,
        'uses fields' => TRUE,
        'uses options' => TRUE,
        'type' => 'normal',
      ),
    ),
  );
}

How do I keep the theme templates for the style plugin and the handlers in separate folders for clarity?

I'm using Views 3 in Drupal 7.

You should create an addressfield/theme/theme.inc that contains the template_preprocess_addressfield_* functions. Then add: $theme_path = drupal_get_path('module', 'addressfield') . '/theme'; at the top.

'handler' => 'addressfield_plugin_style_jmapping',
'path' => $path,
'theme' => 'addressfield_jmapping_view',
'theme path' => $theme_path,
'theme file' => 'theme.inc',

That should work just fine.


Cron not working when called from SSH php curl - Elysia cron module activated I have Elysia cron module activated, with some cron task scheduled.

I have a crontab pointing to an sh every */2 minutes. The sh executes a php with a curl call to cron.php?cron_key=CRON-KEY. It was working perfectly some weeks ago. Suddenly, it has stopped working. When I launch the same cron.php address by browser, it works perfectly, executes the cron with all the scheduled tasks in order as defined by Elysia config.

But when the same cron.php is called via the SSH php (console or just through the cron daemon), it does not work. It gives no error or hint, just does not do anything. I have tested curl in the same domain, with GET parameters, to a different php file, and it is working. I have no idea what can be happening, I have re-installed Elysia cron, and the same results. I cannot understand why Drupal knows that the script is called via a non-browser script and why it stops working.

After much debugging (too much debugging, I am afraid), I discovered that the problem was in that the cron did not go through all the steps (bootstrap). The problem (which was not logged) was in the Domain Access module, in which I deleted the English language in one of the domain. IMHO, this is a bug, but not sure if of the module, the core or what. I cannot afford wasting 8 hours of my time looking for errors when I make a simple change that, in principle, should not affect the entire performance of Drupal. This is the kind of things that make Drupal not trustworthy.


Views Filter, Relative Date I have a view constructed with many fields, one of those fields is a date field.  I added a filter on my date field that is asking for a relative date.  OK, this is no problem, but I have a request to gather all results from month to date.  For example, I want to get the results from today's date, back to the beginning of the month.  I used for this filter, the operator, "is equal to", the relative date, "this month," and I get no results back, even though there is results between now and the beginning of the month.  I was thinking I am using the wrong relative date.  I looked up the documentation here: http://php.net/manual/en/datetime.formats.relative.php, and "this month" looks like the correct format, but maybe it is not. Can someone point me in the right direction.

I figured out the answer to my question.  In the filter option, if you filter the relative time format "first day of this month," and assign the operator "is equal to or greater than," the output will be the first day of the month to the current day.
Hope this helps anyone that reads my post.


Live site still taking nodes url as localhost/ I have developed a Drupal site on localhost; I then exported it to a production site, and made the required changes in settings.php.
The index page opens fine, but when I log in, the URL is still referring to localhost.
I tried to set the base URL in settings.php, but it did not help.

I am using Drupal 7.10.

Try clearing all Drupal caches at yourwebsite.domain/admin/config/development/performance


How to disable breadcrumbs for certain pages? How can I just disable breadcrumbs for certain pages on drupal 8?

There is a module for this on D7, is it easy in D8?

Your Breadcrumb is a block that you place in Block Lay-out. Then just change its visibility.


Migration Issue: New Site won't open -- server doesn't see file that is there I am migrating a Drupal site from my localhost to the most current Bitnami Drupal AMI on Amazon:

I uploaded the DB successfully.
I moved the files correctly.
I copied over the modules and libraries.

I got the WSOD, changed the error reporting and now, upon opening the site I get:

    Fatal error: require_once(): Failed opening required
'/opt/bitnami/apps/drupal/htdocs/sites/all/modules/views/includes/view.inc'
(include_path='.:/opt/bitnami/php/lib/php') in
/opt/bitnami/apps/drupal/htdocs/includes/bootstrap.inc on line 3066

But the file is in the proper spot, within the structure outlined by Bitnami:

/home/bitnami/apps/drupal/htdocs/sites/all/modules/views/includes

How do I convince drupal (or php) to use "/home" instead of "/opt"?  I suppose I could just try a symlink but... that seems like such a kludge.  I'd like to do it the "right" way.

Any suggestions?

If your files are all under /home instead of /opt you could just setup a virtualhost and point to the /home docroot

e.g, for apache, where www.example.com is your site domain name:

<VirtualHost *:80>
     ServerName www.example.com
     DocumentRoot /home/bitnami/apps/drupal/htdocs
     CustomLog /var/log/apache2/example-access.log combined
     ErrorLog  /var/log/apache2/example-error.log

     php_value memory_limit 256M
     php_value upload_max_filesize 128M
     php_value post_max_size 128M
     php_value max_execution_time "360"

     FileETag ALL

     <Directory /home/bitnami/apps/drupal/htdocs>
         RewriteEngine on
         RewriteBase /

         RewriteCond %{REQUEST_FILENAME} !-f
         RewriteCond %{REQUEST_FILENAME} !-d
         RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

         Options -Indexes
         AllowOverride All

         # Follow symbolic links in this directory.
         Options +FollowSymLinks

         # Customized error messages.
         ErrorDocument 404 /index.php

         # Set the default handler.
         DirectoryIndex index.php

         php_value magic_quotes_gpc                0
         php_value register_globals                0
         php_value session.auto_start              0
         php_value mbstring.http_input             pass
         php_value mbstring.http_output            pass
         php_value mbstring.encoding_translation   0

         # Requires mod_expires to be enabled.
         <IfModule mod_expires.c>
             # Enable expirations.
             ExpiresActive On
             # Cache all files for 2 weeks after access (A).
             ExpiresDefault A1209600
             # Do not cache dynamically generated pages.
             ExpiresByType text/html A1
         </IfModule>
         <IfModule mod_deflate.c>
         # Use mod_deflate to compress text content as required and supported by the client
         # Note that the frontend will automatically gzip content if supported using PHP functionality
         AddOutputFilterByType DEFLATE text/html text/javascript text/css application/x-javascript
         </IfModule>

     </Directory>

</VirtualHost>

<VirtualHost *:80>
    # Redirect non-www to www version of site
    ServerName example.com
    Redirect permanent / http://www.example.com/
</VirtualHost>

Add to /etc/apache2/sites-available/example.conf

Then, to enable:

sudo a2ensite example.conf
sudo service apache2 restart


Views and empty parameter in Path to link I know my title isn't explicit, but i will explain my problem. I created a view that displays me all documents(content) of my website, some documents are linked to a project(content) via entity reference, and in my view I display a link to a document. if there is a project the link looks like : node/100?project=5 . If there is no project the link needs to look like : node/100.

So in my view I added field excluded from display with the id of the project, and a second field which is the id of the node document and I rewrite the link  to :

node/[nid]?project=[field_doc_project]

My problem is: This works fine for document with projects only. good url: node/100?project=5 bad url, without project: node/100?project=.

Can I check in view if the project id exists and rewrite the url to node/100?

thanks

almost there,

add a link to the original content as a field, exclude it from display
add a path to the original content as a field, exclude it from display

rewrite the term reference to the full url you want to have using replacements [path]?something=[someid]

add a no results behavior and output the link from 1) [view_node]


Date module not showing Text with Date Popup widget I have enabled Date Module completely. But when I try to add Date field to my custom content type the widget has only two options "Text Filed" and "Popup Calendar". There is no third option "Text Field with Date Popup Calender"?

I think "Date Popup" module is not enabled. You have to enable it, then it shows the Pop-up calendar option in the select list.


having problem with db_or() and LIKE clause in drupal 7 I am trying to retrieve data from db with INNER JOIN.

I need the following query executed from drupal's db_select(), query is in normal format :

SELECT uo.* , uop.data FROM `uc_orders` AS uo
INNER JOIN `uc_order_products` AS uop ON uo.order_id = uop.order_id
WHERE (
  (
     uop.data LIKE '%mfp_donation%'
  )
  OR (
     uop.data LIKE '%scholar_donation%'
  )
  OR (
     uop.data LIKE '%reunion%'
  )
)

I already tried in drupal, the process is following :

$query = db_select('uc_orders', 'uo')
    ->fields('uo')
    ->fields('uop', array('data'));

$alias = $query->join('uc_order_products', 'uop', "uo.order_id = uop.order_id");

$order = $query->condition(db_or()
       ->condition($alias . '.data', '%mfp_donaiton%', 'LIKE')
       ->condition($alias . '.data', '%scholar_donaiton%', 'LIKE')
       ->condition($alias . '.data', '%reunion%', 'LIKE')
    )
    ->execute()
    ->fetchObject();

All the process is working fine, but the problem is when i execute/fetch the results then i only get the output for ->condition($alias . '.data', '%reunion%', 'LIKE') . I mean i only get the %reunion% part. The first two conditions is not executing i think.

Any suggestion?

You can use dpq() to inspect your query.
Your query looks good, but I suspect that there's a small error in your condition. You put donaiton, shouldn't it be donation ?


Drupal Common's 3 How To Edit The Commons Browsing Widget Tabs? In Drupal 7 Common 3

Browsing Widget Tabs
https://drupal.org/project/commons_bw

Want to remove the Wiki's Tab
How can I do this please?

Many Thanks for your help

If you specifically need to remove the Wiki's Tab instead of turning off Commons Wiki module, none of the functions to override has been set up as a hook, as far as I can understand.

So even if the following method is not the best approach, you could make a very quick patch to commons_bw.module :

Into function commons_bw_get_tab_definitions($widget_type = 'group')

add unset($tabs['commons_wikis']); before return $tabs;

Of course you'll have to remember this whenever you update your Commons distrib...

See also this great post on how to add your own content type to the Commons browsing widget. This will give you a complete overview of what you can do


Development to staging to production process I am looking for suggestions on the right way of moving configurations and code from Dev to Staging to the Production environment for Drupal 8 Site. I also need to set up a Reference environment which will be a replica of the production environment but on a server with less resources.

I am using git for code, so it is an easy task to move code changes around.

The site is developed iteratively, hence I need to deliver content types, views and display in an iterative manner to the production site, which will have content already present based on the previous iteration.

I can see some documentation on this topic but all of them are about Drupal 7 or earlier versions.

Any help/suggestions or pointers will be appreciated.

This is a good start, drupal 8 has inbuilt configuration import/export functionality: https://www.drupal.org/docs/8/configuration-management/managing-your-sites-configuration

You could automate/speed up the process abit by adding the exported configs to your git repository and using drush to create them

But its especially: do an export on your dev which will generate config files all zipped up. Then do an import on production which allows you to review the changes before actioning them


Can I move distribution profile modules from profile folder to sites/all/modules? I just installed a distribution profile and ran Drush up to update modules.

I have some problems with the modules located at profiles/somefolder/modules: Drush moved out the old modules but no new modules are added.

Can I move the modules from profile folder to sites/all/modules?

The installation profile is Commerce Kickstart.

If the modules in question are not enabled you can move the modules.

The paths to their location in the system table in the database will be updated when you visit /admin/modules.

However, If they are enabled you may run into issues.

See http://drupal.org/node/183681


db_select doesnt work with me i've problem using db_select it return strange object instead of the result
here is the code

function _table_subscrib(){
  $result = db_select('user_company','uc')
->fields('uc',array('user_company_uid','user_company_nid','user_company_sub_number','user_co    mpany_date'))
          ->extend('TableSort')
         ->extend('PagerDefault')
         ->limit(50)
         ->execute();

$header = array('User Name','Company Name','Subscribtion Number','Date');

$rows = array();
while($data = $result->fetchAssoc());
{
    $rows[] = array(
        $data['user_company_uid'],
        $data['user_company_nid'],
        $data['user_company_sub_number'],
        $data['user_company_date']
    );
    drupal_set_message("ssdsd");
}

$output = theme_table(
            array(
                "header" => $header,
                "rows" => $rows,
                "attributes" => array(),
                "sticky" => true,
                "caption" => "",
                "colgroups" => array(),
                "empty" => t("Table has no row!") // The message to be displayed if table is empty
                )
            ).theme("pager");

return $output;

}

here is the object returned too

DatabaseStatementBase Object ( [dbh] => DatabaseConnection_mysql Object ( [shutdownRegistered:protected] => [target:protected] => default [key:protected] => default [logger:protected] => [transactionLayers:protected] => Array ( ) [driverClasses:protected] => Array ( [SelectQuery] drupal......

thanks

You set incorrect semicolon at the end, remove it: while($data = $result->fetchAssoc());

And next manner looks more clear, instead using while:

foreach($result as $data) {
    $rows[] = array(
        $data->user_company_uid,
        $data->user_company_nid,
        $data->user_company_sub_number,
        $data->user_company_date,
    );
}


Out of the several possible ways, what is the best practice for getting a field value for an entity? There are many different ways to get a field value from an entity.  For example, a text field:

$entity->get('title')->value;
$entity->get('title')->get(0)->get('value')->getValue();
$entity->get('title')->get(0)->getValue()['value'];
$entity->get('title')->first()->get('value')->getValue();
$entity->get('title')->first()->getValue()['value'];

And so on.

And then, depending on the entity, for the entity title (or name or label), you can sometimes do...

$entity->getName();

What is the best practice?  The first expression above (using the "value" property) is most concise -- are there any drawbacks to using it?

Is there any reason to prefer the first() helper instead of get(0)?  Why does the first() helper exist?  Are there cases when the first value in a field list doesn't have a 0 index?

There's likely no fast rule-of-thumb here because you're describing a few different things that will greatly depend on context (what entity, what fields?).

First, let's disregard ::getName(); it's a Taxonomy specific-wrapper around ::label() (whatever the entity has defined as its readable label in the entity definition it will return it). There's no such things a multiple labels so let's get to the main question being asked here: best practice on pulling field values.

It really depends on what you're trying to do.

If you look into ::get() method on the entity, you'll see its basically pulling data out of the internal $fields property which is is an array of objects that implement FieldItemListInterface. Classes that implement the interface supply the various get(), first(), getValue() methods that you can use when you're dealing with fields that may have one, none, or many values. They do extra overhead of checking for the existence of data or making sure it exists.

If you know for sure the data exists in your class you can skip the chaining of methods/properties and just get to the directly (e.g. $node->title->value), if not, these methods exists when you're dealing with uncertain structure in your entity/fields. Whatever the case, it depends on the specific entity class and the specific implementation of FieldItemListInterface to really decide what is best.


How to display the related node content in a block? How can I display the related content for a specific node (type product) in a block? I would like to display the image, title and a trimmed body of the related content (from the same company) at the end of the node.

You can use the Featured Content module for that.

Alternatively, you can also use the Views module by filtering your content using the node of the current page as an argument and using taxonomy or node reference to relate the content.


Show forms in a modal window I have a form and I am using Drupal 7. I need to show this form in a popup when a user clicks a link. The user should then be able to complete the form whilst in the pop up window. I can use anything like Colorbox or modals or anything. I just wanted to know which is the better option and what options do I have for Drupal.

There's 2 good options I know of currently: iframe (in colorbox for example) and CTools. Which option to use depends of the circumstances. I guess this information I found in the CTools modal.html file brings out the main difference:

  CTools provides a simple modal that can be used as a popup to place forms. It differs from the normal modal frameworks in that it does not do its work via an iframe. This is both an advantage and a disadvantage. The iframe simply renders normal pages in a sub-browser and they can do their thing. That makes it much easier to put arbitrary pages and forms in a modal. However, the iframe is not very good at actually communicating changes to the main page, so you cannot open the modal, have it do some work, and then modify the page.

I have no personal experienced with CTools on this subject so I can't add anything else to that, but I've implemented the iframe method in a couple of projects. In the most recent one I used the Colorbox plugin to show a few forms created with the Webform module in a popup.
I'll add some example code here in case there's some interest.

Link to the form:

'.t('Send message').'

Javascript code to open the linked address in a popup:

if ($('a.colorbox_form').length > 0) {
  var link = $("a.colorbox_form").attr('href');
  link = link.concat('?colorbox=true');
  // colorbox=true is attached for later use (read below).
  $("a.colorbox_form").attr('href', link);
  $("a.colorbox_form").colorbox({iframe:true, width:500, height:450});
}

In the theme template file:

function mytheme_preprocess_page(&$variables) {
  // Different template and additional stylsheet for colorbox content.
  if (isset($_GET['colorbox']) && $_GET['colorbox'] == TRUE) {
    $variables['theme_hook_suggestions'] = array('page__iframe'); // page--iframe.tpl.php
    drupal_add_css(path_to_theme() .'/iframe.css');
    $variables['styles'] = drupal_get_css();
  }
}

I attached 'colorbox=true' to the links using javascript so that users with javascript turned off would see the form with the normal template. The iframe template only has messages, title and content printed.

This already works, but I ran into a issue with Webforms: 'colorbox=true' wasn't preserved when the form got submitted. My attempt to fix it:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if (isset($_GET['colorbox']) && $_GET['colorbox'] == TRUE) {
    // The id-s of the forms that are possibly shown within a popup.
    $form_ids = array('webform_client_form_2', 'webform_client_form_4');
    if (in_array($form_id, $form_ids)) {
      $form['#submit'][] = 'mymodule_webform_submit';
    }
  }
}

function mymodule_webform_submit(&$form, &$form_state) {
  //drupal_set_message('
'.var_export($form_state['redirect'], TRUE).'
');
  if (!isset($form_state['redirect'])) {
    $form_state['redirect'] = array($_GET['q'], array('query' => array('colorbox' => 'true')));
  }
  else {
    $form_state['redirect'][1]['query'] = array('colorbox' => 'true');
  }
}


Disable the navbar in a Bootstrap sub-theme I've noticed that the Bootstrap Navbar, while behaving like the 'Main menu' is not available to be enabled and disabled from the blocks admin page, furthermore at the admin menu admin/appearance/my-bootstrap-subtheme/settings there aren't any options to disable it...

Is there a line or option that I can add to the file at...

my-bootstrap-subtheme/templates/page.tpl.php

...that would disable it?

Alternatively perhaps there is something that can be edited inside the (parent) bootstrap file...

bootstrap/theme/settings.inc

around line 105 that would add a 'Disable Navbar' option at admin/appearance/my-bootstrap-subtheme/settings ...

Incidentally where would I put this edited settings.inc file inside my subtheme directory?

Thanks.

So to add this as an optional setting we can look at how it's done for other navbar variables. For example the navbar positioning which is on line 112 of that settings.inc

  $form['components']['navbar']['bootstrap_navbar_position'] = array(

Let's see where the variables you can select in that are referenced, such as fixed-top. It's referenced in html.vars.php where they implement the hook_preprocess_html() function to take that selection using theme_get_setting('bootstrap_navbar_position') and create some related variables to pass into the classes_array for the html.tpl.php.

So you can create a similar field with options like enabled and disabled and pass that on to the page.tpl.php using YOURTHEME_preprocess_page (which would probably go in template.php) to create a variable like navbar_on when it's enabled

if (theme_get_setting('bootstrap_navbar_enabled') == 'true') {
  $vars['navbar_on'] = '';

 }

and then check in page.tpl.php to see whether or not that's true or not before printing the page.

     <?php if ($navbar_on): ?>
          NAVBAR CODE
     <?php endif; ?>

EDIT: actually maybe this is already in the theme, just not very clear
https://www.drupal.org/node/2287185


Change "From" element in drupal mail While sending registration success e-mail in Drupal system, I want to update "from" element.

Ex:
My admin e-mail is "hello@gmail.com".
While sending e-mail to user, I want to change it as "Myname <(hello@gmail.com)>"

Can we do it through hook_mail_alter?

I have tried below code. But din't work as expected.

function mymodule_mail_alter(&$message) {
 print_r($message); // I din't get any response here
}

Want to append Name before email ID.

Edit: hook_mail_alter its not triggering neither module nor template.php. Module is enabled. I have cleared cache too.

Existing comment : https://api.drupal.org/comment/59119#comment-59119

We can easily change the From with hook_mail_alter using 'from'
key from $message.

function mymodule_mail_alter(&$message) {
  $message['from'] = 'Your Name ('. $message['from'] . ')';
}

Also, Please check hook_mail function https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_mail/7 which needs to be written for your module and then you need to call drupal_mail function.

hook_mail_alter is just for modifying the variables passed to drupal_mail.


How to use drupal_add_library with a module? I'm new to Drupal and don't really understand how to set up drupal_add_library.

I've made a simple module that links out to a .js file. However, this .js file depends on a couple of generic functions. I've put this generic functions in a library and want to call them.

I've set up my code as such:

function products_preprocess_page(&$variables) {
  drupal_add_library($module, $name);
  drupal_add_js(drupal_get_path('module', 'products') . '/assets/myScript.js');
}

But am not sure what to put in $module and $name (I'm assuming name is the actual name of the .js you want to call from the library), or even if this is the right place to call it.

Can anyone point me in the right direction?

You can call it in that hook if you want it on every page (or add some logic to restrict the pages that it loads on), that's fine.
As per the API:

$module: The name of the module that registered the library.
$name: The name of the library to add.

If you're creating your own library, Jimmy Ko is correct: you need to declare it in hook_library.
Note that $name should exclude the file extension (e.g. .js)


How do I allow users to select published content on the site to be displayed on their profile page? I would like to have published content on my site which a user can select if he/she would like for it to be displayed within a block on their profile page.

For instance:

Published content is an article with image and body,
When the user is viewing this node there is a checkbox (or whatever that will work) that will say "Add To Profile".
If selected, then the content teaser will appear within a block on that specific users profile page.

I know how to get content that is created by a user to appear on that users profile, but I have been having difficulty getting this right.

PS: I know very little php, but know my way around Drupal.

You might want to look into the Flag Module.  It provides links on nodes that allow them to be tagged/flagged. Then, with Views, you can create a block that will be displayed on user profiles with content flagged by that user.  In fact, it comes prepackaged with a "bookmarks" view that might be a good starting point for this.


Exposing a type of field operation (flag lists) for search index view I installed the flag list operations module which gives me the ability to do operations on my views results. But this flag list operations doesn't show up on my search index view as seen below.

I'm sure there is some parameter or variable that is set in the flag list module that is preventing this operation to show up on the search index view.

What should I be looking for in the flag list module code to enable this operation to show up in the search index view?

Those flag list operations come from a Views handler; they're applied only to the node entity type in flag_lists_views_data_alter.

The Indexed node isn't a node entity, it's something specific to the search API module (added in search_api_views_views_data). It only contains fields that are indexed, plus any extra stuff search API or contrib modules add on.

I haven't tried it, but you may be able to include the nid in the index, and add a relationship in the View to Content. That would, in theory, give you access to everything that Views knows about for a node.

Failing that, you'll probably have to implement your own Views handler, implement hook_views_data_alter, and find the table whose field handler you need to override (it'll be search_api_index_MACHINE_NAME). The class in includes/flag_lists_handler_field_ops.inc would probably be a good template to start from.


How to override configuration variables in settings.php I need to override configuration variables declared in the settings.php. How this can be possible? Any help me on?

Note: I am trying to override a custom configuration variable, not any default one.

You can't overwrite the variables in settings.php.


Alter a module's setting I am using the Entity background module, which at the start of its .module file has a line which defines an image style constant.
define('EB_IMAGE_STYLE', 'large');

I don't want to use that image style, and I don't want to alter the original .module file.
I thought I could write a tiny module just to redefine that line, to alter it. After hours of trying to search for and understand hooks, I am no closer to a solution.
How can I correctly achieve what I want?

There is no need to programmatically alter it, as there is a configuration form that allows you to change it, the README.txt says

The image style used for the background image can be changed by going
to "admin/config/system/entity_background_image"

There is also a link to it in configuration


Constraint on paragraph field not working Here is a very simple code:
1-My constraint plugin (MyConstraint.php)
/**
 * @Constraint(
 *   id = "MyConstraint",
 *   label = @Translation("Never Validated", context = "Validation"),
 *   type = "string"
 * )
 */
class MyConstraint extends Constraint {
  public $message = "error %value";
}

2-My constraint validator (MyConstraintValidator.php) [=>addViolation in all cases]
class MyConstraintValidator extends ConstraintValidator {

  public function validate($items, Constraint $constraint) {
    dpm("I am displayed");
    $this->context->addViolation($constraint->message, [
              '%value' => 10
            ]);
    return;
}

3-My constraint added to my bundle
function mymodule_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle)
{
    if($bundle=='my_bundle'){
      $fields['my_paragraph_field']->addConstraint('MyConstraint', []);
    }
}

Result:
1-The dpm message 'I am displayed' is displayed
2-The entity is saved without any validation error
Notes:
-I have other constraints which are working well, If I test one of them (on my_bundle), the violation of this working constraint will be displayed but not the one with the code detailled here.
-The problematic constraint is added to a paragraph field... I suspect the problem is coming from there
-Nothing in the error logs.
I am looking for a hint to where to look.

On your addConstraint() your second parameter is an empty array - if you do not want to add any options leave that empty or use NULL