Commerce Module allowing user to customize product is drupal commerce able to allow user customization of products in the following way. Imagine your product is a bike.
You want your user to:

Change color of the bike (and therefore changing price, depending on chosen color)
Change wheel type (and therefore price)
Change type of break (brand for example)
Further, the individual product should be saved (cookie for example) and one should be able to share a link to the individual product (here I saw many examples where sharing the product does not work - because you will always go to the default product)

I was looking out there but could not find many shops that solve the descriped tasks.

I used commerce kickstart on simplytest.me - https://ds64.ply.st/tops/guy-short-sleeve-tee
to have a quick view. If I change the color, add it to the shopping cart, click on checkout and click on edit item again, I will end up at the standard configuration. Therefore the whole configurator does not make sense if I can not edit and save my individual customized product.

Nice to have a descriptive text that summerizes the chosen attributes and therefor for example a max. weight of the bike could be calculated...

Nike for example generates a url with a random id that can be used to share the customized product...

http://store.nike.com/us/en_us/product/air-max-95-id/?piid=40361&pbid=166815001#?pbid=166815001

Thanks for your aswers in advance!
Pedro

Yes, you can do something like this example:

https://drupalcommerce.org/videos/tutorials/customizable-products-pizza-store

Have to tweak a bit for the sharing part, probably would go with a custom module and hook_entity_view_alter() using the variables from the url to adjust for the specific changes.


Disable editing of post during update I would like to disable user access to the administration during updates, such as bugfixes and additions of new content-types etc. I'm not completly sure on how to achive this. What would be the best solution, setting the site in maintaince mode is not an option.

It sounds like you're running into a common deployment issue with Drupal: the fact that content and configuration reside in the same database. This generally puts a kink somewhere in most deployment strategies, as you start to run into issues whenever you have to merge existing user content (often a moving target) with upstream configuration changes.

Depending on how else you may have things set up, this may or may not involve drastic changes to your workflow, though this is the generally recommended solution for such issues. I'm not sure how much experience you have on these topics, so I'm going to break it down piece-by-piece for the benefit of anyone running into similar issues.

Dev/Test/Prod Workflow

