How to add a preview image to a content type? Is there a functionality in Drupal to add a preview image to a content type (for example in the info file). The idea is, that an editor who doesn't know which content type to choose for his content would see a 'preview image' in addition to the description text and then know what content type he would need to use. I can't find anything like this in the system and no module which would provide this functionality.

No, this functionality is not in Drupal core.

It could (at least in principle) be added through a contributed module, but AFAIK, there is currently no contributed module offering this.

It may not be trivial to add this feature in a meaningful way.  It is not unusual for Drupal sites to have content types that uses the same visual layout - but different workflows and access rules - for different use cases.  A "preview image" would not distinguish them from each other in such cases.

While the idea of different content types for different purposes is at the core of the "Drupal way" of building a site, I've noted that many ordinary users, editors and even admins struggle with this particular idea.  The problem you mention: "the editor who doesn't know which content type to choose for his content" is a real one.

I've not found a really good solution to this.  In the real world helpful content type descriptions are often not read by users/editors/admins.

My solution so far is to offer a very restricted number of content types to end users, and use very descriptive names for the types they're exposed to (e.g. "Personal blog post", "Embedded video").


Hide status messages generated from Commerce - Not required with use of Ajax add to cart module I am using a nice little module Commerce Ajax Cart which adds products to the cart without a refresh.

However, my only little issue is that when then navigating to the checkout page, it displays all the status messages for the products that have been added to cart.

I could hide these with CSS using the status class, however, this could also hide any important status messages with it.

So my question is, how can I hide the status messages from commerce, or if anyone knows where these status messages are being generated from within the commerce modules.

Thanks

I believe you're referencing the "Display an Add to Cart Message" Rule.  Looks like:

To disable this go to:
Configuration > Workflow > Rules > Disable - Display an Add To Cart Message.


How to update url_alias after SELECT FROM url_alias After a rather clumsy migration by a previous developer, my new client's site has a whole bunch of incorrect paths, which I'd like to update in bulk (nearly 7000 nodes, so I'll not be doing this by hand).

In particular, their forum topics are aliased like "/content/12345" rather than "forum/12345" as desired.

I've pretty much figured out how to do this directly in MySQL, but I've hit a snag - MySQL won't allow me to update a table I've done a select from, at least in this nested query.

Here's my query:

UPDATE url_alias SET alias = REPLACE(alias, 'content/', 'forum/') WHERE alias in (SELECT alias FROM url_alias LEFT JOIN node ON CONCAT('node/',node.nid) = url_alias.source WHERE node.type = 'forum');

and MySQL says:

ERROR 1093 (HY000): You can't specify target table 'url_alias' for update in FROM clause

Perhaps I should give up and do this in two stages in PHP...?
Or is there in fact a way to do this directly in MySQL?

Regarding the query, you can do the query using a temporary table:

CREATE TABLE `tmp` ( alias varchar(255));

INSERT INTO tmp (SELECT alias
FROM url_alias LEFT JOIN node
ON CONCAT('node/',node.nid) = url_alias.source
WHERE node.type = 'forum');

UPDATE url_alias
SET alias = REPLACE(alias, 'content/', 'forum/')
WHERE alias in (SELECT alias FROM tmp);

DROP TABLE tmp;

But if there are lots of those aliases with all different cases, it's better to follow the following steps:

Delete all records from the url_alias table.

TRUNCATE TABLE url_alias;
Go to your admin interface at yoursite.com/admin/config/search/path/patterns and define the patterns for the needed node types.
Go to the 'bulk updates' tab of the URL Aliases definitions (yoursite.com/admin/config/search/path/update_bulk) and bulk update all content paths.


How to hide the field names in a custom view? I am new to Drupal and am working on a Drupal 6 (6.28) site. I have created a custom view and corresponding block which shows the most recent story created which has been promoted to Home. The view looks great except that it displays the "Title:" and "Body:" field labels before the Title and Body. How can I remove those?

Thanks in advance.

In Drupal 7 with views 3 it works like this:
If you use fields as display format you can click in your field and disable the "Create a label" checkbox.


When does the user interface translation gets updated? If you turn off  "Check for updates" in /admin/config/regional/translate/settings, on what occasion does the user interface translation actually gets updated?

As far as I know there're two ways to update it:

Installing modules. (Related PO files will be downloaded and imported)
Manually importing PO files from /admin/config/regional/translate/import

Is that all?

The check for updates is being called on the cron job 'Interface Translation'
If you disable the cron job or disable the "check for updates" on the page you mentioned, there will not be an automatic update on cron runs.

The other methods you name are manually methods.

There is one more method in Core UI, if you translate the interface text manually on the admin/config/regional/translate page.

It also depends on the settings "Import behavior" on the admin/config/regional/translate/settings page. If the import gets updated.

This is what I know is available in Core UI.

You can of course have other contributed modules as Drush or Drupal Console to update your translations.
Or even Composer see https://github.com/drupal-composer/drupal-l10n


How do I programmatically get the content title field from a view? How do I programmatically get the content title field from a view?

Try with this out:
The following example with hook hook_preprocess_views_view

/**
 * Implements hook_preprocess_views_view().
 */
function myModule_preprocess_views_view(&$variables) {
  $view = $variables['view'];
  $result = $view->result;
  //- Titles Array
  $titles = [];
  for ($i = 0; $i < count($result); $i++) {
    $titles[]= $result[$i]->_entity->title->value;
  }
}


Help with Geocoding and Openlayers missing markers I have followed this tutorial exactly http://drupal.org/node/1002852 to create a node type with geocoding. I have a default install of openlayers, openlayers_geocoder. Geocoding appears to be working when editing/saving the node, however the marker (or polygons) do not appear on the node's map.

I have gone through this same problem.

I believe this is happening to you, because you did not set the Openlayers Data Overlay on Views.

And if you did, you did not selected/activated it on your Openlayers preset:

And if you did, you did not map the fields on the openlayers data overlay display settings:


update a module in the front page after adding new content into another page I want to create a block on the home page which highlights the latest news from the 'news' page. I would like to add new content into the 'news' page frequently. Every time when I add a piece of new article (news), I would like the block to show the image and the title of that new article automatically.

What is the best way to achieve this?

Thanks

Sounds like you should be using Views.

Create a new view
Create a page display and configure it to output the content you want.
Create a block display and configure it to output the content you want.
Add the block to your homepage

Now when you add new news it will show up on both the page and the block.


How do I invoke a service after submitting a form? I am very new to Drupal and I am asked to create form with a submit button and a service that makes a get request to an API with the values from the form. The API is a simple API that the user can enter a country and it will return a response with the correct greeting from that country.
This is my routing file.
hello_world.salutation:
  path: '/hello'
  defaults:
    _controller: Drupal\hello_world\Controller\HelloWorldSalutation::salutation
    _form: Drupal\hello_world\Form\GreetingForm
    _title: 'Get a greeting from a different language'
  requirements:
    _permission: 'administer site configuration'

First problem is that I do not know how to make the form and the controller in the same routing,
and second is that I do not know how to invoke that service when the user has entered submit.
This is the services file.
services:
  hello_world.salutation:
    class: Drupal\hello_world\HelloWorldSalutation
    arguments: [ '@config.factory' ,'@tempstore.private']
  cache.nameofbin:
    class: Drupal\Core\Cache\CacheBackendInterface
    tags:
      - { name: cache.bin }
    factory: [ '@cache_factory', 'get' ]
    arguments: [ nameofbin ]

I will skip some lines from the GreetingFrom class to keep it simple, but I can add them if it is required.
Here is the submitForm function from the GreetingForm class. The idea is to put the input in a global tempstore so I cal access the values from the controller I guess.
  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    $search_str = $form_state->getValue('greeting');
    // check the input
    $params['items'] = $form_state->getValue('greeting');
    // 2. Create a PrivateTempStore object with the collection 'greetingForm_values'.
    $tempstore = $this->tempStoreFactory->get('greetingForm_values');
    // 3. Store the $params array with the key 'params'.
    try {
      $tempstore->set('params', $params);
    } catch (\Exception $error) {
      // dump the error for now, read error, --fix this!
      dpm($error);
    }
  }

And the salutation function from the controller looks like this.
  public function salutation()
  {
    $tempstore = $this->tempStoreFactory->get('greetingForm_values');
    $params = $tempstore->get('params'); // this value should come from the search form
    return [
      '#markup' => $this->salutation->getGreeting($params),
    ];
  }

You're trying to do four things at once (form, service, integration with API, caching), so you can't see where the problem is. Instead, break this down into distinct steps.
First, code and debug your form. In the submit function, just use the messenger service in your form ($this->messenger()->addMessage('this is a test message');) to display a static value for your greeting. You should reach a point where visiting /hello and submitting the form will display the message. You can customize that message later. Get this working first.
Second, code and debug your service class. I find it useful to use drush php-script here to execute a standalone PHP script that accesses your service. That way you can ensure your service is doing exactly what you want, and figure out how to communicate with the external API, before you try to use your service in a form. You don't need the "_controller" in your routing file. The way to access your service is using \Drupal::service('hello_world.salutation')->salutation(). Instead of passing variables through a tempstore, pass them as parameters to your salutation() method. So your standalone PHP script for drush would look something like this:
<?php

  $greetings = \Drupal::service('hello_world.salutation')->salutation('some string entered on your form');
  echo $greetings;

Save this as test.php then execute this with drush php-script test.php.
Third, once your service is working as you want, integrate your service with your form. You should be able to take the PHP script you wrote in step two and insert it almost unchanged into your form submit function. (As a future enhancement, learn how to inject your service into the Form rather than use the static \Drupal::service() call, but that can wait until after you have this working).
Fourth (do this only after you have the above working), examine your need to cache data, and then implement some sort of caching in your service if needed. You haven't shown all your code or completely explained what you're doing, but I don't see anything that justifies using cache.nameofbin or a tempstore.


How to create multiple batch imports Ok I have been working with the batch API and I have one working successfully now I would like to run another batch after the first one.

batch_set says I can do this:

array(
  array('my_function_1', array($arg1)),
  array('my_function_2', array($arg2_1, $arg2_2)),
)

I am trying this, but it isn't running the second function:

$batch['operations'][] = array('test_function1', array($new_node), array('test_function2'), array($new_node));
batch_set($batch);

Any ideas on how to run the second function?

Using more than one function for a batch surely works, as one of the test functions for the batch API contains the following call.

batch_set(_batch_test_batch_3());

_batch_test_batch_3() contains the following code.

  // Ensure the batch takes at least two iterations.
  $total = 10;
  $sleep = (1000000 / $total) * 2;

  $operations = array();
  for ($i = 1; $i <= round($total / 2); $i++) {
    $operations[] = array('_batch_test_callback_1', array($i, $sleep));
  }
  $operations[] = array('_batch_test_callback_2', array(1, $total / 2, $sleep));
  for ($i = round($total / 2) + 1; $i <= $total; $i++) {
    $operations[] = array('_batch_test_callback_1', array($i, $sleep));
  }
  $operations[] = array('_batch_test_callback_2', array(6, $total / 2, $sleep));
  $batch = array(
    'operations' => $operations,
    'finished' => '_batch_test_finished_3',
    'file' => drupal_get_path('module', 'batch_test') . '/batch_test.callbacks.inc',
  );
  return $batch;

What is wrong in your code is how you set $batch['operations'].

The correct code is the following one.

$operations[] = array('test_function1', array($new_node));
$operations[] = array('test_function2', array($new_node));

$batch = array(
  'operations' => $operations,
);

batch_set($batch);


How can I export shortcut sets and shortcut links in Drupal 7? I am using Drupal 7 and I have some shortcut sets (per role using the shortcut per role module) and shortcut links in them and I would like to export them either using the features functionality or with any other exporting mechanism.

But I do not find any relevant exportables in the features exporting options not even in the Strongarm section. Is there a way yo do this or should I manually recreate them in the other site installations?

I have also seen a relevant question but it does not have any answers regarding the shortcuts part.

Finally, managed to programmatically create the shortcut sets and links with the following php script:

<?php
echo 'populating shortcuts...';
$shortcut_set = new stdClass();
$shortcut_set->title = 'Default';
$shortcut_set->set_name = 'shortcut-set-1';
$shortcut_set->links = array(
    array('link_path' => 'admin', 'link_title' => 'Admin',),
);
shortcut_set_save($shortcut_set);
echo ' shortcuts population finished';
?>

as mentioned in this drupal post.

A also had to apply this patch in shortcut module, which fixes the shortcut_set_save function called by the script.


Fresh drupal install shows drupal core warning I recently installed drupal using git clone option and updated it using composer but I am getting this error I can't fix.

Is there any way to fix this issue? clicking on available updates won't fix the issue. Also, the error related with "LIMITED DATE RANGE" seems mistaken, because I have php7 installed on a 64bit system

Since you used git clone, you probably pulled from the HEAD and are running a development version of Drupal. Your Drupal installation does not have an official version number, so it cannot be detected. You can install Drupal with composer, download the zip, or try to clone a tagged release (I always used composer so I am not sure if a tagged release works).

As for the 32/64 bit warning. Depending on the PHP version you have installed, you can run a 32bit PHP installation on a 64bit OS. I suppose that is the root of your problem.


Putting sites online Well, I'm finally ready to put my five-site multi-site installation online. This community has been a great help in getting me to this point. So thank you all for that.

I'm a bit nervous about the gotcha's that await me in this next step -- discovering differences in operation between my local environment and the one online. I'm running XAMPP on my computer with Apache 2.4.10, PHP 5.6.3, and MySQL 5.6.21. Drupal core and all modules are up-to-date. In addition to each site's database, there is an extra db that is accessed by all sites for common data. For the online system, I plan to select a host company from the list on the Drupal.org, so I can expect them to have all the right stuff. I plan to get a shared server account.

In my current ASP sites (which these Drupal sites will replace), I've been able to develop the sites entirely on my local computer and then just upload the files to the online server and I don't think I've ever had a problem with any differences in operations. My scripts are set up to detect whether they are running locally or online and adjust certain things (such as inter-site URLs accordingly). I've attempted to develop things in Drupal to work that way too, but I'm not sure if there are differences I don't yet know about. I'm concerned about this because on the ASP sites I never had to instal any software. The server company instals whatever is necessary to run the site and I just uploaded files compatible with their software. But in Drupal, I've had to instal Drupal over again for each site, so I'm a bit unsure about how this will translate to the online environment.

So one question I have: Is it possible to simply FTP the entire Drupal folder plus the MySQL database to an online server and have a functioning set of sites, or do I need to go through the installation process on the online computer again for each site?

The doc page on Migrating a site says that it is for single site and that migrating multi-sites is covered elsewhere, but doesn't say where. Even for a single site, it lays out a 16-step process in which I don't think I'll understand most of the steps until I've done them. In any case, that page seems to say that the answer to my above question is very much NO, that I cannot do this by just copying files over.

Anything helpful to suggest on entering this process?

To answer your question: Yes. All you should need is your code sitting on a web server and your data sitting in a database for your Drupal site to go live.

As for suggestions, I have a few regarding workflow. Drupal has a lot of pain points with deployment because not only is the content stored in the database, but most of the configuration is as well. So while you can upload modules, the settings need to be manually set on production, automatically deployed with the Features module, or automatically deployed with update hooks in modules.

Uploading your site for the first time via FTP will work, but it's usually a lot more complicated when deploying updates. Here are a few things that you should learn to help combat this:

My first suggestion would be that you set up a development server (your local dev will work), a staging server to test your deployments, and a production server which will host your live site. It's crucial to have this (or something similar) so you can catch any problems and avoid a production down situation.

Second, you should learn how to use Git for version control to manage and deploy your code. You should use it for all projects, actually, even if you're not deploying them. I cannot tell you how many times I've rolled a change to production that broke the site and was able to roll back with one command. I'm not going to try and convince you why using version control is a good idea because there is an entire internet that says you should. Here is just one article: http://www.git-tower.com/learn/git/ebook/mac/basics/why-use-version-control

Third, assuming that you're using Drupal 7, you should use the Features module to store your settings in code and deploy them via git. Features is a necessary evil in order to accomplish this, and there are a ton of quirks that give it a huge learning curve, but it's worth it in the long run. This answer seems pretty solid. A more advanced and custom approach is to use calls to hook_update_n in your modules to automatically deploy database updates and settings. This article Does a good job explaining it.