Generally speaking, we have at least three servers in an optimal workflow. A "Development" server where our main version control repository lives (if you're not using one already, I highly recommend it!), a "Staging" server where we run our last rounds of acceptance testing and start adding default content, and a live "Production" server where everything is served to the end user.

Dev/Test/Prod in Drupal

As mentioned above, the fact that the database contains both content and configuration makes things quite messy. It's difficult to check a database into revision control, it makes configuration much less portable, and most attempts to decouple content and configuration are met with frustration (as with locking out certain privileges while making major updates to the site).

The adage "configuration moves forward, content moves backward" through the dev/stage/prod workflow still holds true as best practice with Drupal. We want to put as much configuration into code as possible, removing it from the database in an effort to decouple the two. This way, we can push features forward through the workflow as normal, and then take content from the live site and pull it back to dev when needed, without getting in the user's way.

Moving Configuration to Code

How do we move configuration to code, though? The Features module allows you to export the configuration of most popular modules to code as "feature modules"--in fact, anything that implements CTools Exportables is fair game. You could even add your own hooks to these exported feature modules and bundle them in an installation profile for one-click deployment (they're still just modules!).

In the rare cases where you can't achieve the desired functionality using Features alone and absolutely must hack at the database, you can do so through a custom module or an existing exported feature, using hook_install() and hook_uninstall(). hook_update_N() can be used for incremental updates, but remember to update hook_install() to reflect the same changes as well!

Moving Content

If required, content from staging can also be pushed to live using a solution like the Deploy module. This way, you can push updates from dev to staging, and then use maintenance mode on staging only when polished functionality is being pushed forward from Dev. You could also use it to push content from your live site back to the Dev server, to ensure that you always have easy access to the latest live content.

That said, now that configuration has been stripped out from the database, it becomes much easier to just move the database around as a content store, rather than a hodge-podge of content and configuration.

In Closing

This is a difficult and long-standing problem in Drupal, and doesn't have a quick fix, though I've used the above workflow on several projects with a high degree of success. I'd be happy to clarify any parts of my answer.


Create page with different content types This should be something simple but I didn't figure out how to do it. Let's say I have three different content types: Client information, client projects and client updates.

I would like to have a "New client" node that will automatically create the three above content types.

Is that possible?

Yes, you can use Node Reference field on the "Client" content type. So you can reference from this node to another node like the Client Information which belongs to this Client.

To show all information at once, you can set the Node Reference field on "Manage Display" to render the full node.


Conditionally register a user based on fields I have a Drupal 8 User registration form that has several text fields to gather information about the user.

I'd like to write a custom hook that examines the values in those fields and then either proceeds with the registration or 'cancels' it, like perhaps redirecting to a static page or displaying some static content.

What are the hooks I need to make this happen?  Do I alter the form?  Or do I hook an entity_presave function?

What do I need to do to cancel the default form processing or default entity presave/save routines?

thanks,

Forms have a validate and submit function(s). Submit never runs unless all validation passes.

So all you have to do is add a custom validation

/*
 * Implements hook_form_FORM_ID_alter
 */
function mymodule_form_user_register_form_alter(&$form, FormStateInterface $form_state) {

  $form['#validate'][] = 'mymodule_registration_validate';

}

/*
 * Custom Validation
 */
function mymodule_registration_validate(&$form, FormStateInterface $form_state) {

  $field_name = $form_state->getValue('field_name'); // Gets the value entered by the user
  // Note: depending on your field type & settings sometimes this value is an
  // array, so you may have to keep drilling down.
  if($field_name != 'Hello World') { // perform check
    $message = t('Only Hello World is allowed'); // message to display
    $form_state->setErrorByName('field_name', $message); // set error
  }

}

$form_state->setErrorByName will display an error message and highlight the offending field in red.

If  you want to redirect use $form_state->setRedirectUrl($url);


Uc_product module for drupal 7 not found In my Drupal 7 installation, i want to enable the ubercart feeds module but it says :"Requires: Uc_product (missing), Feeds (enabled), Chaos tools (enabled), Job Scheduler (enabled)" . The problem is i cannot find the uc_product module in the drupal website, or anywhere, any help?

The uc_product module is part of the Ubercart module.  Based on drupal-commerce you added as tag to the question, I assume you are using the Drupal Commerce module instead of the Ubercart module. In that case, uc_product wouldn't be useful, unless you switched over to using the Ubercart module.

The Commerce Feeds module would likely be more useful if you are really using the Drupal Commerce module.


Using Drupal.settings.basePath in Modernizer / yepnope.js loads I am currently starting development of drupal sites on Acquia. Using git and working locally is a new workflow for me. When building locally and trying to utilize  Modernizr load / yepnope, my JS in my script.js file typically looks like this..

Modernizr.load([
    {
    test: Modernizr.mq('only all'),
    nope: '/sitename/docroot/sites/all/themes/theme/js/libs/polyfill.js'
    },
    ....

So that works locally on my machine, but when I commit my changes and push to my acquia development server the file path for the loaded scripts is incorrect, since it's not the same setup I guess.

http://mysite.devcloud.acquia-sites.com/mysite/docroot/sites/all/themes/theme/js/libs/polyfill.js

It needs to be the below, without the mysite/docroot in the URL.

http://mysite.devcloud.acquia-sites.com/sites/all/themes/theme/js/libs/polyfill.js

So that brings me to Drupal.settings.basePath. If I print this out it gives me /mysite/docroot/ on my local setup. If I do it on the dev server, it would print out something different (probably just / ).

So me being the amateur assumed I could do something like this.. (forgive the poor sample, I know it can be done better)

var myroot = Drupal.settings.basePath

Modernizr.load([
{
test: Modernizr.mq('only all'),
nope: myroot + 'sites/all/themes/theme/js/libs/polyfill.js'
},
....

And this of course does not work. Just returns query1 is not defined.

So I am sure there are faults in many of my attempts to make this work.. so if anyone can suggest something to me, either workflow related or how to fix my setup / code, that would be great.

Thanks

Your local environment seems to be misconfigured. If you're running apache with vhosts then your VirtualHost definition should look like this:

<VirtualHost *:80>
  ServerName whatever-you-choose-for-a-dev-domain.com
  DocumentRoot "/path/to/the/drupal/root/directory"
</VirtualHost>

Where the DocumentRoot should also include /sitename/docroot

Alternatively you may be able to edit .htaccess in the Drupal root directory to
    RewriteBase /sitename/docroot
Which there should already be a commented definition of RewriteBase in there that you simply would uncomment. But I think the VirtualHost path would be the best one.


user_load() and EntityFieldQuery not found when running script via Drush I'm trying to run a php script from the command line via Drush. When I tried to use EntityFieldQuery...

$query = new EntityFieldQuery;

I got the error:

PHP Fatal error:  Class 'EntityFieldQuery' not found in /path/to/my/script.php on line 43

So, I tried to make it even simpler, and just used this script:

<?php

print "inside script\n\n";
$user = user_load(1);
print "name: ".$user->name;

?>

But I get the error:

PHP Fatal error:  Call to undefined function user_load() in /path/to/my/script.php on line 17

It doesn't appear that drush is bootstrapping properly. Am I missing something? What do I need to do for drush to be able to use the drupal apis?

I read through Drush php-script | Drupal functions such as node_load() are not being found, but I've got mysql client libraries already installed so that isn't a solution for me.

Ok, WOW, I found the error by running my script with the -d option:

drush -d scr /path/to/my/script.php

I noticed in the log it spewed out that it was getting an error connecting to the database. I apparently had messed up the privs when I set them up. I regranted the privs and my script ran just fine.

The error message about not being able to find a function was a total red herring.


jQuery detect submit on form problem I'm trying to detect when a form is submitted so I have written this code:

jQuery('#formid').submit(function(event){
        console.log('submit handler');
})

But nothing happens and the form is submitted normally. The form is rendered as usual and the submit button is generated with this code:

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Enviar'),
    '#attributes' => array('class' => array('btn','pull-right')),
    '#ajax' => array(
        'callback' => 'contact_form_ajax_submit',
        'wrapper' => $result_wrapper,
        'progress' => array(
          'type' => 'none',
          'message' => NULL,
        ),
    ),
  );

I don't know why my jquery script doesn't intercept the submit. I've checked the form id (obviously) so I ask for help because I have no idea about what could be the problem.

Thanks

Link: http://seminolaproducciones.com/contacto

For normal forms you need bind submit event handler to the form, something like below as Baysaa said,

jQuery('#formid').submit(function() {
  console.log('submit handler');
  return false;
});

However For Drupal AJAX forms this wont work, Because Drupal AJAX forms are submitted by Drupal in a different way when the submit button is clicked, So you need to just bind the click event to the submit button to detect the form submission, Something like below,

jQuery('#submit-form').submit(function() {
  console.log('Form is being submitted');
});

Here the restriction is you cant prevent form being submitted, even if you put return false in you custom click handler.


Webform token for select field value (not key) I have a webform select field called tour and I have set up an email to go out, using the default template:

Submitted on [submission:date:long]
Submitted by user: [submission:user]
Submitted values are:
[submission:values]

The results of this submission may be viewed at:
[submission:url]

When the email goes out, it sends the key (nid):

Tour: 8349

rather than the value of the option:

Tour: 10-Jan-16 - Awesome Tour

I have tried the following tokens:

[submission:values:tour:label]
[submission:values:tour:value]
[submission:values:tour:withLabel]

I am looking for the proper token to output the value in the key/value pair of a select field.

For the tour field, I am replacing the options via a hook. I only mention this step for completeness sake as I don't think it has any impact on my issue.

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'FORM_ID') {

    // get all tours
    $query = db_select('node', 'n');
    $query->fields('n', array('nid', 'title'));
    $query->condition('n.type', 'tour');
    $query->join('field_data_field_tour_type', 't', 't.entity_id = n.nid');
    $query->fields('t', array('field_tour_type_value'));
    $result = $query->execute();

    // group by tour type
    $options = array();
    while ($row = $result->fetchObject()) {

      // tour type 1
      if ($row->field_tour_type_value == 1) {
        $options['Type 1'][$row->nid] = date('d-M-y', strtotime($row->field_event_date_value)) . ': ' . $row->title;
      }

      // tour type 2
      else if ($row->field_tour_type_value == 2) {
        $options['Type 2'][$row->nid] = date('d-M-y', strtotime($row->field_event_date_value)) . ': ' . $row->title;
      }
    }

    ksort($options);

    // set the tour options correctly
    $form['submitted']['tour']['#options'] = $options;
  }
}

It turns out the issue was with the form alter hook. I had updated the #options which made the form work just fine, however I needed to update the webform component with a line delimited list of key|value pairs.

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'FORM_ID') {

    // get all tours
    $query = db_select('node', 'n');
    $query->fields('n', array('nid', 'title'));
    $query->condition('n.type', 'tour');
    $query->join('field_data_field_tour_type', 't', 't.entity_id = n.nid');
    $query->fields('t', array('field_tour_type_value'));
    $result = $query->execute();

    // group by tour type
    $options = array();
    $flat_options = array();
    while ($row = $result->fetchObject()) {

      // tour type 1
      if ($row->field_tour_type_value == 1) {
        $options['Type 1'][$row->nid] = date('d-M-y', strtotime($row->field_event_date_value)) . ': ' . $row->title;
        $flat_options .= $row->nid . '|' . date('d-M-y', strtotime($row->field_event_date_value)) . ': ' . $row->title . "\n";
      }

      // tour type 2
      else if ($row->field_tour_type_value == 2) {
        $options['Type 2'][$row->nid] = date('d-M-y', strtotime($row->field_event_date_value)) . ': ' . $row->title;
        $flat_options .= $row->nid . '|' . date('d-M-y', strtotime($row->field_event_date_value)) . ': ' . $row->title . "\n";
      }
    }

    ksort($options);

    // set the tour options correctly
    $form['submitted']['tour']['#options'] = $options;
    $form['#node']->webform['components'][7]['extra']['items'] = $flat_options;
  }
}

I've added the $flat_options variables to handle this and assigned it to the proper field in my form array. Keep in mind referencing the component by number [7] is not the cleanest and most maintainable way to do this but it works in a pinch.


REST GET ResourceResponse returns encoded json I have a decoupled drupal project with an angular 5 front end that is utilizing a restful api to store data.  Because this API needed a key that we didn't want to expose we have created a restful endpoint in the Drupal code that acts as a sort of proxy.  The front end hits Drupal, Drupal adds the key, hits the api, and then Drupal returns the api's response to the front end.

When I hit the API directly, I get clean JSON:

{"total":610,"results": .....

But when I use the proxy, I get encoded json:

"{\u0022total\u0022:610,\u0022results\u0022:[{\u0022_id\u0022:\u .....

My Angular request:

get(): Observable<RecipePreview[]> {
    let encryptedAuthorizationString = 'BLAHBLAHBLAH';
    const headers = new HttpHeaders()
        .set("Content-Type", "application/json")
        .set("X-CSRF-Token", this._HttpServiceService.csrfToken)
        .set("Authorization", "basic " + encryptedAuthorizationString)
    ;

    let u = this.filter.url();

    return this._http.get(u,{headers})
        .map(res => {
                return res;
            }
        )
    ;
}

The Drupal RESTful endpoint code looks like this:

/**
 * Responds to entity GET requests.
 * @param $data
 * @return \Drupal\rest\ResourceResponse
 * @throws \GuzzleHttp\Exception\GuzzleException
 */
public function get() {
    $url="BLAHBLAHBLAH";

    $client = \Drupal::httpClient();
    try {
        $request = $client->request('GET', $url, [
            'headers' => [
                'Content-Type' => 'application/json',
                'apikey' => "BLAH-BLAH-BLAH"
            ],
        ]);

        $file_contents = $request->getBody()->getContents();
    }
    catch (RequestException $e) {
        //An error happened.
        $file_contents = "There was an error.";
    }

    \Drupal::logger('Proxy API')->debug($file_contents);

    return new ResourceResponse($file_contents);
}

I'm pretty sure that ResourceResponse is doing something to the json, and there has got to be a way to tell it to not do it anymore?  But how?  Thoughts?

I'm also using the same final end point in a drupal content migration from source and I believe this formatting is causing issues with that as well.

Thanks so much for helping me out with this!

Kevin was on to it.  It was being double encoded.  I have to return a response, so I decode the results from the first api, then return it as a json response:

return new JsonResponse( json_decode($file_contents) );


Using Feeds importer to import separate urls to same content-type I'll try to parse out my problem laconicly:

I've two separate urls formatted as csv files that I want to import to the SAME content-type.

I'm using the same Feeds importer to accomplish this task, using the same unique identifier to import each url and update/overwrite all existing nodes.

Yet, for some reason I'm still getting new nodes when I should be getting updated nodes.

I have no clue where the process could be going wrong hence my post herein. Any help would be most emphatically appreciated.

David

If you don't find a direct solution to this issue, try set an unique field on the content type instead and use that instead of an UUID. Have a look at Support unique targets in mappers


How do I add an image for each menu column? I have 4 columns in the footer, and am displaying a different menu in each block(column). I would like to add an image above the menu items for 3 out of 4 menus. What is the best way to do this? Is it possible to add a field to the menu content type as such? If this was possible I could then create a view for each block/column, by pulling in the menu items and images...

What would be the best way to do this?

It's pretty easy to do that with CSS

#column-1{
  padding-top:20px; /* Space for image */
  background: transparent url('../images/bg-col-1.png') no-repeat left top;
}


Nesting of tabs within quicktabs is it possible to create new tabs and place them under quick tabs, i.e, i want to create two new quick tabs and add them under (nesting structure) already existing three quick tabs...How can i achieve this

If I understand your request well, I think this is the solution supplied by @monymirza. But in the latest stable version of quicktabs you have the possibility to select quicktabs to be show under a tab.

Checkout this image to see : (ab is a quicktab instance that has been created earlier, and c is the parent tab that will contain ab)


How to define specific page on hook_page_top? I want to add some stuff to the top of the page on certain pages.

How can I specify which pages that my custom content should be included on?

You can use the request object to figure out what page you are on and what to do with it.

Fx

$uri = \Drupal::request()->getRequestUri();

Maybe you want to get the route name instead:

$route = \Drupal::routeMatch()->getRouteName();

From there it's just a matter of defining your conditions in the hook.


Can uploaded files be renamed in the server to avoid name collision? I want my site to host some images. The user is able to upload images as a content type.

If two users create content and upload images with the exact same name (myImage.png), will the older image file be overwritten in the server (and therefore both content entries would end up with the same image file)?

If yes, it is rather troubling. So now I wonder: is there a module that renames the uploaded file so it will not collide with other uploaded files?

I have searched for a couple ones, not exactly tested them since they seem to add too much extra functionality I just don't need: I like the default file uploading system that comes with Drupal 7. I just want it to avoid name collisions (if it happens).

You don't need to worry about the renaming of the images; Drupal does that for you by default :)
Lets say if you upload image1.jpg, and again someone else does the same the second file will be renamed image1_0.jpg.


view infinite scroll: how to exec a js function after loading items ? I have the module "views infinite scrolling" installed on my site and it works. Now I want to exec a function when all loaded (Via ajax) items are loaded and showed to the user. How can I do this ? Thanks.

You should be able to use Drupal JS Behaviors. Views Infinite Scroll should fire off Drupal behaviors on an AJAX request. You would need to add custom JS to your pages that use infinite scrolling.

Here's an example where someone uses this to add a class to views rows loaded from Views Infinite Scroll.

Drupal.behaviors.myBehaviorName = {
  attach: function (context, settings) {
    // run your code here
  }
};


Trying to get property of non-object in i18n_langcode() (line 229 of i18n.module) and a bunch of other property of non-object notices Recent logs lies to me.

I even did a dpm($node->title); with devel and indeed it's there.

I have like 6 pages of these notices that appear per page load. They are all different locations but they all have the same error type, property of non object. Has anyone experienced something like this?

I don't think it's a hack, at least not a Core hack, cause Core has been updated several times.

Ugh, soo strange.

This is hard to debug, here is another example

As you can see, I created a variable $test = i18n_language()->language and xdebug tells me $test = "en" yet on line 230 it fails to get the value according to the log.

Finally solved this mystery.

I was able to narrow it down to a bean block in the site's footer. Upon inspecting all of the bean's block display fields

Disabling this field fixed the issue. Where is it coming from? IDK yet. I will update once I know. Seems like custom module.

Update

Yep, turns out Featurette image link is coming from a custom module. Notice the big error in line 24 and line 30.

More errors here, what a mess!


Displaying the parent term first in Views I have managed to create to organize my content using the Taxonomy module, it is 2 levels deep.

Level 1
    > Level 1-a
        > Level 1-a-i
    > Level 1-b
        > Level 1-b-ii
Level 2
    > Level 2-a
        > Level 2-a-i
Level 3
    > Level 3-a
        > Level 3-a-i

I display this using the Views module.
But the problem I am facing is that the view displays all terms,

Level 1
Level 1-a
Level 1-a-i
Level 1-b
Level 1-b-ii

What I am trying to achieve on this view is something like this

Level 1
Level 2
Level 3

And then when the user clicks a level it will display child, until they reach the deepest level of the taxonomy

Level 1-a
Level 1-b

and then for example selecting Level 1-a

Level 1-a-i
Level 1-a-ii
Level 1-a-iii

The Views Tree module might be what you're after.


hook_filter_info langcode is always und I am trying to filter text and the result replace depends on the language of the node.
The filter process callback function accepts $langcode argument but it always pass as "und".
If I could access the Entity object to check it's langauge that would be perfect.
I've tried to understand where the "und" value comes from and understand that it's from the field settings.
Currently I'm getting the language code from the active $language object and in order to filter per language I set the filter cache to FALSE and I don't wanna do this.

How can I overcome this problem?

Thanks,
Bnaya

The process callback is generally called from the check_markup() function.

That function blindly passes the $langcode value through to the process function, so it is up to the caller of the check_markup() function to send through the appropriate language.

You can see the list of functions that call check_markup() here.

The main one that you will encounter would be the text module's _text_sanitize() function, which is what formats the text for text fields that user input filters.

As you can see, it also passes through the language of the field.

Going up another level we have hook_field_load(), which also passes through the langcode.

Back again we get field_attach_load(), which calls hook_field_load() via _field_invoke_multiple().

All these are passing through langcode.

field_attach_load() is called by all these functions.

So basically you can scour the API site and see that is calling check_markup() in your case and see why there is no langcode being passed in.

Alternatively, you can install the devel module and put

dpm(debug_backtrace());

in your format process function.

Then load the page where your text is printing out and you will get a backtrace on the screen.

The backtrace will give you all the functions that have been called to get to your code. It shows you all the parameters that have been passed into function along the way.

This way you can more quickly isolate the point where the language becomes LANGUAGE_NONE (UND) - In theory :)