Fourth, and probably most importantly, BACK UP YOUR DATABASE AND YOUR CODE. As I mentioned before, Drupal makes heavy use of the database. If you lose that, you lose your site. Make sure you have scheduled backups for your database (and your code if it isn't in Git).

I'm not trying to scare you, but I'll be honest: if you do decide to go this route (and I believe I'm not the only one who thinks you should), there will be a lot to learn and a ton of frustration at first. I can tell you that you're going to have a maintenance nightmare on your hands if you plan to deploy updates by uploading files via FTP.

I have been to a lot of talks and training on this subject at Drupal Camps, Drupal Cons, and Drupal meet-ups, and I'm still learning how to manage deployment. Once you learn the tools and get your workflow down, things will go a lot smoother and you'll be able to recover quickly if anything bad happens.

I hope this helps. Let me know if you have any questions!


Create a zip file from a list of selected files and make the zipped file downloadable I have a list of image files. I need to archive those files in zip format and make the archived file downloadable. I have seen ArchiverZip class defined in the system module of Drupal 7. But I couldn't be able to create a zip file. How can I do this in Drupal 7 ? Is there any hooks or custom modules for this ? Please help me out with this.

UPDATED
Following are the codes:

$zip = new ArchiverZip('archive.zip');
foreach($_POST['img'] as $fid):
    $query = db_select('file_managed', 'fn')
            ->condition('fid', $fid)
            ->fields('fn', array('filename'));
    $result = $query->execute();

    foreach($result as $row) {
        if(file_exists('sites/default/files/'.$row->filename)){
            var_dump($zip->add($base_path.'sites/default/files/'.$row->filename));
        }
    }
 endforeach;

And this reflects the following error

  Exception: Cannot open archive.zip in *ArchiverZip->__construct()* (line 91 of basepath\modules\system\system.archiver.inc).

Please help me with this . .

Make sure you include the class

module_load_include('inc', 'zip_archive', 'zip_archive.class');

Also check permissions for archive.zip file. Create one if its not there.


How to make the main menu expanded? I have set main menu items expanded but when I print them in page.tpl.php($main_menu) there are no children for menu items.How can I make them expanded?

Go to admin/structure/menu/manage/main-menu and edit the parents that have children that you wish to show, and click the tickbox 'show expanded'

Or alternatively install the module http://drupal.org/project/menu_expanded which brings back the tickbox on the menu 'list items' page ala drupal 6

Hope this helps


How can I limit and show only the first referenced node per node in a view? I have content type A with a field that references nodes of type B. This is field with multiple values.

I need to show all the values of content type A, and include one of the fields of the referenced content type B (an image). So I created a view showing these fields.

The problem is that I just want to show the first result of content type B and eliminate the duplicates of content type A. So according to the post Only show first entity reference in views, I used the module Views Distinct. And it works, the problem is that I have more than 2000 nodes and the query is very very slow.

So the next thing I thought was to use the Infinite Scroll module to make it faster. And this works, but the problem now is that I need to group the results by a field, and with this module the header of each group is being repeated, every time results are loaded.

So I thought I could use the Delta for the reference field, and filter it to the nodes with delta = 0, but I don't know why the first value is not 0 is a different number. So this option is not valid.

Does anyone know how to show only the first reference with a good performance?

I can suggest you one solution which will probably help you with performance.

You can make use of views field view module.

You can use the view which you have created to render the fields of content type A and now create a separate view (as block) of content type B with current node ID as contextual filter and required relationship for the reference field and set limit to 1 or use delta as filter and call this view as field in the view in which you have rendered content type A fields.

EDIT: Second view can be called conditionaly wherever required, so is more handy if you require it only once in the parent view (by result count or once in header) OR get rendered it with every result of parent view.


HTML5 Video showing both Source and Flash fallback I'm experiencing a sudden problem with an embedded HTML5 video on my Drupal site. At first I thought it was a problem with my HTML5 code, but I believe the problem is with the WYSIWYG editor within Drupal.

I have a video in several formats, and want have a Flash fallback for those less fortunate.

Here is my code:

 <video width="480" height="320" controls="controls" poster="poster.png">
    <source src="video.webm" type="video/webm" />
    <source src="video.mp4" type="video/mp4" />
    <source src="video.ogv" type="video/ogg" />

    <object width="480" height="320"
            data="moxieplayer.swf" type="application/x-shockwave-flash">
       <param name="src" value="moxieplayer.swf" />
       <param name="flashvars" value="url=video.mp4&amp;poster=poster.png" />
       <param name="allowfullscreen" value="true" />
       <param name="allowscriptaccess" value="true" />
    </object>
 </video>

Everything was working as expected. Then I opened the WYSIWYG editor, Disabled rich-text to get to the HTML, and added the "poster" attribute. I clicked save and, ever since, it has been showing TWO videos: the main source and the Flash fallback.

I found that odd so I removed the poster attribute (going back to what I had before), but the problem remained.

I know what the problem is... It became apparent when I viewed the source in the browser. The source is being rendered like this:

<video width="480" height="320" controls="controls" poster="poster.png">

      <source src="video.webm" type="video/webm"></source>

      <source src="video.mp4" type="video/mp4"></source>

      <source src="video.ogv" type="video/ogg"></source>
    </video>

  <object width="480" height="320" data="moxieplayer.swf" type="application/x-shockwave-flash">
     <param name="src" value="moxieplayer.swf" />
     <param name="flashvars" value="url=video.mp4&amp;poster=/" />
    <param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="true" />
 </object>

Notice that in the rendered code, "object" is now outside the video tag. I'm guessing that's the problem. For whatever reason it was fine, then I edited the code to add the poster, and rocking the boat has resulted in this issue. I am in "Full HTML" mode when making my edits.

Unfortunately, disabling WYSISWG isn't an option as my customer needs to use it. This is a bit frustrating as I suspect that may be the issue. I'm using TinyMCE 3.5.10.

Does anyone have any suggestions on how to deal with this problem?

Thank you very much!

In these kinds of cases, the easy fix would be to add a second text field for "embed code" outside the main wysiwyg area. If you set it to use a new "HTML without linebreaks" text formatter, that'll help eliminate any wackiness on the "Full HTML" default setting.

Protip: use the Better Formats module to stop the user from having to choose a format for this field. That way, they can just paste and forget.


Search API Referencing entity relations I am working on a project where i would like to be able to create a search api view that has a relation to the referencing entity.

The use case:

I have a content type: Products page that holds the commercial information about the product

I then have a content type Product that holds all the specifics (article number, serial numbers etc)

I have created a search api view on the content type Products Page that shows all the commercial information in the catalog with some facets end an exposed full text search box.

Each product node has an entity reference to the Products page node it belongs to

Of course, i would like visitor to be able to search for article numbers in the fulltext search. The result needs to to show the Products Page node that is being referenced by the product node that holds the article number that was searched for.

However i cannot see how i can create the relation that you would normally use when using a regular view?

Addtionally and example below:

Products Page node: Chairs (with body and image)
Product nodes:
- Wooden chair (art nr 123, and entity ref to Chairs)
- Metal chair (art nr 456, and entity ref to Chairs)

So when ppl search art nr 123, i want my view to show the Products page node "chairs".

Thanks in advance!

Implement hook_entity_property_info_alter()

function MY_MODULE_entity_property_info_alter(&$info) {
    $info['node']['properties']['article_number'] = array(
        'type' => 'text',
        'label' => t('Article number'),
        'getter callback' => 'MY_MODULE_get_article_number',
    );
}

function MY_MODULE_get_article_number($node) {
    if ($node->type == 'product_page') {
        // Return the article number from the referenced product node
    }
}

Go to admin/config/search/search_api/index/{index_name}/fields and select the property. Now you can use this property like any other field.

In your case you need to configure this field in you view. I assume you added Search: Fulltext search to your filter criteria. Click on this filter and add the property to the Searched fields settings.

I hope this works for you.


How can I disable a path from a view? I have some views I want to keep, and maybe use in the future.
currently I am not using them and want to disable the path, or leave it as "No path is set".

but all the I'm I am getting the following message:

  Display "VIEW" uses a path but the path is undefined.

can someone tell me how can I leave a view as "No path is set" and be able to save that  not set?

Thanks!

You should disable the view by going to
Structure -> views
Inside views on the right side there will be a tab and when u click on it you can disable the view so that you can enable it for future use.


How can I bypass the login screen during checkout in Commerce 2? I'm building a site where I want to allow guests to purchase without creating a user account. This appears to be default behaviour in Commerce 2.1 (the message stating that the user can create an account at the end of checkout is currently not implemented although I know work is being done on that in this issue https://www.drupal.org/node/2857157).

However, I also don't want to offer guests the option to log in, which is what currently happens.

So, I want to simply bypass the Login page and go straight to the checkout page.

I was able to solve this problem by editing the Default checkout flow at /admin/commerce/config/checkout-flows, where I could simply disable the Login or continue as guest step.


Drupal Album/Photos modules error. Not show photos/image/uid www.sitename.com/photos/image/697 --> go... But, not show image and other content and blocks...

Error messages:
1- Unable to generate the derived image located at public://styles/large/public/photos/image_1/6396455561366990133.jpg.

2- DrupalDefaultEntityController->load() array_flip() [function.array-flip]: Can only flip STRING and INTEGER values!.

3- format_date() /includes/common.inc dosyasının 2014 line) date_timezone_set() expects parameter 1 to be DateTime, boolean given.

Help me please...

The problem was the Photo Information Block being inactive; it has been now fixed.


How to pass Webform elements from controller to custom twig template I'm pretty new to Drupal and probably this is simple but I got stuck with this.

What I'm trying to do:
I have created a custom module where I have defined a custom route to display my webfrom in custom twig template.

How and what to return from Controller so my webform elements will be available in custom twig template.

my_module.module

/**
 * Implementation of hook_theme
 *
 * Since we have a lot to explain, we're going to use Twig to do it.
 */
function my_module_forms_theme($existing, $type, $theme, $path) {
  return [
    'my_template' => [
      'variables' => ['test_var' => NULL],
      'render element' => 'form'
    ],
  ];
}

my_module/src/Controller/MyModuleController.php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;

class MyModuleController extends ControllerBase {

public function content() {
    $my_form = \Drupal\webform\Entity\Webform::load('my_form_id');
    $form = \Drupal::entityManager()
      ->getViewBuilder('webform')
      ->view($my_form);

$build = [
  '#theme' => 'my_template',
  '#form' => $form,
];
return $build;

}
}

In my twig template, I want to be able to use form elements like below.
Please let me know how to achive this.

my-template.html.twig

{{ form.element.name }}
{{ form.element.email }}

Thanks

my_module.module:

/**
 * Implementation of hook_theme
 *
 * Since we have a lot to explain, we're going to use Twig to do it.
 */
function my_module_forms_theme($existing, $type, $theme, $path) {
  return [
    'my_template' => [
      'template' => 'my-template',
      'variables' => ['form' => NULL],
    ],
  ];
}


How to export posts in excel? I want to export posts with only these data to Excel:

Post title
Post URL
Author
Publish Date

How can I do so?

Use the Forena module to create a "report" that includes the data that you're interesting in (Post title, Post URL, Author, publish Date). As part of the report design, indicate which export formats you want to allow for exporting the data included in it. XLS is one of the typical formats that are supported, but their could be other formats enabled also, such as CSV,  XML, HTML, etc.

Have a look at the Simple Table of States example, and think of it as the equivalent of your "posts that you want to export". And note the hyperlinks in the upper right, which are:

CSV.
XLS.
HTML.
XML.

Try any of these links to get the equivalent of the extracted information, but in the format you requested (there or other supported formats such as PDF, DOC, JSON, etc).

Checkout Forena's Community Documentation for (way) more details, and/or the documentation that comes with the module.

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


Simpletest fatal error without message locally my unit tests run just fine. On my online dev server, they fail and I don't get any error message despite "The test did not complete due to a fatal error." in the test messages and "An internal server error occurred. Please try again later." as return text of the batch process. No entry in the default error log, no error log file in the temporary simpletest public directory.

Is there any way to debug this and get the stack trace etc?

When I run the tests via Drush, they work just fine. This issue occurs only with the testing user interface and might be related to the PHP memory_limit as I run on a shared host.

The point where the test fails seems to be arbitrary: Sometimes it comes as far as 200 asserts before failing, sometimes the fatal error occurs after only 40 assertions. Also the test function from which the error is thrown differs, but they all belong to the same class.

Figured it out ... The hoster I use (uberspace.de) has a timeout for script execution time. Some Simpletest tests do not respond for several minutes, which triggered the timeout.


cache_render database table growing in size I am having a drupal 8 website where cache_render table is growing to GBs. I am not sure why this growing huge, any starting pointers would be helpful.

Thanks

There are some ongoing improvements to e.g. cache 404 pages only for a short time.

Make sure that cron is running, so that expired caches are deleted.

Also consider using an alternative cache backend like Redis or Memcache, both have a max size that the allocate and delete items that have not been used for a while.


How to send a custom Solr Query using Search API Solr I'd like to send custom solr query (preferably in hook_init) using Search API Solr to a specific URL.

Something like:

function hook_init() {
  $url = "admin/luke?show=schema";
  $solr = new SearchApiSolrService(); // must have an instance of SearchApiServer
  // $httpTransport->performHeadRequest($url);
  // $response = _sendRawGet($url);
  drupal_set_message(print_r($response, TRUE));
}

How I can do achieve that? Is there any live example?

Thank you.

From version RC4 you can use makeServletRequest() to generate custom solr queries. See some examples on GitHub.

Here are some code examples:

  // Ping example
  // class_exists('Apache_Solr_Service') ?: spl_autoload_register('_search_api_solr_autoload'); // make sure that SolrPhpClient class is loaded (use only for <=rc3)
  $server = search_api_server_load('my_solr_server'); // CHANGE THIS
  $solr = new SearchApiSolrService($server);
  $result = $solr->ping();
  drupal_set_message(print_r($result, TRUE));

  // Simple search query (not fully tested)
  // class_exists('Apache_Solr_Service') ?: spl_autoload_register('_search_api_solr_autoload'); // make sure that SolrPhpClient class is loaded (use only for <=rc3)
  $server = search_api_server_load('my_solr_server'); // CHANGE THIS
  $index = search_api_index_load('my_index'); // CHANGE THIS
  $query = new SearchApiQuery($index);
  $query->keys('foo');
  $query->fields(array('title'));
  $solr = new SearchApiSolrService($server);
  $result = $solr->search($query);
  drupal_set_message(print_r($result, TRUE));

  // Custom path example for rc4 and above (not fully tested)
  $server = search_api_server_load('my_solr_server');
  $uri = SearchApiSolrConnection::LUKE_SERVLET . "?show=schema"; // or any other custom URL
  $connection = $server->getSolrConnection(); // or: new SearchApiSolrService($server)
  $response = $connection->makeServletRequest($uri);
  drupal_set_message(print_r($response, TRUE));

  // Example for assembling the right URL
  $server = search_api_server_load('my_solr_server');
  $url = 'http://' . $server->options['host'] . ':' . $server->options['port'] . $server->options['path'];

Above code tested in hook_init with Drupal 7 and Search API Solr [rc3].

Acquia

If you're using Acquia, you can use Acquia-Search-Proxy which allows you to send custom queries against Acquia Search (Apachesolr + Search API Solr). See also my fork of Acquia-Search-Proxy which include some extra improvements.

Example custom queries via CLI:

PATH_INFO="/admin/ping" php search-proxy.php
PATH_INFO="/admin/luke" QUERY_STRING="show=schema" php search-proxy.php
PATH_INFO="/select" QUERY_STRING="q=foo" php search-proxy.php
PATH_INFO="/admin/file" QUERY_STRING="contentType=text/xml;charset=utf-8&file=schema.xml" php search-proxy.php


Share fields between commerce variation types? I have 12 types of products that have 4 similar property fields, for example: weight, force, collar size, noise level. There are many other different fields for each of the 6 types.

Is there a way to set up Drupal Commerce variation types so 'weight' for example is the same fieldname on all these products types?

I'd like to do this so that a faceted search can allow customers to search for weights or collar sizes, etc, across all product types.

Or any other ideas on how to structure this?
(using Drupal 7 and Drupal Kickstart 2)

Assuming you are asking about Drupal 7, the answer is yes. You can share base field types across product bundles. Each bundle will have it's own instance of the field, but the data will be stored in the same underlying storage system.

You can add them by choosing from the list of fields under "Add existing field" on the field editing screen:


Extra fields in 'manage display' for content types On my old website, there were extra fields such as 'Author', 'Last modified', 'Tags', 'Post date', 'Read more', 'User picture', and 'Comments' available in the 'manage display' section of content types.

I'd like to have these fields on my new website too, but I really can't remember anymore how they got there. Does anyone perhaps know if they were provided by a certain module?

When using Display Suite, you have to first save the layout you're going to use, then the fields will appear.

Under the "Current Template" section, "None" is probably selected. For a default display, select the "One Column layout" and click save. These fields should then populate.


My page is in hook_admin_paths(), but doesn't show admin theme function mymodule_admin_paths() {
  $paths = array(
    'admin-dvr/*' => TRUE,
  );
  return $paths;
}

I have a module which generates a page and I want that page to be themed with the admin theme. I implemented the above hook so that when I browse to admin-dvr/dvr/manage it should be displaying with the admin theme.

On my dev server, this works just fine. When I push that code to production, and flush all the caches, I'll sometimes see it load with the admin theme ONCE, but then every time after that it loads with the mainsite theme.

What am I doing wrong? Why won't it load my page with the admin theme?

I would suggest you place your admin pages under admin/dvr. In that way you should not need to implement hook_admin_paths() at all.


Adding Content to Drupal 7 through a remote PHP script In our system, the content is generated by a standalone PHP script that runs from command line. Is there a way to add this content programmatically to a remote Drupal 7 CMS from this standalone PHP script?

I am not able to find such information on drupal.org. I have found the following code:

$node = new stdClass();

// Set content type
$node->type = 'article';

// Prepare defaults
node_object_prepare($node);

// Define language (currently language neutral)
$node->language = LANGUAGE_NONE;

// Basic content
$node->title = 'Test';
$node->body[$node->language][0]['value'] = 'Body text';

// Example if using custom fields
$node->field_CUSTOM_FIELD[$node->language][0]['value'] = 'Value';
// Example if using fields that are taxonomy type
$node->field_CUSTOM_FIELD_TAXONOMY[$node->language][0]['tid'] = 1;

// Save node
node_save($node);

But this code has to run from Drupal 7 server process only. This code cannot be used in a standalone PHP script that runs remotely. Another option is Entity API but that code too has to run on Drupal Server only. Do I need to create my own module and code my standalone PHP script to connect to API exposed by this module?

Services module can be used to allow to create node remotely

Check out some reference links as below

https://groups.drupal.org/node/144394
How do I POST a new node using the Services module?
https://drupal.org/node/1354202


How to get all database which can be used in 'db_set_active' Is there any way to list all possible database connections using Drush?
I am debugging an application where db connections are not written in settings.php and I'm not able to find all possible connections. And in code I can see

$database = db_set_active('test');

Is there any way to list the db connection names like test, test1, test2?
Any help is appreciated.

All database connection strings are in global $databases variable;

global $databases;
dpm($databases);

with drush:

drush php-eval 'global $databases; print_r($databases);'


Ajax call module function I need to make asynchronous page requests on every page load using AJAX, the idea being that a function in my module is called even when pages are cached.

The only documentation I've been able to find (Drupal 7) is for form handling using AJAX and handling links.

How do I call a module function from a custom AJAX request? Would I just implement hook_menu() and write a custom ajax request or is there a better way of doing this in Drupal 7?

I guess the answer depends on what that ajax call does, and if it is for a 'one site use' or for a contribution module.

If it s for a contribution module hook_menu might be the only way to go.

Though if it s just for a 'one site use' i would just add a JS snippet in your page.tpl.php or even html.tpl.php that launches the Ajax query. This would work on every page even when if cached.

EDIT
Actually you could also use the page preprocess function and add a js file to all your pages.


how to detect current language to show the other(s) in the menu I'm using i8n to host a bilingual site and I only like to display the inactive language in the top bar. What php code do I need to detect the current language so I place the inactive language in the template?
Thanks:

<a href=
<?php
global $language;
if (($language -> name) == 'English') {
print "\"http://www.mangallery.net/fr\"".">french";
} else {
print '"http://www.mangallery.net"'.">english";
}
?>
</a>

Use the global variable $language

https://api.drupal.org/api/drupal/developer%21globals.php/global/language/7


5 second delay caused by itok I recently noticed a 5 second delay on my Drupal 7.34 website which I think is being caused by itok (a new security token used for files, like images, that are modified by Drupal).  How do I remove this delay?  Do I have to disable itok?

For instance this image takes 5 seconds to load.

If you can, look instead at serving the image as a public file, so that your webserver can return it directly without loading Drupal at all for that request. Instead of seeing system/files in the path, you'd see a path to the actual image file on your server - eg sites/default/files/.

Review whether it's necessary to serve images using the Private download method, which introduces a Drupal bootstrap and access controls on all static file requests. The default for this is configurable at admin/config/media/file-system.

It may be you're seeing a delay across all requests handled by Drupal, and have noticed it because you'd expect serving a static file to be quicker than that? Note that requests for static files (eg your logo) are not similarly affected, but for me I see ~6s response time checking the more basic pages on your site (eg curl --head against your donate page).

Is your server overloaded, or do you have modules enabled which might be performing time-consuming operations (eg network activity, DNS lookup, ...) for every request?

A patch in d.o#2089789 gives you a means to remove the itok token if you do need to serve that image after checking Drupal's access controls.

The reasons for introducing itok are discussed in the Drupal 7.20 release notes.


Change Input Field Value using Hook Form Alter (User Login Block) How would I go about changing the input field value from e.g. 15 to 10 in the default User Login Block for Username and Password fields, using Hook Form Alter?

Put this in your module:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login_block') {
    $form['name']['#size'] = 10;
    $form['pass']['#size'] = 10;
  }
}

Also hook_form_user_login_block_alter can be used, then you don't need to check the form_id.

Remember to clear the cache, if you are not already using hook_form_alter.


How to tell if you are on a view page in preprocess_page I am trying to see if we are on a view page in the preprocess_page function in my MYTHEME.theme file.