Off canvas dialog using a button I am trying to adapt the relatively new off canvas dialog introduced in Drupal 8.5.

It is suggested to use it with the Drupal Form-API and a link element like this:

$form['off_canvas'] = [
  '#title'      => 'Some title',
  '#type'       => 'link',
  '#url'        => \Drupal\Core\Url::fromRoute('some route'),
  '#attributes' => [
    'class'                => ['use-ajax'],
    'data-dialog-type'     => 'dialog',
    'data-dialog-renderer' => 'off_canvas',
    'data-dialog-options'  => \Drupal\Component\Serialization\Json::encode(['width' => '40%']),
  ],
  '#attached'   => [
    'library' => [
      'core/drupal.dialog.ajax',
    ],
  ],
];

This works pretty straight forward and out of the box, but for a very special use case I need to attach an AJAX-callback with a button element which is not possible using a link element when looking at the Drupal form API specifications.

This is what I got trying to use a button element and a callback with off canvas dialog functionality:

$form['some_button'] = [
  '#type'     => 'button',
  '#value'    => 'some value',
  '#attached' => [
    'library' => [
      'core/drupal.dialog.ajax',
    ],
  ],
  '#ajax'     => [
    'callback' => '::some_callback',
  ],
];

Callback function goes here:

public function some_callback(&$form, FormStateInterface $form_state) {

  $response = new \Drupal\Core\Ajax\AjaxResponse();

  $title = 'Some title';

  $content = '
Some content
';
  $options = [];
  $response->addCommand(new \Drupal\Core\Ajax\OpenOffCanvasDialogCommand($title, $content, $options));
  return $response;
}

The funny thing is: once the off canvas dialog is initialized using $form['off_canvas'] it works on both elements for $form['off_canvas'] and $form['some_button']. On pageload it uses the old dialog for $form['some_button'] and the new off canvas dialog for $form['off_canvas'].