views_get_page_view() gives me an undefined function error.

I want to get values from my view to display outside the view area in page.html.twig

That function will error because it does not exist in Drupal 8.

You can do this though:

$view_id = \Drupal::routeMatch()->getParameter('view_id');
$view = \Drupal\views\Views::getView($view_id);

Be sure to validate view_id first though, that it exists/length before calling the second line.


How to add slider to show multiple view's product in a slider in commerce site of drupal 7? I am working on Commerce Kickstart. In my homepage there are 3 views & each view contain 3 product. Each view's products are shown in a column like below image :

I want to add slider to show all products by clicking "< >" arrow. How can I implement. Please Help. Thanks

you can achieve your requirement using views_slideshow module.

Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View.

News item slideshow (such as the title, image etc).

The Last X number of X submitted (images, videos, blog entries, forum posts, comments, testimonials, etc.).

Rotate any image, based on any filters you can apply in views.

Hottest new products for any ecommerce drupal site.

Rotate contact links, share links, etc.

Implementation :

Steps:

Enable view slideshow module.

Create a view using existing content type(ex-product).

View format: Slideshow

Add item for slideshow (such as the title, image etc).

For getting Next & Previous link

Goto view slider settings

Enable the controls as text.

It displays 'next','pause' and 'previous' link

Later you change the css as per requirements.


How do I add a Javascript library to a field formatter? I'm trying to include a Javascript gallery (jQuery lightGallery) on my new Drupal 8 site and wrote a field formatter for this purpose.

Now I need to add the jQuery lightGallery to pages using this field formatter and call the library when the page is ready. I am confused about how I am supposed to do this, though.

I defined the library in the module containing my field formatter, but I'm not sure how I attach it only on sites that contain the field.

The documentation of the library uses the jQuery $(document).ready function to call the libary, how would that work inside a Drupal module?

In your formatter's viewElements

public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
  $elements[$delta] = array(
    '#theme' => 'theme_name_if_any',
    '#variablenametobepassed' => $this->viewValue($item) * 20, // any other preprocessing
    '#attached' => array('library'=> array('module_name/library_name')),
  );
}

return $elements;
}


Commerce Line Item Taxonomy Reference Filtered by Product Selection Here's the scenario:

I'm selling furniture. I have a chair we'll call Mission Chair.
The Mission Chair comes in oak or maple, both are priced differently. I have a field in my product
I have a product display created which references these 2 products
Customers need to choose 1 of 5 stain colors, but each type of wood has 5 different choices (and they're not the same choices)
The stain choice is required, but does not affect the price.

In my Product Variation Type, I have a term reference field which is referencing a Wood Species vocabulary.

I assume I would create a term reference field on the line item type where they would make the stain color choice. What I need to figure out is how do I do some kind of contextual filter to only show the stains available for the chosen wood species? (which is a taxonomy term on the chosen product - not the display, the product variation)

Should the stains be child terms in the same vocabulary as the wood species, or should it be a separate vocabulary with an additional term field that references a specific wood species (taxonomy reference, the same vocabulary the product variation uses) for each stain color term, and then filter on that somehow?

You have two basic approaches you can use: either treat the stain color as a customization or treat it as a second attribute.  Which you pick depends on a little on your backend process needs and the experience you want to provide.

If you use a second attribute and have a product variation for each stain in each wood, Commerce's default add to cart form should provide the user experience you are describing. You might find it helpful to take a look at this tutorial.

If you want to treat stain as a customization you'll likely want a couple extra modules -- in particular Commerce Customizable Product.  Commerce Guys have a tutorial covering that scenario.


Why does dpm() sometimes fail and krumo() works They both dump variables in the same format & style. From some articles or documentation that I'd read, it seems krumo() calls dpm().

The problem is that sometimes I call dpm($var) and nothing happens, but krumo($var) on the same script works fine. I think I'd had the same problem in the reverse circumstance(ie: krumo($var) does not work, dpm($var) works). Why is this so? Is there some structure that needs to be available on the particular page or script that either of these functions uses for it's display? Maybe some region or block?

typically inline php code such as a views php field value, or a Display Suite code field for example ... doesn't always run in a page's context.

When you have a field expecting <?php  /* some code here */ ?> this is run an Anonymous php function and returns a value.

In my experience dpm() doesnt always work in these cases.

Another example is trying to dpm within a Cron or Queue task. These dont run in a page context either so using something like Devel's dd function can be useful.


Alternative ways to programmatically add user fields? Currently i use this to programmatically add user fields:

function openid_connect_entity_base_field_info(EntityTypeInterface $entity_type) {
    if ($entity_type->id() === 'user') {
        $fields['field_family_name'] = BaseFieldDefinition::create('string')
          ->setLabel(t('Family Name'))
          ->setDescription(t('Add a description'))
          ->setRevisionable(TRUE)
          ->setTranslatable(TRUE)
          ->setDisplayOptions('form', array(
            'type' => 'string_text_field',
            'weight' => 30,
            'default_value' => 0,
          ))
          ->setDisplayConfigurable('form', TRUE);
      }
return $fields;
}

but it results in the admin of the site unable to uninstall my module as shown:

Are there any alternative ways to programmatically add user fields without causing the admin of the website to be unable to uninstall the module that programmatically added the user fields?

I found a solution using .yml files in your modules config/install directory.

1. Create the user field

go to Configuration -> People -> Account Settings -> Manage fields and press "+ Add field". I'd recommend giving the field a unique machine-readable name to prevent conflicting user fields.

Enable the user field in Manage Form Display and Manage Display if you want it to appear in the users edit profile and registration page.

2.Exporting the user field configuration

go to Configuration -> Development -> Configuration Synchronization -> Export -> Single Item

Once you get to a screen similar to the one below, set configuration type to "Field" then set the configuration name to the field you have created.

In your modules Config/install folder(create one if needed) create a new file named after filename highlighted in red below.

Finally Copy the yml text into the file you just created.

then set configuration type to "Field Storage" then set the configuration name to the user field you have created.

In your modules Config/install folder(create one if needed) create a new file named after filename highlighted in red below (don't copy the one in the example your user field will have a different name).

Finally Copy the yml text into the file you just created.

YOU NEED BOTH YML FILES TO PROGRAMMATICALLY CREATE A USER FIELD

I recommend doing this for each user field you want to programmatically add rather than copying the configuration and changing a few properties.

With this method you can uninstall the module that created these user fields.


How to keep password form populated ever if the validation fails on registration On the registration page when the validations for profile fields fail, the page is refreshed with error messages. The problem is that then the password form is cleared even if the user has already entered an acceptable password.
Is there any way to keep the password populated even if the page is refreshed after the validation fails?

The password form field is always cleared out when re-submitting the form after a validation handler reports an error.
There isn't a workaround to that, as the password form field is not using the "#default_value" property that usually other fields would use to pre-populate the fields with a value that is then edited from users. If you use the "#value" (supposing that would have any effect for the password form field) then that value would override the value entered from the users.


how to create a custom form and embed it on a node Right now, I want to create a form which only have an email textfield and a submit button.

This is what I did in my "custom_request_price.module":

function custom_request_price_form(&$form, $form_state) {

  $form['email'] = array(
    '#type' => 'textfield',
    '#size' => '20',
    '#maxlength' => '255',
    '#required' => TRUE,
  );
  $form['email']['#attributes']['placeholder'] = 'Email Address';

  $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Send');
  );
}

However, I don't know how to embed it to my article. I don't want to add this into a menu or make this as a new page. What I want to do is: when I open my article page, it directly showed up and visitors can enter their email address and simply to click "send" button.

My search:
For doing this, I thought I need to add "drupal_get_form()" in my node-article.tpl.php to show this form on my article page. I am totally new for doing this. I don't know how to add form-ID in my custom module. Also, I don't know whether this is the correct way to embed my form.

The way I would go about it is to create the form within a Drupal block. In this manner, you could configure when & where the form could be placed on the page and with what types of content. You also wouldn't have to edit your theme if you'd ever wanted to add the form to another type of content.

Look at hook_block_info() & hook_block_view(), and reference the user module's implementation (user_block_info() & user_block_view()) for how it create its user login block.


add popups window with link I want to build popups in Drupal 8. This is the code I am using.

$attr = array(
 'attributes' => [
   'class' => ['use-ajax'],
   'data-dialog-type' => 'modal',
   'data-dialog-options' => Json::encode([
     'width' => 700,
   ]),
 ]
);
$url = Url::fromRoute('resume.grade_detail', ['uid' => $id, 'courseid' => $courseid]);
$internal_link = \Drupal::l($average, $url, $attr);

return array('#markup => $internal_link);

In the rendered output, i don't find the CSS classes I added; as result, the popup doesn't work.

I need help.

The markup element strips some HTML tags from the output. It is much better to just use the following code.

$attr = [
 'attributes' => [
   'class' => ['use-ajax'],
   'data-dialog-type' => 'modal',
   'data-dialog-options' => Json::encode([
     'width' => 700,
   ]),
 ]
];
$link = Link::createFromRoute($average, 'resume.grade_detail', ['uid' => $id, 'courseid' => $courseid], $attr);

return $link->toRenderable();


How to set number of articles per page on the Blog module? I came across a 6.15 drupal site that I had to modify one simple thing:
put instead of 3 articles per page , 5
on the front page the blog resume is shown, and it seem that the blog module doesn't have any setting to do that..
It isn't made with views, nor is it a block.. I don't even know how they get to the front page (probably by being promoted..)

here a snapshot of what I see on the front page...

how can I set the number of articles?
I can't find it anywhere...
I was thinking of defining a view or something and renounce of this built-in functionality...

Looking at blog_page_last and node_page_default, I see that both use the persistent variable called "default_nodes_main" (which defaults to 10) for the number of nodes per page. That variable can be set on the form at /admin/content/node-settings, under "Number of posts on main page".

The above means that both the /node and /blog pages use the same value. If you want different values for both pages, you probably need to rebuild one (or both) of them as a view.

I hope that answers your question.


Save image in any weight and immediately reduce it I am building a site using drupal 7. I created a node form for users to write content and upload images (using the core image field).

Is it possible to let users to upload images of 5-10 MB (and more), and immediately reduce the weight of the image to only 1 MB, and only then save it on my Drupal site?

My goal is that user will be able to upload any image size they want, but still save space on my Drupal site.

I'm finding that drupal 7 does that out of the box (although it's possible I have a module doing it.  Rather than fixing the size of the file, set the max pixels for the image and drupal will resize it (and thus reduce the size) on upload.


Which kind of views style to use JS image effect? I wonder which kind of views style do I choose to make a page like it can be done with masonry.

Actually I use Susy 2, and the example present items in div, actually I get items in a ul via views. Which is better?

Try using Views Fluid Grid - jQuery Masonry module.


Display Location of node Title different in Teaser vs Full I created a custom template, node--article.tpl.php which renders my field_image field first, then shows the submission date, then displays the title and then renders the rest of the content.

This works very well in Teaser, but when I click on the node and view it in Full, the Title is rendered at the top. It is above the field_image instead of where it exists in the template. My template is just a slightly altered version of the Zen node.tpl.php. Why is the title being rendered up top instead of where it is in the template?

Here is my template:

<article class="node-<?php print $node->nid; ?> <?php print $classes; ?> clearfix"<?php print $attributes; ?>>

  <?php print render($content['field_image']); ?>

  <?php if ($display_submitted): ?>

      <?php print $pubdate; ?>

  <?php endif; ?>

  <?php if ($title_prefix || $title_suffix || $display_submitted || $unpublished || !$page && $title): ?>

      <?php print render($title_prefix); ?>
      <?php if (!$page && $title): ?>
        <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

      <?php endif; ?>
      <?php print render($title_suffix); ?>

      <?php if ($unpublished): ?>

<?php print t('Unpublished'); ?>

      <?php endif; ?>

  <?php endif; ?>

  <?php
    // We hide the comments and links now so that we can render them later.
    hide($content['comments']);
    hide($content['links']);
    print render($content);
  ?>

  <?php print render($content['links']); ?>

  <?php print render($content['comments']); ?>

Just a thought, have you tried using Display Suite?


Boolean fields configuration - How to enter a string in ON/OFF value bigger than allowed? How to enter a bigger string than allowed in boolean fields?

When I try to submit a string bigger than a certain value, the string is automatically cutted.

I want to put this text:

  (4% du montant total de la location et 0.5 .- par jour et par personne pour l’assistance/rapatriement en cas de location à l’étranger)

But only this is allowed:

  (4% du montant total de la location et 0.5 .- par jour et par personne pour l’assistance/rapatriement en cas de location à l’étr

Trim the field down to something suitable so it makes sense, something like - 4% du montant total de la location et 0.5, and put the rest into the description field.


How to create text base field without format? How to create base field without format surplus?

E.g. this

$fields['data'] = BaseFieldDefinition::create('text_long')
  ->setLabel(t('XML Data'))
  ->setDescription(t('The product XML data.'));

creates two columns in the table:

`data__value` longtext,
`data__format` varchar(255) CHARACTER SET ascii DEFAULT NULL,

Text (plain, long) field type is string_long.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21Plugin%21Field%21FieldType%21StringLongItem.php/class/StringLongItem/8.2.x


Adding an image to the home page I'm using the Zen sub-theme. I don't want all the new stuff on the site showing on the home page so I'm editing page--front.tpl.php. Removed print render($page['content']). But now I want to add some static text and and image to my home page.

How do I go about doing this basic thing?

You can simply create a node, and put this node (eg. node/15) in the admin/config/system/site-information default frontpage field.

Otherwise you can also create a custom  page with hook_menu() like this:

$items[path] = array(
    'title callback' => 'page title',
    'page callback' => 'page_callback',
    'access callback' => 'access_callback',
    'type' => MENU_SUGGESTED_ITEM,
);

and in page_callback() you can return your  custom theme template/function.

Or simply use some contributed modules like "Empty Page", "Front Page", "Empty Front Page" and others..


How to programmatically add a filter that requires a relationship to a view I have a view filtering out a specific node by nid, and it was working until I added a relationship. I want to filter based on the nid of the target of the relationship, not the base table nid. Here is my code, pre-relationship:

$options = array(
  'operator' => '!=',
  'value' => array('value' => $nid),
);
$view->add_item ($display_name, 'filter', 'node', 'nid', $options);

I tried replacing nid with the view relationship base field alias, but that didn't seem to be recognized at all. How do I indicate to Views that this filter should work via the relationship?

I figured this out by a stroke of luck after posting this. Here is what I did:

// Get a list of all relationships on the view display
$relationships = $view->get_items('relationship', $display_name);
// In case there are no relationships, set this to null by default.
$last_relationship = null;
if (!empty($relationships)) {
  // @todo: is the last relationship always the one whose ID goes with the returned entities?
  $last_relationship = array_pop($relationships);
}
// Filter out the (un)desired item.
$options = array(
  'operator' => '!=',
  'value' => array('value' => $id),
);
if ($last_relationship) {
  $options['relationship'] = $last_relationship['id'];
}
$view->add_item($display_name, 'filter', $view->base_table, $view->base_field, $options);


Alter the conditions in a DatabaseCondition object Would there happen to be a way to alter the conditions in a DatabaseCondition object? Say I have this:

DatabaseCondition Object
(
    [conditions:protected] => Array
        (
            [#conjunction] => AND
            [0] => Array
                (
                    [field] => search_index.type
                    [value] => node
                    [operator] => =
                )

            [1] => Array
                (
                    [field] => DatabaseCondition Object
                        (
                            [conditions:protected] => Array
                                (
                                    [#conjunction] => OR
                                    [0] => Array
                                        (
                                            [field] => search_index.word
                                            [value] => foo
                                            [operator] => =
                                        )

                                    [1] => Array
                                        (
                                            [field] => search_index.word
                                            [value] => bar
                                            [operator] => =
                                        )

                                )

                            [arguments:protected] => Array
                                (
                                )

                            [changed:protected] => 1
                            [queryPlaceholderIdentifier:protected] =>
                        )

                    [value] =>
                    [operator] => IS NULL
                )

        )

    [arguments:protected] => Array
        (
        )

    [changed:protected] => 1
    [queryPlaceholderIdentifier:protected] =>
)

I would like to make changes on the conditions. Any ideas?

You can grab the conditions array for the full query like this:

$conditions =& $query->conditions();

As you're getting the array by reference any changes you make to it (and the conditions within) will be reflected back on the query object before it's executed.

If you want to replace all of the conditions in the query you can simply overwrite that array with a new one (filled with conditions obviously).

It might be safer, though, to loop through the conditions array and remove/alter only the conditions that you need to change. This will make sure that conditions added by other modules will still get their chance to be included in the query.

Editing an existing condition is tricky (I haven't managed to get it to work yet though I haven't tried very hard!). I think your best bet is to rebuild the conditions you need to change from scratch and replace them rather than try to edit them directly.


How to synchronize two check boxes values, upon change? In my module, I have created a simple form with a single checkbox (A) and a submit button.
I also have a checkbox (B) boolean that i added in the user profile.
Now I would like to:

write a submit function that would update checkbox (B) with the status of checkbox (A).
Get rid of the submit button, and have Checkbox B updated automatically  upon change of checkbox (A) status.

I am trying to achieve an email notification on comments system as I described here in a previous post: How to add a checkbox form to a panel?

Thanks,

baba

I got it working this way:

/**
 * Implements hook_block_info
 */
 function mymodule_block_info() {

  $blocks['block_notify'] = array(
                           'info' => t('Notify me'),
                           'cache' => DRUPAL_NO_CACHE,
                           );

   return $blocks;
}

/**
 * Implements  hook_block_view
 */
 mymodule_block_view($delta = '') {

 $block = array();
 switch ($delta) {
               case 'block_notify':
                 $block['content'] =  drupal_get_form('mymodule_example_form');
                 break;

              }
  return $block;
}

function mymodule_example_form($form, &$form_state) {

 global $user;
 user_full = user_load($user->uid);
 $val = $user_full->field_user_message_notification['und'][0]['value'];

 $form['form_notify'] = array(
                         '#type' => 'checkbox',
                         '#default_value' => $val,
                         '#title' => t('Notify me by email when I receive a new message'),
                         //'#description' => t("Check this option to be notified by email when you receive a new message"),
                         );

drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule_request.js', 'file');
global $user;

return $form;
}

function mymodule_example_form_submit($form, &$form_state) {
// Submission logic.
 global $user;
 $user_full = user_load($user->uid);
 $edit = (array) $user_full;
 $edit['field_user_message_notification']['und'][0]['value'] = $form_state['values']['form_notify'] ;
 user_save($user_full, $edit);

 }

Then to trigger form submit on checkbox change I just added the follwing javascript in mymodule_request.js

jQuery(document).ready(

function ($)
{
 jQuery.noConflict();

 $checkBox = $("#edit-form-notify");

 if( $checkBox.length != 0)
 {
    $checkBox.click(
        function(){
            //        alert('hello');
            this.form.submit();
            }
          );

 }
});

I can now just select the "Notify me" block in my panel by " add content" in panels.


Change user picture via services 3 I'm update user profile data via services 3 but I have a problem with user picture. I send user picture to my web site via services and it works:

{"fid":"1078","uri":"http://MyDomain/rest/file/1078"}

But how can I pass this "FID" to the user update method ? Which is the correct parameter name ?

Thanks.

M.

The file ID is stored in the  picture column of the users table

  Foreign key: {file_managed}.fid of user's picture.

So your payload to the update resource would look something like

{
  "uid": "123",
  "data": {
    "picture": "1078",
    # rest of user data
  }
}


Invoke a camera to start in Drupal 7 Forms API I am currently developing a module which must be capable of taking a picture. I dont know how will I make it? How will I invoke a camera to open just by clicking a button? Any idea?

Have you tried the webcams module ? Even if it's dev I'd say it's worth trying.

Do a search on webcam on Drupal and try out some of the modules listed.

Else if you want to develop your own module then the best way is probably doing the integration of an existing webcam jquery module. (See some jquery plugin examples here)


Hide YouTube Video For Some Countries Hello I Am Making A Website On Drupal And I Am Adding A YouTube Video On Some Page So I Want To Hide These Videos From Some Countries example I Want To In Usa So I Want to hide in india  So Which Module Or Way That I Can Do It

Try https://www.drupal.org/project/geo_block. It will allow you to add your video to a block and choose which countries should or should not see it.

Keep in mind however that this, like most other region blocking/detecting tools can be tricked.


Page not found in drupal 7 I am new to Drupal. I added a new content type and a view that points in the google map for the locations I entered

This worked fine in my local site. I implemented the same in the live site. But that gave a page not found error for every page and all the pages are redirected to some another unneccessary page.

Please let me know if adding a view can cause this kind of errors.

I used these modules: Location Map, Geocoder, geoPHP , Geofield and Geomap.

Or did this effect occure because of using these modules?

Check if anything in this list of typical things might help:

Make sure "clean urls" is enabled. Refer to "Clean URL leads to duplicate URL after migration to another hosting" for more details on that.
Make sure the value of "base_url" is set correctly (in your settings.php).

Another option is to check the logs. If you find errors there (like PHP Fatal errors), then try to narrow down that error to the module that causes the error and disable that module (and report it in its issue queue on Drupal.org). If you don't know which module is causing it, then first disable all modules, and enable them one by one again. If at some point the error then comes back, then that must be the problem module causing your problem. Then disable that module again and re-enable all others.


CAS Authentication disable drupal invitation I am using the CAS module to authenticate my users. That is working fine and dandy, but I want CAS to be the only way a user can authenticate. Currently when the user goes to /login, it shows a page where it gives them the redirection notification message, a drupal login invitation message, and a log in button. Only when they click the login button, is CAS authentication conducted. Is there a way to have it so that the only way to authenticate would be using CAS?

I do not know the CAS module but I do know a very generic way to hide / replace any page with another: add an alias! De-aliasing happens before routing. So if CAS has a page say /cas you'd like to see when someone visits /user/login simply add an alias with a system path of cas and alias user/login.


Why do I get the following errors when I install themes and modules on the website locally running on my Mac? I'm just up and running and everything looks OK. Developing locally on a Mac with XAMPP, I have changed httpd.conf to suite my user and group, and FTP is OK. Now I want to install a new theme using "Install from a URL," but when I paste in the URL for my theme and click install, I get the following error:

  Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-cache-26f2422c/responsive-7.x-1.6.tar.gz) [function.unlink]: Permission denied in drupal_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
  Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/color/base.png) [function.unlink]: Permission denied in drupal_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
  Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/color/color-preview.png) [function.unlink]: Permission denied in drupal_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
  Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/color/color.inc) [function.unlink]: Permission denied in drupal_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
  Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/color/colors.css) [function.unlink]: Permission denied in drupal_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
  Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/color/preview.css) [function.unlink]: Permission denied in drupal_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
  Warning: rmdir(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/color) [function.rmdir]: Permission denied in drupal_rmdir() (line 2361 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
  Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/css/layout.css) [function.unlink]: Permission denied in drupal_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
  Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/css/responsive-style.css) [function.unlink]: Permission denied in drupal_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
  Warning: rmdir(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/css) [function.rmdir]: Permission denied in drupal_rmdir() (line 2361 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
  Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/favicon.ico) [function.unlink]: Permission denied in drupal_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).
  Warning: unlink(/Applications/XAMPP/xamppfiles/temp/update-extraction-26f2422c/responsive/flexslider.css) [function.unlink]: Permission denied in drupal_unlink() (line 2197 of /Applications/XAMPP/xamppfiles/htdocs/sandbox/cashbacon/includes/file.inc).