So this must be an initialization problem for $form['some_button]. But I can not get this to work with the off canvas dialog at pageload and documentation for the new off canvas functionality is quite rare.

I tried to tell $form['some_button'] to use off canvas as a parameter in a lot of ways, but it does not work. I guess I missed something here.

Can you guys give me a hint how to make this work from the very start using a button with an Ajax callback?

When getting back to this issue I did notice the strange behaviour is gone after upgrading to the latest Drupal 8.6.3. All works as expected even using a button.

I am not able to reproduce the behavior/error from above.


How to populate a node reference field based on the selected taxonomy term? I have two content types and one vocabulary:

Service Categories - different categories of jobs. (VOCABULARY as the list is small and does not change)
Service Tasks - tasks that relate to an individual category
Services - record consisting of details related to a service performed

On the services page, I have a have a term reference field that allows the user to select the category of service.  Below that I have a node reference field that I would like to have populate the related task from which to choose once the category has been selected.

Without involving programming, is there a solution to my problem?  I am new to Drupal (using version 7) but am picking up the concepts quickly.

I would accomplish this by arranging your vocabulary like so:

Category 1

Task 1

Task 2

Category 2

Etc.

I would probably just name it Service Tasks, but that's my preference. Then use the hierarchical select module.

Enable the module and it's Taxonomy Select sub-module, then add a term reference to Services using the hierarchical select widget. Now you can choose tasks related to their parent categories without having to make all sorts of references.


403 Error - Unable to create Paragraphs via REST with ?_format=hal_json Trying to add paragraphs via REST to the earlier created node.
I've installed the Paragraphs Type Permissions module, enabled the following permissions for my REST user's role

Text: Create content
Video: Create content

See: https://www.drupal.org/project/paragraphs/issues/3012600#comment-12851834
but still getting an error 403 and {"message":""} in response while trying to add some paragraphs to the node created earlier.
Error log:
Type        access denied
Date        Monday, December 28, 2020 - 20:40
User        restadmin
Location    https://drupal-8.site/entity/paragraph?_format=hal_json
Referrer
Message     Path: /entity/paragraph?_format=hal_json. Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException: in Drupal\Core\Routing\AccessAwareRouter->checkAccess() (line 120 of /var/www/core/lib/Drupal/Core/Routing/AccessAwareRouter.php).
Severity    Warning
Hostname    77.139.170.139
Operations

Here JSON for the Text Paragraph:
   {
        "field_text": [
            {
                "value": text,
                "format": "full_html",
                "processed": text
            }
        ],
        "parent_id": [
            {
                "value": str(parent_id)
            }
        ],
        "parent_type": [
            {
                "value": "node"
            }
        ],
        "parent_field_name": [
            {
                "value": "field_paragraphs"
            }
        ],
        "type": [
            {
                "target_id": "text"
            }
        ],
        "_links": {
            "type": {
                "href": base_url + REST_TYPE_PARAGRAPH_TEXT
            }
        }
    }

Here JSON for the Video paragraph:
{
        "field_video": {
            "value": "video:" + str(video_id)
        },
        "parent_id": [
            {
                "value": str(parent_id)
            }
        ],
        "parent_type": [
            {
                "value": "node"
            }
        ],
        "parent_field_name": [
            {
                "value": "field_paragraphs"
            }
        ],
        "type": [
            {
                "target_id": "video"
            }
        ],
        "_links": {
            "type": {
                "href": base_url + REST_TYPE_PARAGRAPH_VIDEO
            }
        }
    }

What permission am I missing here?

Check on permission Paragraphs Type Permissions -> Bypass Paragraphs type content access control was missing here.
There was also a problem with the JSON request payload of the video paragraph, here the correct version:
    {
        "field_video": [
            {
                "target_id": video_id
            }
        ],
        "parent_id": [
            {
                "value": parent_id
            }
        ],
        "parent_type": [
            {
                "value": "node"
            }
        ],
        "parent_field_name": [
            {
                "value": "field_paragraphs"
            }
        ],
        "type": [
            {
                "target_id": "video"
            }
        ],
        "_links": {
            "type": {
                "href": base_url + REST_TYPE_PARAGRAPH_VIDEO
            },
            base_url +  REST_RELATION_PARAGRAPH_VIDEO_FIELD_VIDEO: [
                {
                    "href": base_url + "/media/%d/edit" % video_id + FORMAT_HAL_JSON,
                    "lang": "en"
                }
            ]
        }
    }

And a correct/working version of the text paragraph JSON payload:
    {
        "field_text": [
            {
                "value": text,
                #"format": "full_html" - getting error "full_html" not recognized
            }
        ],
        "parent_id": [
            {
                "value": str(parent_id)
            }
        ],
        "parent_type": [
            {
                "value": "node"
            }
        ],
        "parent_field_name": [
            {
                "value": "field_paragraphs"
            }
        ],
        "type": [
            {
                "target_id": "text"
            }
        ],
        "_links": {
            "type": {
                "href": base_url + REST_TYPE_PARAGRAPH_TEXT
            }
        }
    }


How to create an Ubercart add to cart button programmatically with defaults? I am able to create an add to cart button:

$nid = 27;
$node = node_load($nid);
$add_to_cart = array(
    '#theme' => 'uc_product_add_to_cart',
    '#form' => drupal_get_form('uc_product_add_to_cart_form_' . $nid, $node)
);
return drupal_render($add_to_cart);

This gives me an add to cart button, but with no attributes selected. How can I alter this code to allow for the defaults to be set to specific values. For example, if I have an attribute with aid = 1, called "action", and two possible value... oid = 3 = register ... and oid = 4 = transfer..... of which I want the default to be "transfer" for example?

I managed to use cart links instead:

/cart/add/p27_a6osfsdfsdfsdf_a7o706_a2o8_a1o515_q1-idomainName?destination=cart


How to translate strings in (programmatically created) custom module? I've (programmatically) created a custom module which includes a block with a string wrapped in the $this->t() function. How or where can I extract this translation file?

In Drupal 7 I would extract a translation file of the custom module, but the POTX module is not ported to Drupal 8 yet.

public function build() {
  return array(
    '#markup' => $this->t('How and where can I translate this string?'),
  );
}

Potx is not yet ported to Drupal 8 but it can parse Drupal 8 modules.

You can install it as a drush command instead of a drupal module and then it should work fine on your Drupal 8 module.

What that doesn't support yet is extracing existing translations from a running site. Looks like people are working on a port in https://www.drupal.org/node/2356469 which supports that.


How do I open a custom module ajax form in colorbox popup? How do I open a custom module AJAX form in colorbox popup using button click?

If you output your form hidden in the html, you can pop it up with colorbox_inline.

If your form lives in a menu callback and has a path, you can put a rendered link to your page everywhere and it will open modal with colorbox_load - see also ng_lightbox, if you put your path in it's config.


Hiding full node display and URL This is very similar to How do I hide nodes that shouldn't be directly accessed from users and search engines?

I would like to:

Not have certain nodes be directly accessible at the full URL (ie. at node/1234 or its alias), since they're being used in a view
Make sure they're not being indexed in search engines

My questions are:

Does marking a node as "unpublished" have any side effects? other than viewing the node (assuming you're an admin) and seeing the node as unpublished
Marking a node as published yields a 401 when its viewed (at its full URL) by anonymous users. Does the page still get crawled? Is there a way to redirect the 401 and not get hurt from a SEO perspective?

EDIT: Using Drupal 7.

Thanks!

One of the biggest changes at the architecture level of Drupal 7 is the introduction of entities as an abstraction for content. The old days of trying to cram everything in nodes is over. In short, you get all of the convenience of nodes without the overhead and unnecessary code (and in your case, the architectural challenge of "hiding" nodes from users, crawlers).

Drupal Commerce uses them for products. This allows the products themselves to be inaccessible to end users, but attached to the product displays and views for the end user to see and purchase.

Utilize the Entity Construction Kit (ECK). It will give you a nice UI to create your entities and then just use views to display them for the end-user.


How to hide /node/ , /taxonomy/, /mymodule/, etc., from the URL path I have the module Path auto installed. I would like that the user could not access the content by the URL http://www.myexample.com/node/7 and instead would have to follow the menu and other webpage links with its alias. So if I forgot to set an alias for a content, I will be redirected to 404 or home page. The goal is to protect the "real" URLs which Drupal generates when creating content via admin and modules.

If you set the patterns for a content type on URL aliases. You get the "Generate automatic URL alias" So you never get the node/* urls on that content type.

You find the URL aliases section on your configuration page.
Patterns is a tab there.


Preventing a block's custom template file from being cached I have built a module that needs to provide a small piece of dynamic content on every page load of a certain content type. It works great, however the section of code I provided is always cached in Drupal theme registry (it seems). The Variables I need generated on each pageload are "$userpicturepath" and "$variables['userfullname']" How do I prevent this from being cached? For completeness, here is my module's code:

subscribe_blocks.module

//implementation of hook_block_info
function subscribe_blocks_block_info() {
    $blocks['author_subscribe_block'] = array(
        'info' => t('Author Subscribe Block'),
        'cache' => DRUPAL_NO_CACHE,
    );
    return $blocks;
}

//implementation of hook_block_view
function subscribe_blocks_block_view($delta = '') {
    switch ($delta) {
        case 'author_subscribe_block':
            $blocks['content'] = theme('subscribe_blocks_block');
            break;
    }
    return $blocks;
}

// Implementation of hook_theme
function subscribe_blocks_theme(){
    if ( arg(0) == 'node' && is_numeric(arg(1)) ) {
        $node = node_load(arg(1));
    }
    $user_fields = user_load($node->uid);

    return array(
        'subscribe_blocks_block' => array(
            'template' => 'subscribeblocks',
            'variables' => array(
                'userfullname' => $user_fields->field_name['und'][0]['safe_value'],
                'userpicture' => $user_fields->picture->filename,
                'userfields' => $user_fields,
            ),
        ),
    );
}

subscribeblocks.tpl.php

<?php
drupal_page_is_cacheable(FALSE);

if ($variables['userpicture'] != NULL){
    $userpicturepath = 'sites/example.com/files/styles/user_profile/public/pictures/' . $variables['userpicture'];
} else{
    $userpicturepath = 'https://someimgurl';
}
?>

                <img src=<?php echo $userpicturepath; ?> class='subscribeuserpic' >

Never miss another story by <?php echo($variables['userfullname']); ?>. Subscribe today.

                    <?php
                    $block = module_invoke('webform', 'block_view', 'client-block-5401');
                    print render($block['content']);
                    ?>

I'm using Drupal 7, have all other caching turned off (for now), and have tried using several modules including CacheExclude (https://www.drupal.org/project/cacheexclude) and Ajax Blocks (https://www.drupal.org/project/ajaxblocks).

Probably not the best way to do this, but I was able to overcome this by rebuilding the theme cache when this block was run using:

<?php
drupal_theme_rebuild();

I'd love if someone could help with a better answer though!


Blocks per user setting/individual I am having my navigation links in my utility bar which is in a block named 'tray'; however, some users prefer to have the navigation links in the normal position and that is in a side panel inside a block named 'second sidebar'.

How can I make it so that the users can choose on their profile to either use the utility bar and navigate from there, or leave it as it is and have the links in the sidepanel.

Update: I mentioned panels, but it should have been blocks.

You can add per user preference settings. Check this for a working example of how to add a preference setting in the user profile form and how to store and read it.


How to remove 'None' from forum options? In D7 advance forum, when users want to create a forum thread at node/add/forum, they are presented with a dorp-down menu fo froum whose default is set to .

So when users do not choose an existing forum from the menu, their thread is just added to 'None' forum, which is so bad. I need frequenty to remove these 'none' forum threads.

So I'm wondering how remove this  option or otherwise solve this problem?

The forum is set as a taxonomy reference in the field list of the content type 'forum post'.

Can you not just set it to be a compulsory field at /admin/structure/types/manage/forum

This way if somebody entered a blank value it would reject the answer and ask them to resubmit, which works better than the default being one of the forums, in which case lots of topics still end up in the wrong place.

The only thing I'm confused by is that I thought this was the default setting for Drupal's inbuilt forum content type anyway? Buy maybe I'm wrong on that.


$drupal_hash_salt is empty in my installations This is the code in settings.php

$drupal_hash_salt = '';

From what I know it should be a random string and I shouldn't change it at all and it has a direct effect on the website security. But why this variable is empty? Is there any problem and what should I do to assign a string to this variable?

The hash is used to salt things one-time links and forms tokens, it filed usually by the installer.

You can add your own salt here, basically any random string or even replace it with the content of a file (see the documentation in the default.settings.php).

If this variable is empty, a hash of the serialized database credentials will be used as a fallback salt (though you have to add it manually if you have a database cluster).

This is function used as a fall back if there is no salt drupal_hash_salt

function drupal_get_hash_salt() {
  global $drupal_hash_salt, $databases;
  // If the $drupal_hash_salt variable is empty, a hash of the serialized
  // database credentials is used as a fallback salt.
  return empty($drupal_hash_salt) ? hash('sha256', serialize($databases)) : $drupal_hash_salt;
}


Why can't I override my views theme template files? I am using D7. I am using one of the template file names suggested in the theming information in the view. Putting that template file in my theme templates folder. saving it and clearing the cache. The .tpl.php does not seem to be recognized and/or overwrite the default file. What am I doing wrong?

Be sure you use the Rescan button in the Theme: Information dialog. Also, be aware that pasting names not carefully enough can put white space in front of the file name. You wont see the spaces in FileZilla or TC, but it can leave your file unrecognized. So watch out when pasting.


How can I run PHP code without writing a module? I need to attach a field to some bundles. A PHP snippet will do the job for me, so I don't need a module.The below snippet is what must be executed :

$field_name = 'field_custom_image';
// Create the field.
$field = array(
  'field_name' => $field_name,
  'type' => 'image',
);
field_create_field($field);

and then the snippet to add this field to bundle :

// Create the instance.
$instance = array(
  'field_name' => $field_name,
  'entity_type' => 'node',
  'bundle' => 'article',
  'label' => 'Image',
  'description' => 'An image for the article.',
  'required' => TRUE,
);
field_create_instance($instance);

Is there a way to run PHP code directly in Drupal, without the need to write a module, install it, make it run, and uninstall it?

Yes, there is, but given your description I wonder if it will help you:

Install module Devel
Go to http://yoursite/devel/php
Enter your code and execute it.


How do I fix a site after I removed a module? I deleted a module without disabling and uninstalling it first.  Now I just get a blank white screen, but I don't see any error messages.  What can I try to fix this?

Run the following query.

select info from system where name = 'module_name';

You will get a blob. Within this blob look out for text after version. You can find the version of the module here.

Download this version of the module. Place it in sites/all/modules folder(you can also find out the previous location from the file-name field in system table), uninstall the module. Now delete the module.


Adding Class to views row if View style is Unformatted list / Content I need to add a CSS class to a views row depending on a field. So far this is easy going if I use Fields as Content (add class via replacement patterns then).

But I find it far more difficult to do this when using Row style "Content" and a custom view mode (e. g. Teaser).

I found the following code to work for me if I use Row style "Content":

function mytheme_preprocess_views_view_unformatted(&$vars) {
foreach($vars['view']->result as $rkey => $rval)
{
    $node = node_load($rval->nid);
    if(isset($node->field_breite) && !(empty($node->field_breite)))
    {
        $vars['classes_array'][$rkey] .= $vars['classes_array'][$rkey] . " " . $node->field_breite[LANGUAGE_NONE][0]['value'];
    }
}

}

I like to ask if this is a suitable approach or am I maybe wasting resources by loading each node and can I grab the node data easier somewhere else?

PS: It is not a option for me here to use Fields in the View as content because I want to use different content types in the view with different fields.

Settings:

You can try do this later in process or template, when the $vars['rows'] is flattened. You can pull all instances of field_breite out of the flattened row and put them into the classes of the row. For this the field_breite has to be in the custom view mode of course. This would be not so nice for coding, but much faster.

I would code it like this in mytheme_process_views_view(&$vars), but I'm sure you need some debugging:

Go row by row in $vars['rows']. Search the complete field with preg_match() by using the html tags of the field and set parenthesis in the regular expression to get the field value in $matches[1]. Add the field value in $matches[1] to $vars['classes_array'][$id] to set the row class. Cut the complete field out of the row with str_replace() by using $matches[0] from the first search and an empty string.


Clear views cache after node inserted in Drupal 7 I've views which list the list of node details. I've set views cache for 30 mins.
I want to clear particular views cache when insert a node.
I've tried below code to clear cache but there is no difference in my page.

function phponwebsites_node_insert($node) {
 if ($node->type == 'tasks') {
   views_invalidate_cache();
 }
}

The next snippet should work for you

cache_clear_all('MY_VIEW_NAME:', 'cache_views_data', TRUE);


Plugin to make selecting a page on a menu easier I'm in the process of building a drupal site and wonder if there is an easier way to create menu items.

When I create a menu item in a menu I need to manually enter the url of the link for the item.  Is there a plugin available that will allow me to select from a list all the content created in the system so I can simply select the page I wish it to link to?

Obviously it would also need to allow me to type in a link for custom modules etc?

Does this exist as a plugin?

Content menu module improves Drupal's default menu management interface for tighter intergation of content authoring and menu management, so content can be created and edit right from the menu interface (e.g. creating content for a menu item that has been just created)
You can create a new menu item as

URL – With the traditional menu item form

Dummy – As a dummy menu item (with simple dummy link target)

New NODETYPE – directly create a new content for the new item

Existing content – selecting an existing content via a nice filterable view (if views is enabled)

Menu position rule (if the Menu Position module is enabled)


Make block render right after enabling the module I'm working on a module which renders a small block in a footer region. My goal is to make it work out of the box with default settings. User just needs to enable it with drush, no configuration required.

In Drupal 6 version I stumbled upon a strange problem. Looks like after enabling module it's hook_block isn't called, so block isn't rendered. It can be fixed either by doing drush cc all or going to blocks admin page. All caching is disabled on the test site.

I tried to incorporate drupal_flush_all_caches and drupal_cache_clear into hook_install without success.

Can someone give a hint?

After some trials I found an easy workaround:

function mymodule_enable() {
  _block_rehash();
}

It's function which get called then one visits /admin/build/block. It rescans blocks provided by modules.


Show contact form in block only, not page? I'm using the Contact and Contact Form Blocks modules to create a contact form and display it in a block.

The problem is that the Contact module creates a page but I don't want a page, only the block.

Is this possible, perhaps with a different set of modules? If not then I guess I can deny access to the page using .htaccess, but that seems a bit of a hack (although since it's easier to do that than to add custom code, I'm not really interested in a custom code solution).

EDIT: I've tried using a webform instead but have the same issue. There's an option to make the webform available in a block, but the page (node) is also created

You can use the module Webform for contact forms. It comes with the option to make it available as a block. Here's a quick screenshot of the option:

You can also add other function like email notification, AJAX, template for confirmation page, etc. It's a highly customizable module, very recommended.


How to pass argument from one view to another view? I have filter  in separate view and want to pass the value to another view and get the filter result in Drupal.

Scenario: I have two views, one for filter and another for filter result.

I want to filter based the content: title. In another view I have to fetch the result and display based on title filter.

My question: How can I argument from one view to another view?

Here is how you can do it programmatically:

// load and display view A
$view_A = views_get_view('view_A_name');
// execute view
$view_A->execute();
// get all nids from the result
foreach ($view_A->result as $result) {
   // capture the result of your field in an array.
   $values[] = $result->field_machine_name;
}
// render view
print $view_A->render();

// now load view B
$view_B = views_get_view('view_B_name');
// set arguments for view
$view_B->set_arguments(array(implode(",", $values)));
// execute view
$view_B->execute();
// render view
print $view_B->render();


How can pass a data of a node's field to entityform field I have a field named "code". This hidden field stores some alfa_numeric values.

Nodes with using this data field have an entityform type as a block in page.

How can I pass node's data values to entityforms data field as prepopulated.

You can use hook_form_alter in a custom module and pass the node field value to the value of the form item eg :

<?php
  function mymodule_form_FORM_ID_alter(&$form, &$form_state, $form_id){
    // dpm($form);
    $node = node_load(arg(1));
    $form['field_code']['#value'] = $node->my_field[LANGUAGE_NONE][0]['value'];
  }
?>

Things you need to know are:

The ID of the entity form for FORM_ID, you can get this using Get form ID module.

What the field you are populating is ? you can install Devel module then uncomment the line in the above code to inspect the form.

Where within the node object the field with the data is ? If Devel is installed you can navigate to the node and click on the Devel tab and explore the node there.

If you are using hidden fields then ['#value'] is ok but if it is a textfield then you should use ['#default_value'].

Also, this is presuming that the form is in a block on the node page, other wise node_load(arg(1)); will node work.


Drupal 7 - Login with external Database I want my users to be able to login into Drupal with an external user database.
I searched for a long time and don't get any module/trick/whatever that is out there.
Please help me a little, I'm new to Drupal, I don't know anything about hooks or whatever.
Isn't there a module exactly like this: http://drupal.org/project/ppauth
only that I can use my own database with?

Help? Please, I'm desperate! :(

Is your external database provided by another authentication mechanism? There are mature modules for Active Directory, Social Network login, and many others besides.

If your database for authentication is totally custom, then you will need to write some custom code.

Drupal users generally login using the user_login form. When users login, a particular function, user_login_authenticate_validate, is called by the user_login form's submit hook. This function validates user credentials against the local database.

user_login_authenticate_validate can be replaced with another function by using hook_form_alter on the user_login_form. You will need to create a new module, and implement code something like the following...

/**
* Implements hook_form_FORM_ID_alter().
*/
function mymodule_form_user_login_alter(&$form, &$form_state, $form_id) {
  // Add your own validators to the form.
  $form['#validate'] = mymodule_validators();
}

/**
* Returns an array of user validation function callables.
*
* @see user_login_default_validators().
*/
function mymodule_validators() {
  return array('user_login_name_validate', 'mymodule_authenticate_validate', 'user_login_final_validate');
}

/**
* Validation function, validates users against foo database.
*
* @see user_login_authenticate_validate()
*/
function mymodule_authenticate_validate($form, &$form_state) {
  // Use the password and username from the form, and make sure you set
  // $form_state['uid'] to the correct uid for the auth user.
  $password = trim($form_state['values']['pass']);
  $username = $form_state['values']['name'];

 // Authenticate them against your database, and find their drupal uid....
 $form_state['uid'] = mydatabase_auth_function_that_returns_a_drupal_uid($username, $password);
}

Implementing your own authentication is a decision that you should not take lightly. Personally, I would never go down this path. There are serious security concerns when rolling your own authentication mechanism. Wherever possible, you should leverage mature and well-tested solutions.


Drupal Commerce | Hide or set an alias to the order number in the checkout path Is there any DC module or configuration that would allow me to set an alias for the order number that is shown on the checkout path.

i.e.

Instead of example.com/checkout/10

Something like example.com/checkout/order or just plain example.com/checkout

An alias module would have similar functionalities as the me module.

I to went that road, did not want customers to see an on each order incrementing ID in URL's. In hook_url_outbound_alter() any path can be encrypted by altering the regular expression.

/**
 * Implements hook_url_inbound_alter().
 */
function mymodule_url_inbound_alter(&$path, $original_path, $path_language) {
  // Decrypt paths that are encrypted by our hook_url_outbound_alter() to hide possible id's in paths.
  if (preg_match('#^ENC:(.+)#', $path, $m)) {
    $path = _mymodule_mcrypt('decrypt', $m[1]);
  }
}

/**
 * Implements hook_url_outbound_alter().
 */
function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  // To hide id's in paths, we encrypt them.
  if (preg_match('#^checkout/.*#', $path, $m)) {
    $path = 'ENC:' . _mymodule_mcrypt('encrypt', $path);
  }
}

/**
 * Helper function to encrypt and decrypt strings, ie. paths to hide containing id's.
 * NB: We replace forward slashes for exclamation marks, otherwise trailing
 *     slashes in the URL will be ignored by Drupal.
 */
function _mymodule_mcrypt($action, $string, $key = null) {
  if (!$key) {
    $key = $GLOBALS['drupal_hash_salt'];
  }

  $mcrypt_method = MCRYPT_RIJNDAEL_128;
  $iv_size = mcrypt_get_iv_size($mcrypt_method, MCRYPT_MODE_CBC);

  // Make key exactly as long as long as $iv_size.
  $key = substr(str_repeat($key, CEIL($iv_size / strlen($key))), 0, $iv_size);

  if ($action == 'encrypt') {
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $encrypted_string = base64_encode($iv . mcrypt_encrypt($mcrypt_method, $key, $string, MCRYPT_MODE_CBC, $iv));
    return preg_replace('#/#', '!', $encrypted_string);
  }
  elseif ($action == 'decrypt') {
    $decrypted_string = base64_decode(preg_replace('#!#', '/', $string));
    $iv = substr($decrypted_string, 0, $iv_size);
    $decrypted_string = substr($decrypted_string, $iv_size);

    return rtrim(mcrypt_decrypt($mcrypt_method, $key, $decrypted_string, MCRYPT_MODE_CBC, $iv));
  }

  return false;
}


Why isn't the page cal back needed in Ajax jQuery? In the following code, I didn't set any page arguments, but I can still tse the parameter in example_result(). Why it works?
function example_menu() {
  $items['example-menu'] = array(
    'page callback' => 'example_result',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function example_result($para) {
  $items = array('a', 'b', 'c');
  return drupal_json(array('values' => $items));
  exit;
}

That is explained in the examples shown for hook_menu().

 function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
    );
    return $items;
  }

  function mymodule_abc_view($ghi = 0, $jkl = '') {
    // ...
  }

Using the code above, and accessing the page as http://example.com/abc/def, the page callback would get 0 and '' as arguments; accessing the page as http://example.com/abc/def/123/foo, $ghi will be equal to 123, while $jkl will be equal to 'foo'.

That is the default behavior of Drupal.

You could also use wildcards arguments, but in that case those arguments should be passed in the URL.


When hook_field_load and hook_field_formatter_view are called? I have implemented the hook_field_load() and hook_field_formatter_view() function to replace some characters in a specific field's value. But they don't seem to be called at all.
I wrote some command like exit() and print_r($field) in the hooks but nothing happens.

When this hooks are called? (and is this the correct way to do alter field values for view?)

hook_field_load() and hook_field_formatter_view() aren't hooks really. They rather are callbacks which only can be used from a module implementing the field in question by itself. The documentation at api.drupal.org for both hooks is not very clear in that by stating nothing or just a vague:

  Define custom load behavior for this module's field types.

When grepping through the Drupal 7 code you never see this so called hooks invoked by module_invoke_all() which is a clear sign for that functions are not handled like hooks.

hook_field_attach_load() may be used instead of hook_field_load() which is a real hook.

See also the discussion at http://drupal.org/node/702586 for that matter.


How to show all terms with are used in Content? I have Content type: Products. It has field (Brand) on taxonomy base.
I use Views and want to see list of terms (all brand names) wich are used in my materials on the Product type base. I understand that it is possible to chose Taxonomy as base for Views building, but I want to build View on Content base.

Is this in Drupal 6 or Drupal 7? In Drupal 7, you should create a content view, use fields, and then in the fields section and select the relevant content field. This should then display all the various options that are selected.


When can a contrib module considered to be stable? Is there a clear definition of a module being stable in comparison with a release candidate? When can a stable version be released?

As an example, can't the Read only mode module considered stable?

Read the docs.

Release naming conventions

  rc: A release candidate should only be created when the all critical bug type issues are reported fixed in the project's issue
  queue. This tag should only be used when the developer believes that
  the project is ready for use on a production site. There is no
  official best practice for how long a project should be a release
  candidate before creating a official .0 release, but it is suggested
  that it should be out for at least a month with status set to "needs
  review". If something (e.g. a new critical bug is reported) makes it
  necessary to create a new release during this period, a new release
  candidate should be created and this should remain for at least a
  month with status set to "needs review".


Get the fields from a reference entity (content type) in a Paragraph field I have a paragraph field that is a reference entity to the Customer Testimonial content type. A content editor can add the customer-testimonial paragraph and type the name of the testimonial. This will then display the text on the website.

I have made a paragraph--c15a-customer-testimonial.html.twig template file with the following code.

{%
  set c15a = {

    title: content.field_testimonial.entity.field_testimonial_titel,

  }
%}

Testimonial title

{{ c15a.title }}

Of course, this prints nothing. How can I get the fields from the content type I'm referencing in my paragraph?

The referenced entity is not built yet, so you can't access the formatted field content.

You can get the field value from the database by using the paragraph object:

{{ paragraph.field_testimonial.entity.field_testimonial_titel.value }}

This is unformatted, which might work for a title field.

If you want a formatted output better use a custom view mode for the referenced entity to configure the fields, or in this case one field, if this is all you want to display.


How to move the edit tab in node.tpl.php The $tabs variable is being printed in page.tpl.php, but I want to move it under the title of my node. I can't use the $tabs variable in my node template and I don't see the variable being prepared in template.php as well.

How can I get $tabs to show where I want in my node template file?

The $tabs variable is set up in template_preprocess_page(); you can add the same var to the node template file by implementing a preprocess hook:

function MYTHEME_preprocess_node(&$vars) {
  $vars['tabs'] = menu_local_tabs();
}


How to create charts based on content types items? I want to create a chart according to each content type created per month or week.

How can I do it? Is there any suggestion to use some module?

Using the Charts module
Step 1: Getting started
To create charts in Drupal, just use the Charts module. It comes with a sample view which will give you a chart for each of your content types.
Just clone and refine that view, and check how close you are to make it fit your needs. Refer to Create charts using Views (and its subpages) for more details.
For a sample of such chart (derived from the delivered sample view), have a look at this demo sample.
Step 2: Create the tabular format of the view
A common mistake when creating charts, is that the data to be charted is (not yet) correct. So you really need to first work on getting the tabular format of the view created correctly. That's also what's recommended in the Bonus tip within Steps to create charts using the views UI, i.e.:

You may find it easier to start with a "Table" display and convert it to a chart display after setting up the data. It can be easier to visualize what the result of the chart will be if it's been laid out in a table first. ...

Step 3: Add the chart to your view
Do not try to start this step if you didn't first complete the prior step.
There is an issue which might help to answer this question, or at least to understand the challenge here. I.e. Graph node input over time (support date formatting on a continuous axis).
In Comment #3 of that issue is stated: 'The trouble here is that neither Views nor Date modules provide aggregation options for date-based fields.'.
Using the Quant module
If using the Charts module you can't get it to work (or don't want to consider the suggestions above), then you may want to look at the Quant module as an alternative. Here are some excerpts from its project page:

... provides an engine for producing quantitative, time-based analytics for virtually any Drupal component. Quant takes raw data about normal Drupal actions, such as node creation, and plots the activity over time, with the selected time being configurable. See the screenshot provided for a better understanding.
Provided charts:

Content creation
Comment creation
Content creation by type
Aggregate content creation
User creation
Page views (requires Statistics)
User shouts (requires Shoutbox)
User point transactions (requires User Points)
Group creation (requires Organic groups)
Group joins (requires Organic groups)
Invites sent (requires Invite)
Invites accepted (requires Invite)
Statuses shared (requires Facebook-style statuses)
Private messages (requires Private message)

Especially the "Page views* chart that is provided might be close to what you're looking for.
Evaluating other charting modules
If none of the above modules would work in your case, then you might want to look at the "Comparison of Charting modules" documentation.
Disclosure: I'm a (co-)maintainer of all modules mentioned above (and original author of the comparison).


Node relationships, backwards or forward? I know node references are not as popular as entity references are, but I'm curious on backwards and forward relationships.

This is a use case I see someone doing.

Job  < -- Job Application

2 content types, and the node reference in the Job application point to Job.

In reality, shouldn't Job be pointing to the Job applications?

2nd use case

Project --> Files

When you create a project, you attach files to it, most of the time files are known beforehand so additional ones after parent node creation would be unlikely.