The file permissions are already set to 777.

Go to /admin/config/media/file-system
and change the 'Temporary directory' from
/tmp to tmp


How do I programmatically render a view with contextual filters? How do I programmatically render a view with contextual filters in Drupal 8?

In Drupal 7, I generally use the following code.

$view = views_get_view('test_view'); //test_view is the view machine name
$view->set_display("block"); //block is the view display name
$view->set_arguments($tid); //$tid is the argument to pass
$view->pre_execute();
$view->execute();
$content = $view->render();

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

Basing on the code used by views_get_view_result(), I would use the following code, as code equivalent to the one you show in the question.

  $args = [$tid];
  $view = Views::getView('test_view');
  if (is_object($view)) {
    $view->setArguments($args);
    $view->setDisplay('block');
    $view->preExecute();
    $view->execute();
    $content = $view->buildRenderable('block', $args);
  }


status report asks me to run update.php but getting 'no pending updates' I'm on core version 7.58.

My status report says "Some modules have database schema updates to install. You should run the database update script immediately."

But when I run update.php (or drush updb) I get 'no pending updates'.

I'm not experiencing any problems with the site (except for a small bootstrap-issue that doesn't seem related) and the log doesn't display any errors or warnings.

What can cause this?

Go to systam.module and check for if (max($updates) > $default) { line after this add dpm($module) you will get to know which module prevents this database update and fix that module accordingly. The code will look like below:

if (max($updates) > $default) {
   dpm($module);
   $requirements['update']['severity'] = REQUIREMENT_ERROR;
   $requirements['update']['value'] = $t('Out of date');
   $requirements['update']['description'] = $t('Some modules have database schema updates to install. You should run the database update script immediately.', array('@update' => base_path() . 'update.php'));
   break;
}


Drupal form won't save with TinyMCE (Firefox only) I have a Drupal form with a TinyMCE (3.5.6) instance on it, this is instantiated via the Wysiwyg module. If I save the form in Firefox, it visually displays an AJAX spinner but nothing happens, the form does not save and leaves me on the form. All other browsers work. I can get it to work 2 different ways but not sure why it works and how to translate that to a permanent fix. I have been going through all the suggestions in http://www.tinymce.com/forum/viewtopic.php?id=18821 but have not been successful yet.

1.) If I unminify the code with http://jsbeautifier.org it works without throwing console errors but JSLint throws tons of lint errors in the code.

2.) If I delete the code below it works,

<textarea rows="3" cols="60" name="field_caption[und][0][value]" id="edit-field-caption-und-0-value" class="text-full form-textarea" style="display: none;" aria-hidden="true"></textarea>it works but with the below error:

but throws this error.

NS_ERROR_UNEXPECTED: Component returned failure code: 0x8000ffff (NS_ERROR_UNEXPECTED) [nsIDOMHTMLDocument.implementation]
http://loc.dbtv.nbcuni.com/sites/all/libraries/tinymce/jscripts/tiny_mce/tiny_mce.js?mhcuev
Line 1

Here is a video of the issue at hand => https://docs.google.com/file/d/0B47tip0c_KEtY2w1akUtcFZHYUU/edit

The main fix is linked to in comment #6 of the TinyMCE bugtracker here => http://www.tinymce.com/develop/bugtracker_view.php?id=3152

The source fix is in comment #4 but that won't help many since you need to have an environment to actually compile TinyMCE.


Revolution Slider stuck at loading I need your help. I am running a site (D7.43, jQuery 1.10) with the Jollyany theme under the hood. The theme comes packaged with the revolution Slider from ThemePunch. I am trying to include a slider into a page, but am then confronted with the slider being empty and the loading spinner spinning away merrily forever. Navigation bullets and left right arrows are visible but do nothing.

You can see the page here: wixschool.net/test-class.

This page shows the revolution slider in place. The slider shows the last of three images, constant spinner, no transition to next slide. Navigation also doesn't go anywhere, slider completely stuck. Slider scripts are called in the head, html for the slider is put in place and seems OK.