This is the more "correct" way as I see it, a Project can "have many" files. I also notice it could be done in the reverse as well, a file could reference a project.

The whole idea of Many to one, one to many, and many to many relationships in Drupal using the node / entity references module really make me wonder.

With the project user case, you can use references dialog, and you can create children right then and there. Doing the reverse of that, creating a parent could be possible, but why would one do that?

I've watched many videos, and I can see people doing it both ways almost with no consistency. I almost get confused myself when thinking about this. I come from doing things where these relationships are a bit more defined, and the DB schema is setup as so.

So does it really matter which way you put the reference? Also is it bad to have 2 node reference each other? I noticed there is some back references modules etc, what use do these have outside of making it easier for views? Did they have provide any other practical uses? (I know views3 with the node reference module , back references work out of the box now). Does it really just come down to workflow and how it would be easiest to get the creation forms to have the experience you want?

If someone could clear this up for me, I would really appreciate it.

A one-to-many relationship (also in DB design) is typically created by referencing the parent from the child. In the Jobs/Job Applications case, this translates into a reference from Job Application to Job, not vice versa.

In the Project/File case, if each file can only belong to one project, then it's also a one-to-many relationship and so File should reference Project. This is definitely how it should be if we were designing database tables for those entities.

However, in terms of Drupal and node references and given this particular example, Files are almost like properties to the Project node. So I wouldn't be surprised to see Files referenced from Project in a multiple-value node reference field, just for convenience.


How do I implement Entity Reference Behaviour Plugins? Do Entity Reference behaviour plugins exist for Drupal 8? Please see:
https://www.drupal.org/node/1803064#comment-10717088
Are there any existing examples; documentation or code?

I would like to upgrade entityreference_prepopulate but I am unsure about these behaviour plugins.

Answer on IRC via berdir: "no, that doesn't exist". So it simply does not exist yet in D8.
Supplementary info provided for field settings in D8 =>
berdir:

note that fields, like all config entities have a concept of third party settings. you can use that to store per-field settings. didn't check the other parts
see https://www.drupal.org/project/allowed_formats for a projects that uses third party settings on fields


Calendar Multiple URL's Output Specific Block/Menu Dead Links Hi I've created a block that I only want to appear in the members area this includes a page where I use the Calendar Module, the problem I have is that I have listed the pages where the block should be outputted however with the calendar there are multiple url's for every view depending on month, so I can't feasibly output the block with all of these pages/url's which are possible through the calendar......

So is there a way to output this block specifically for every view output of the calendar, aside from listing all the url's in the block configuration page......

Also another issue the menu of the calendar isn't working, is there some setting I need to turn on in the admin area to get the menu to work........

http://www.cambrianvacation.co.uk/artbelow/?q=calendar-created/month

Regards

Ant

Block visibility settings accept wildcard characters. If the calendar URL's are of the form, say:

/calendar/april/....
/calendar/may/....

all you have to do is to enter calendar/* in the block visibility settings, and all the pages will be identified. (Adjust according to the actual path of your calendar.)


Use template file from module I did this in my custom module:

/**
 * Implements hook_theme().
 */
function my_module_theme() {
  return [
    'my_module' => [
      'template' => 'my-module'
    ],
  ];
}

/**
 * Implements hook_theme_suggestions_HOOK_alter() for form templates.
 *
 * @param array $suggestions
 * @param array $variables
 */
function my_module_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  // Block suggestion for specific block bundle.
  if (isset($variables['elements']['content']['#block_content'])) {
    $block_bundle = $variables['elements']['content']['#block_content']->bundle();

    if ($block_bundle = 'my_block_bundle') {
      array_splice($suggestions, 1, 0, 'my_module');
    }
  }
}

I already created this block bundle in the module, so I want to use my template from module (my-module.html.twig in my_module/templates) for all blocks in this bundle, but with this code all my blocks in this bundle disappeared.

What I'm doing wrong here?

I haven't checked the rest of the code but

if ($block_bundle = 'my_block_bundle') {

should be

if ($block_bundle == 'my_block_bundle') {

// you could also use
$suggestions[] = 'your_suggestion' // instead of the splice


How do I programmatically change the query "limit"? I've created listing with views module in which page has 9 items and only in first page the sixth item should be advertisement instead of result item. It means all items after sixth element should be shifted for one item. How can I do this? Would be hook_views_query_alter() the correct hook?

If you can make your change by altering the query itself than hook_views_query_alter() is a reasonable approach, although given your description I suspect hook_views_pre_render() is more likely to give you access to the data you are thinking about.  The query alter lets you change the actual query run against the database, while prerender lets you edit the result set before Drupal renders it as HTML (or similar) for output.

Depending on the details of your use case it might make sense to actually use two queries: one that pulls the value you want to highlight and one that pulls everything else.  If the highlighted item is identified because it's the 6th, this approach would be just as hard as yours, but if it's highlighted because of some other factor (a taxonomy term, or some other field value) than this approach would likely be easier. You can have 1 query that generates the listing page, and a second with a block display that's placed at the top of your listing page.


drupalchat with nodejs I need to run drupalchat with nodejs locally but I get error loading the socket.io.js client library (404 not found)

nodejs server is running

the file exist in that path :

  sites/all/modules/nodejs/node_modules/socket.io/node_modules/socket.io-client/socket.io.js

the request:

  http://localhost/drupal:8080/socket.io/socket.io.js

noddejs config:settings = {
  scheme: 'http',
  port: 8282,
  host: 'localhost',
  resource: '/socket.io',
  serviceKey: '',
  backend: {
    port: 82,
    host: 'localhost',
    scheme: 'http',
    basePath: 'localhost/drupal',
    messagePath: '/nodejs/message'
  },
  debug: false,
  sslKeyPath: '',
  sslCertPath: '',
  sslCAPath: '',
  baseAuthPath: '/nodejs/',
  publishUrl: 'publish',
  kickUserUrl: 'user/kick/:uid',
  logoutUserUrl: 'user/logout/:authtoken',
  addUserToChannelUrl: 'user/channel/add/:channel/:uid',
  removeUserFromChannelUrl: 'user/channel/remove/:channel/:uid',
  addChannelUrl: 'channel/add/:channel',
  removeChannelUrl: 'channel/remove/:channel',
  setUserPresenceListUrl: 'user/presence-list/:uid/:uidList',
  addAuthTokenToChannelUrl: 'authtoken/channel/add/:channel/:uid',
  removeAuthTokenFromChannelUrl: 'authtoken/channel/remove/:channel/:uid',
  toggleDebugUrl: 'debug/toggle',
  contentTokenUrl: 'content/token',
  publishMessageToContentChannelUrl: 'content/token/message',
  extensions: [],
  clientsCanWriteToChannels: false,
  clientsCanWriteToClients: false,
  transports: ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling'],
  jsMinification: true,
  jsEtag: true,
  logLevel: 1
};

what is wrong/missing config/permissions to run them together?

thanks in advance

I have created simple module to Integrate nodejs and build chat server for drupal users  d7 nodejs chat


How can I place a  new  textfield in the tab vocabularies in a content type? I want to place a new text field in the "Vocabularies" field set of a node; the text field is not tag.

I am using the Vertical Tabs module, and my fields in the content type are in group.

The following is the structure of my content type:

Title
Vocabularies (taxonomy) -> Here I want to place a field too.
fieldset1 (Fields:  field1, field2, and field3)
fieldset2 (Fields: field4, field5)

The fieldset for the vocabularies used by a node are added from taxonomy_form_alter(), using the following code (the relevant part is the one between "// 3" and "// 4"):

// 1
if (!isset($node->taxonomy)) {
  $terms = empty($node->nid) ? array() : taxonomy_node_get_terms($node);
}
else {
  // After a preview or form reload, the terms must be converted to objects.
  reset($node->taxonomy);
  if (!is_object(current($node->taxonomy))) {
    $node->taxonomy = taxonomy_preview_terms($node);
  }
  $terms = $node->taxonomy;
}

$c = db_query(db_rewrite_sql("SELECT v.* FROM {vocabulary} v INNER JOIN {vocabulary_node_types} n ON v.vid = n.vid WHERE n.type = '%s' ORDER BY v.weight, v.name", 'v', 'vid'), $node->type);

while ($vocabulary = db_fetch_object($c)) {
  if ($vocabulary->tags) {
    if (isset($form_state['node_preview'])) {
      // Typed string can be changed by the user before preview,
      // so we just insert the tags directly as provided in the form.
      $typed_string = $node->taxonomy['tags'][$vocabulary->vid];
    }
    else {
      $typed_string = taxonomy_implode_tags($terms, $vocabulary->vid) . (array_key_exists('tags', $terms) ? $terms['tags'][$vocabulary->vid] : NULL);
    }
// 2
    if ($vocabulary->help) {
      $help = filter_xss_admin($vocabulary->help);
    }
    else {
      $help = t('A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc.".');
    }
    $form['taxonomy']['tags'][$vocabulary->vid] = array(
      '#type' => 'textfield',
      '#title' => $vocabulary->name,
      '#description' => $help,
      '#required' => $vocabulary->required,
      '#default_value' => $typed_string,
      '#autocomplete_path' => 'taxonomy/autocomplete/' . $vocabulary->vid,
      '#weight' => $vocabulary->weight,
      '#maxlength' => 1024,
    );
  }
  else {
    // Extract terms belonging to the vocabulary in question.
    $default_terms = array();
    foreach ($terms as $term) {
      // Free tagging has no default terms and also no vid after preview.
      if (isset($term->vid) && $term->vid == $vocabulary->vid) {
        $default_terms[$term->tid] = $term;
      }
    }

// 3
    $form['taxonomy'][$vocabulary->vid] = taxonomy_form($vocabulary->vid, array_keys($default_terms), filter_xss_admin($vocabulary->help));
    $form['taxonomy'][$vocabulary->vid]['#weight'] = $vocabulary->weight;
    $form['taxonomy'][$vocabulary->vid]['#required'] = $vocabulary->required;
  }
}
if (!empty($form['taxonomy']) && is_array($form['taxonomy'])) {
  if (count($form['taxonomy']) > 1) {
    // Add fieldset only if form has more than 1 element.
    $form['taxonomy'] += array(
      '#type' => 'fieldset',
      '#title' => t('Vocabularies'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    );
  }
  $form['taxonomy']['#weight'] = -3;
  $form['taxonomy']['#tree'] = TRUE;
// 4
}

The fieldset, which is then changed by the Vertical Tabs module in a tab, is added only when there are more than one vocabulary associated with the content type of the node being created.

To add a new field in that fieldset, you should implement hook_form_alter() in a module, and add code similar to the following one:

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if (isset($form['type']) && isset($form['#node']) && && $form['type']['#value'] . '_node_form' == $form_id) {
    if (isset($form['taxonomy']['#type']) && $form['taxonomy']['#type'] == 'fieldset') {
      // Add your field.
      $form['taxonomy']['mymodule_field] = array(
        // …
      );
    }
  }
}

The module you write should be executed after the Taxonomy module, or the module will not find the fieldset added by the Taxonomy module. The module is executed after the Taxonomy module if it has a name such as TaxonomyAddendum, or if the weight of the module is higher than the weight of the Taxonomy module (10 should be enough).

As for altering the existing fields for the taxonomy terms, you should look at the code between the comments "// 1" and "// 2"; as form is build using the vocabulary ID, as in $form['taxonomy'][$vocabulary->vid], you need to know it to get all the form fields used for the taxonomy terms. If you want to change the form field for a vocabulary for which you know the ID, then the code is simpler, as you don't need to get all the vocabularies that are associated to the node being edited; that is also true if you want to alter the form field for a vocabulary you know by name. You can use the following code to get a vocabulary object knowing the vocabulary name.

$result = db_fetch_object(db_query(db_rewrite_sql("SELECT v.vid, v.*, n.type FROM {vocabulary} v LEFT JOIN {vocabulary_node_types} n ON v.vid = n.vid WHERE n.type = '%s' AND v.name = '%s' ORDER BY v.weight, v.name", 'v', 'vid'), $type, $vocabulary_name));

$type is the content type that, in your case, is $form['#node']->type; $vocabulary_name is the name of the vocabulary.

If you know the vocabulary ID, then you can simply use taxonomy_vocabulary_load() to get the vocabulary object, which you could need to populate the taxonomy term form field.


Multi language with different layout drupal 6 I have a multilingual site with English and Spanish. I need to change the Layout(theme) of my English pages but no chnage in spanish pages. Can we have separate tpl file based on Language? Any help will be appreciatable

John,

This question has already been answered here:
  Page template suggestion per language?

Cheers,


How do I troubleshoot PrivateTempStore for session data? I am updated one of my Drupal 7 modules for Drupal 8 and I discovered that I need to use PrivateTempStore rather than $_SESSION variables. I followed some great examples online, but it does not seem to be storing the data correctly. I am even checking the database directly afterwards, but it does not have the correct data. I've done some debugging at the point where I am storing the data to see what is set, and it says it is set with the value I expect. However, the database does not show this value and reloading the page and outputting the value retrieved does not show what I expect. What are the method people use to debug these issues.

Currently running Drupal 8.8.1 on PHP 7.3.

I am updated one of my Drupal 7 modules for Drupal 8 and I discovered
  that I need to use PrivateTempStore rather than $_SESSION variables.

The Drupal 8 replacement for $_SESSION is not PrivateTempStore, it is the session object in the request:

Drupal 7:

function mymodule_session_counter_increment() {
  if (!isset($_SESSION['mymodule_count'])) {
    $_SESSION['mymodule_count'] = 0;
  }

  return $_SESSION['mymodule_count']++;
}

Drupal 8:

class MymoduleSessionCounter {
  function increment(Request $request) {
    $session = $request->getSession();
    $value = $session->get('mymodule_count', 0);
    $session->set('mymodule_count', $value + 1);

    return $value;
  }
}

See the change record: https://www.drupal.org/node/2380327

For more info see this topic: How do I store the values submitted in a form in the session?


How can I access block metadata from custom plugin instance? Using the block_example module, I created two instances of the example_configurable_text block in the UI and would like to now access their underlying metadata, specifically uuids. By looking at the config table in the database, I can see that there is a record for each (select * from config where name like "%example%";). However, when I debug ExampleConfigurableTextBlock::build, I can't seem to access any of it.

I'm aware that configuration can be loaded via \Drupal::config('<name>'), but I need to be able to access the configuration dynamically from with my plugin class instance.

Is extending BlockBase the right way to go? Do I need to use derivatives? What is the connection between a block instance in the config table and an instance of a block plugin? So many questions.

Generate unique form ID based on context contains the answer you're looking for.

Short answer is, you have to make this unique id yourself. See the mentioned simplenews project and how I solved it there.

Keep in mind that block plugins are not only usable by core block entities, they can also be used by Page Manager/Panels, where you have many blocks in a single variant and even by projects like block_field, which allow to use block plugins on content entities. You must not rely on anything but your own configuration array.

I think I once opened a core issue about this, to introduce a method so that a unique ID can bet set on a block plugin, but I can't find it anymore, only another core issue (https://www.drupal.org/node/2405879) where I mentioned that I can't find that issue anymore :)


Show a view on a custom nodetype only if the logged in user is the author of this node I'm using Drupal 7, with the Views module version 3, and the Context module (no block).

I have a draggable view I want to show on a gallery node. The draggable view shows the image nodes belonging to this gallery node for sorting.

Now I want to limmit the display of this view to the author of the gallery node. (Only the author of the gallery node should organize the image nodes.) I think this could be done with context or relationship (and some coding) inside views, but I don't know how.

I know how I can display the view only on the gallery-node (via Context module). So I only need a way to limit the display of the view to the author of the gallery.

Maybe someone has a solution.

You just need to add an argument to this, passing the logged in user's uid. In Drupal 6, views 2 you used to have to reverse engineer this and add custom php into the argument handling code but this is built into Views 3. In your view:

Add Contextual filter, 'Content: author uid'
Select 'provide default value', type 'user id from logged in user'

This will find the uid of the logged in author and pass that as an argument to your view, restricting the view results to only items that were authored by the owner of that node.


Listing Active Members of Current Group in View pane (OG 7.x-2.3) I am relatively new to Drupal and somewhat boggled by the new version of Organic Groups. We recently migrated our site from OG 7.x-1.4 to OG 7.x-2.3. Everything went fine except certain view panes no longer work. We had one view content pane that listed the members of the group in a page based on the context. We created a panel page for the group home page layout when the content pane was embedded in that page it would show the members for that group. However, the contextual filter for that view was broken after the import.

I tried to copy the view settings from a clean install of the latest OG code but that didn't work. The view is one of users but I cannot figure out how I should set the contextual filters or the relationships of that view to show only the members of the group. I just can't seem to wrap my head around how the OG_Membership object works.

Any help would be greatly appreciated.

In retrospect the answer was rather obvious. When you migrate from OG 1.x to OG 2.x, the views associated with OG do not get updated. So they have "missing/broken relationships." For most of the view panes it was easy to fix by going to the view page and under the "edit view name/description" drop down, there is an option to "Revert View". Choosing this fixes the views that come with OG because it "reverts" the view to the updated OG 2.x code. Custom views have to be rebuilt.


How to delete uninstalled modules via drush? I have been wondering how one could clean up uninstalled modules in the modules folder. Perhaps by piping some drush output to rm rf...

I noticed drush pm list gives small modules that exist in larger enabled modules. Any tips?

drush pm-list --type=Module --no-core --status="Not installed"

Drush is a tool for performing Drupal operations in the shell. If you've already uninstalled the module then there's nothing left in Drush's purview to do, just perform a rm on each module you need removed. pm-list has --pipe option that will spit out the module short name. You can use that output to find the correct directory and remove it. Something like...

drush pm-list --type=Module --pipe --no-core --status="Not installed" | while read -r module; do  find sites/all/modules -type d  -name "$module"; done

The remaining work here is more of question about bash (or your shell of choice) than Drush so I'll leave it to the reader to find his own solution.

It should also be mentioned scripting module folder deletion could be fraught with dangers (e.g. not every module is going to be at the same folder, you shouldn't be deleting submodules, etc.); you're better off manually inspecting a list of uninstalled modules (you shouldn't have that many) and removing them judiciously.


Loading third party PHP SDK library from a custom module drupal 7 I am writing a custom drupal module (my first one in my life), and I am trying to load an external library (https://github.com/jwilsson/spotify-web-api-php), and until now I used these methods:

Loaded file array in info file

files[] = spotify-web-api-php/vendor/autoload.php,spotify-web-api-php/src/Request.php,spotify-web-api-php/src/Session.php,spotify-web-api-php/src/SpotifyWebAPI.php,spotify-web-api-php/src/SpotifyWebAPIException.php
I made this function based on another answers here (Copied the library in libraries folder)

function blve_spotify_registry_files_alter (&$files, $modules)
{
  if (!class_exists('SpotifyWebAPI\Session')) {
    $library_path = function_exists('libraries_get_path') ?
      libraries_get_path('spotify-web-api-php') : 'sites/all/libraries/spotify-web-api-php';

$files[$library_path . '/vendor/autoload.php'] = array(
  'module' => 'blve_spotify',
  'weight' => 0,
);

}
}
I used require_once but will only work on one function

None of these methods worked, when I made a function to call all the loaded files any of the methods or files I need are loaded, please help me to made it work with the required php files. Thanks in advance

Use libraries module to load 3rd party dependencies (easier way), or composer manager to load composer package (better way).

Here you can find some details and examples how to start with libraries module.


get form state values of forms which added via ajax the forms were added via ajax,but I just don't know how to get $values= $form_state['values']['field_name']; ,the result return nothing.Thanks in advance!

<?php

/**
 * hook_menu()
 */

function addstudent_menu(){
    $items= array();
    $items['user/%/add-students'] = array(
        'title'=>t('添加學生賬戶'),
        'page callback' =>'drupal_get_form',
        'page arguments' => array(addstudent_form),
        'access arguments' => array('create new users'),
        'type' => MENU_LOCAL_TASK,

    );

    return $items;

}

function addstudent_form($form,&$form_state){

    $dropdown_source = taxonomy_get_tree(3);
    if(!empty($dropdown_source)){
        $options = array('0'=> '--none--');

        foreach($dropdown_source as $item){ //we get all class term here
            $key = $item->tid;
            $value =$item->name;
            $options[$key] = $value;
        }
    }else {
        drupal_set_message(t('你还没有创建任何班级'),'error');
    }

    $form['addstudent_wrapper'] = array(
        '#title' => t('添加學生賬戶'),
        '#type' =>'fieldset',
        '#prefix'=>'
',
        '#suffix'=> '
',

    );

    $form['addstudent_wrapper']['fields_head']['select_class'] = array(
        '#title'=> t('班级'),
        '#type' => 'select',
        '#options'=>$options
    );

    $form['addstudent_wrapper']['fields_head']['student_qty'] = array(
        '#title' => t('人數'),
        '#type'=> 'textfield',
        '#size'=> 10,

    );

    $form['addstudent_wrapper']['fields_head']['add'] = array(
        '#type' => 'submit',
        '#value'=> '確認',
        '#ajax' => array(
            'callback' => 'addstudent_get_callback',
            'wrapper' =>'fields_wrapper',

        ),
    );

    $form['addstudent_wrapper']['fields_wrapper']=array(
        '#tree' => TRUE,
    );

    return $form;

}

function addstudent_get_callback($form,&$form_state){
    $form_state['rebulid'] = TRUE;
    $i = $form_state['values']['student_qty'];
    return $form['addstudent_wrapper']['fields_wrapper'] = _addstudent_fields($i);

}

function  _addstudent_fields($i){
    for($a=0;$a<$i;$a++){

        $form[$a]['field_number'] = array(
            '#title' => '學號',
            '#markup'=>$a+1,
            '#tree' =>TRUE,
            '#type'=>'markup'

        );

        $form[$a]['field_name'] = array(
            '#title' => '姓名',
            '#type'=> 'textfield',
            '#tree' => TRUE,
            '#parents' => array('field_name', $i, 'field_name'),
            '#size'=> 10,
            '#default_value'=>''
        );
    }

    $form['addstudent_wrapper']['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Confirm',
        '#submit' => array('addstudent_form_submit'),
    );

    return $form;
}

function addstudent_form_submit($form,&$form_state){

    $values= $form_state['values']['field_name'];
    $a = array_values($values);
    foreach($a AS $b){
        foreach($b as $c){
            $r[] = $c;
        }
    }

    dsm($values);

}

Try $values= $form_state['values'];

and then dsm the values. You will get all field values of the form.

I think you should get the form values of ajax in $form_state['values']['addstudent_wrapper']['fields_wrapper'][0]['field_name'] and so on.


Select previous/next nodes of same content type programmaticaly in Drupal 7 there are modules out there for my problem, but they are not stable and also i need to be able to manipulate the result so here we go:

i need to provide a block on a certain node type which offers a previous and next link to cycle through the nodes of the same content type.

how can i select the previous and next node programmatically using db_query() and then output the links to them?

thanks in advance for your help

Clive is right.
But $prev_nid is looking for the first node in the table.
So you could add an ORDER BY, like this:

$prev_nid = db_query("SELECT nid FROM {node} WHERE type = 'my_type' AND created < :created ORDER BY created DESC LIMIT 1", array(':created' => $node->created))->fetchField();
$next_nid = db_query("SELECT nid FROM {node} WHERE type = 'my_type' AND created > :created ORDER BY created LIMIT 1", array(':created' => $node->created))->fetchField();


Rendering semantic HTML5 caption Is there a way to render HTML5 captions in Drupal 8? I've tried with embedding images and embedding media in the WYSIWYG, and I've also tried with media migrated from D7 to D8, but nothing works.

An image with a source like this in the WYSIWYG:

renders on the page like this:

  actual photo of a mermaid

and a media entity with a source like this on the WYSIWYG:

<drupal-entity data-caption="this is the caption" data-embed-button="media" data-entity-embed-display="view_mode:media.large_480x480" data-entity-type="media" data-entity-uuid="7012b662-1430-4610-8fa3-65eede89f7ba"></drupal-entity>

renders on the page like this:

this is the caption

with random
 tags that hold nothing and the caption pulled entirely out of the relevant tag so its parent is actually the body field. Neither of these use HTML5 with a wrapping
 tag or even a
 or
 tag.

I found a suggested hack that uses the image's title tag as a caption, and the sandboxed Image Caption module uses jQuery to produce similar results, but my site is migrating hundreds of articles where the content team has used captions for image credits and we're legally required to display those, so we can't pretend the image title is the caption. Also, the way captions are currently being rendered doesn't allow us to style the them in a way that ties them to the image or separates them from the surrounding paragraphs, so they just blend in with the rest of the text.

I tried to dump the image's variables to the page, but there is no caption:

array:8 [
  "#theme" => "image_style"
  "#style_name" => "large"
  "#attributes" => []
  "#title" =>null
  "#uri" => "public://field/image/groundhog_480x480.jpg"
  "#width" => "480"
  "#height" => "480"
  "#alt" => "Photo of a groundhog"
]

so somewhere in the rendering process the caption is being removed from the image and rendered separately.

Did you double-check that your Text Format (under /admin/config/content/formats) was set to allow the HTML5 tags for this? (See below) If you haven't then the filtering will remove those tags and replace them with <div> tags.

<figure>
<figcaption>