(In fact the sldier does not even show any picture, but I've removed the 'visiblity hidden" from the CSS of the background image so its easier to see the slider.. and it then shows the last of three images, not the first..)

There were suggestions out there that it may be (double call to) script issue, so I have tried switching off all other scripts that are called in the head  and below the body to see if that would make a difference, but besides losing functionaltiy that those scripst supply the slider stays stuck..

Any suggestions as to why the slider doesn't work is extremely welcome!

Edit: I just noticed that on the test-class page the TB MegaMenu dropdown in the menu don't work (any other page they do..). Tried removing the entire menu as well as the TB Menu scripts but still no working slider..

Reason for Revolution Slider failure found: the Rev Slider uses the hammer.js jQuery plugin. Elsewhere on my site I have installed the jQuery mMenu, which also has hammer.js among its scripts. I disabled hammer.js in mmenu, and the Rev Slider comes alive immediately. The clash centres around the event listeners functions in the hammer script.

Haven't solved all though, mmenu still works fine but I do get a 'where is hammer.js' error thrown at me now of course. Will report when and how I solve that..


How to embed a view (with contextual filters) into a node or another view? I'm using the modules below with the Views module to create a views block of all referenced nodes in the entity reference fields.

Entity API
Entity Reference

There is no problem to create a views that lists all the referenced nodes based on this tutorial.
What I want to do is to embed this views into nodes.
I tried both the EVA and Views Field View modules but couldn't be success (no result). The view I want to embed into nodes uses contextual filters and relationships and I think while using this view into a node or another view, the contextual filter doesn't work.

So, how I can embed this view (with contextual filter) into a node or another view?

Using panels module you can create a "pane view" for your view and easily pass any argument as view contextual filter .

here is a tutorial about views content panes


How to integrate CAPTCHA in a search form with Views I have created a search page with the Views module, which includes a few exposed filter criteria. The form will be available to guest users, so I would like to include a CAPTCHA in the form.

The CAPTCHA module has been installed and works just fine in the user registration, but I cannot figure out how to integrate it inside the search page.

PS: I am using Drupal 7.10.

If you go into the CAPTCHA configuration page, there should be an option to "Add CAPTCHA administration links to forms". If you enable this then visit your views page, an option should appear to add a CAPTCHA next to the exposed filter (the option may be a little mangled depending on your layout, it expands out fine when you click it).

A heads up that this can sometimes generate some extra warnings, see how you go.


I Can't add node of a custom content type I have to add a new content type to my site for a new feature i'm asked. I already added two of them before (very early in the building of the site, in fact) and it worked well but this time, when i want to add a new node, my new content type doesn't appear in the list of content types (node/add).

It appears in the admin/structure/types page but not in the node/add.

I cleared the cache and rebuild permissions but nothing happened.

I also tried to create a very basic new content type but it didn't appear either.

An earlier exchange on this forum showed it wasn't likely to be the taxonomy access control module.

If I do a clean install of drupal and create a new content type, it works but on my site, i can't do it so i don't think it is because i forgot some step.

May it be because of some problem with a third party module ?

I don't think i have installed very exotic ones but i have some (CKEditor, Taxonomy access control, Piwik Web Analytics... )

I'm turning mad so if someone has some clue, it may really help.

Thank you

After following clues mentioned in the above comments (by CodeNext), I was able to solve my problem. The issues and the solution I have compiled as below.

There were two problems.

For some needed reason, I displaced the "add content" menu from "Navigation" to "Redaction" (a new menu). This caused the new content type not appear in the "Add content" page. By displacing the new content type in the "add content" menu, I could see my new content type in the right place.
I had a underscore in the content type machine name. Because of this, i couldn't navigate to the node/add/newcontenttype page (I reached the node/add page). By removing it (the underscore), everything goes now the right way.


Permissions by taxonomy for taxonomy and nodes I have following setup:

Taxonomy Departments (hierarchical in at least 3 levels)

Location A

Team A.1

Subteam A.1.I
Subteam A.1.II
Subteam A.1.III

Team A.2

Location B

Team B.1
Team B.2

Taxonomy "Worker" (taxo ref to "Department")
Content Type "performance review" (taxo ref to "Worker" and to "Department"), one user may have multiple of reviews (they can be done from time to time, like every 3 months)
Users with a specific role ("Manager")

What I need is:

Managers should only see specific departments and all workers in that department
If the manager can see Team A.1 (or Location A) he can see all (Teams and) Subteams also (and all workers belonging to those)
Managers should only see the performance reviews of workers he has access to

The question is:

How do I best go forward to get there?

Problems I found with existing modules and more problems:

You can give node acess based on taxonomy, but those modules don't give access to taxonomy based on taxonomy
To me it would be logic to give the user accounts a new field with reference to the "Department" and build the permissions from there. "Acces by Reference" for example would need me to give the "Department" a reference to users (which you could argue for, but in this project I would prefer the other way (or a synced both-way-solution).
Just in case you wonder about this: The review references the department (instead of always getting it from the referenced Worker taxo), because when workers switch to another department, the review should stay in the department in which it was created

If the only way forward is programming my own module:

Is this a good starting point: https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_access_records/7.x ?

I Think You need to take a look at Permissions By Term and you may need to get an extra step to implement some code to provide the required term and assign it for the required permission according to your required hierarchy.


Pull first image from each node to use in view I want to take the first image from the images each node has in its body, to use it as a thumbnail when displaying nodes in a view. How can I do this?

I've used this regex in my views templates for this task -- it works by grabbing the src from the first image tag in the body content (assumes using fields view style):

$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $fields["body"]->content, $matches);
$first_img = $matches[1][0];

if (!empty($first_img)) {
     print "<img src='$first_img'>";
}

You can also pass the source to your imagecache theme function, as Jim and jimajamma suggest, to scale the image.


Loading a large node body sequentially for better performance I have a few very large nodes on my Drupal 7 site. In some cases the body field contains about 2MB of raw HTML (about 250,000 words). Despite the site performing well as a whole, the sheer size of these nodes causes a complete page render to take about 20 seconds, both due to the amount of content being downloaded and the time it takes the browser to render that much HTML.

The only way I can see to improve performance on these nodes is to load the node body sequentially in small bits, fetching bits of HTML as the user scrolls down the page. Is something like that even possible when all the data is contained in one row in the database? Perhaps this is more of MySQL question, but I'm curious if anyone has encountered this before or has alternate solutions to this problem.

It sounds like you've hit an architecture (DBMS) constraint. I'm not aware of a way to break up a node body into segments easily (I mean i'm sure you could use a list of text fields in drupal -- but ewww).

I'm also not sure of a clean way to make the paragraphs index-able for asynchronous javascript fetching, i believe you run into issues like:
https://stackoverflow.com/questions/19477494/per-paragraph-commenting-system

What I would recommend is installing an in-memory cache like Varnish, or Memcache and storing a copy of the full page for anonymous users ... or learning Authcache for more complex scenarios.


How capture video thumbnail , when video is uploaded under media video type file? I'm using Core media module to upload video[Media Type is video,which has field video of 'file field type'].
This module will refer video.png as thumnail for all video uploaded from the local system.

I want to capture first frame of video as thumbnail when video is uploaded from the local system in media section.
I have seen 'PHP ffmpeg' , module , But i don't know the approach to follow to capture first frame of video.
 If i need to write a custom module to capture thumnail while saving media type of video, which hook function I need to use or please suggest me what apprach I can follow?

You can use https://www.drupal.org/project/media_thumbnails_video for this.
It has a dependency (php-ffmpeg/php-ffmpeg) that requires both the FFMpeg and FFProbe binaries to be installed on your server.


How to make users with administrator role member of all organic groups? Is there a way to make all administrator users a member of all the Organic Groups?

For the moment, if an administrator creates an organic group, the only one who will be member of the newly created group will be this particular Admin user.

Maybe I should just find a way to do it throught a Rule ?

UPDATE
I FOUND HOW:

I found How,

go to your content type and change the widget for your field "og_group_ref" from OG_Reference to Select List


OAuth2 vs Session Authentication I'm setting up a OAuth2 Server using the OAuth2 Server module.  Everything tests out as expected.  I login, get the authentication code, which I then trade in for an access_token, which tests out successfully.

The issue comes when requesting a resource that's handled by the services module.  It looks like it's starting a session for the anonymous user instead of calling the other authentication hooks.

After all, if one authentication method fails, it shouldn't assume that it's the only authentication method possible.

Any ideas on how to use OAuth2 authentication code authorization to access services endpoints?

Here's the snip from services.runtime.inc line 116 where it's only looking for one authentication module, it seems.

foreach ($endpoint->authentication as $auth_module => $settings) {
  if (isset($settings) && $auth_error = services_auth_invoke($auth_module, 'authenticate_call', $settings, $controller, $args)) {
    return services_error($auth_error, 401);
  }
}

Make sure the selected authentication methods are enabled for the server, e.g:

admin/structure/services/list/rest_api


When should I create multiple Displays of a View instead of multiple Views? Is it simply a matter of convenience to create multiple Displays of a View instead of multiple Views, or is there a performance benefit?

Does having any of the following items present in some Displays but not others affect the View as a whole?

contextual filters
content type filters
aggregation

For example, I'm curious whether having a display show just Article content type results, another showing Forum results, another showing a custom Photo content type makes each display run slower.  Or if the Views all share the same content type, but differ only in that one has a contextual filter for nid, and the others don't, do they all slow down?

If I have 30 Displays for a single view, should I refactor it for performance benefit, or just because the UI wasn't meant to show that many Displays.

Code-wise, both Views and displays are represented by objects. When a View is being processed, it loads all it's child displays into memory, regardless if you are rendering only one View in the page you are looking at. While database queries are executed only for the active display, the properties of the inactive displays are still loaded into memory.

This means that if you have 50 displays in one View, 50 displays will be loaded into memory, regardless if you are only displaying only one of them. So the answer to your question is yes, typically the more displays in a view you have, the more inefficient the View becomes memory-wise.

With that being said, I personally think that having anywhere between 2-10 displays in a View should prove negligible memory-wise. Having a discreet amount of displays in a View does serve it's practical purposes, after all (otherwise, why would they be there in the first place?).

As to your second question (performance impact of additional filters, etc), yes, adding certain parameters to your View will affect performance. If you want to know by exactly how much, you can go to admin/structure/views/settings (if you are in D7) and select Show information and statistics about the view during live preview, Show the SQL query, and Show performance statistics. Here is a screenshot of the performance screen:

If you are further interested in the behavior of the queries (how many rows are analyzed, which keys are used), you can copy the query from the Views interface (once you've selected "Show SQL query"), and analyze the query using the MySQL explain command. There's plenty of articles like this one for explain usage on Google.


Moved one site to another site files are refering old site I moved whole Drupal setup from ex.(1.1.1.1 to www.example.com). After the move there are some issues. Some Drupal default files are not found error.(ex. close.png ,background.png) because the images references are for the old url:  http://1.1.1.1/modules/overlay/images/background.png.

How can I fix that?

First clear all caches. If that does not resolve the issue check your settings.php file(s) for references to the old address.

If you have images in content you can search the database tables for those fields to look for references (but fix them through Drupal's interface). Unless you have a huge number your better off fixing those one by one. Generally in D7 and before you want site or page relative image references not absolute references.