texts:
I'm trying to get this code working

{% if article_id is defined %}
    {% set entry = craft.entries.id(article_id).first() %}
{% endif %}

The code itself is unimportant, what's relevant is that I'm currently working outside of the context where I would rendering an article. This particular code happens to be broken, and I would like to fix it via inspecting {{ article_id }}. Except I can't, because:

Template Error

A template that extends another one cannot have a body.

---

{% extends "_base" %}

{% if article_id is defined %}
    {% set entry = craft.entries.id(article_id).first() %}
    {{ article_id }}
{% endif %}

Now there's a variety of ways that I could solve this issue, but I'm wondering what's the best option. Ideally it would be something like {{ craft.log(article_id) }} - ie. a function would still produce the Template Error, but at also let me see the value / other information about article_id (either in the error window, or on the javascript console log).

How should I implement the logging behavior that I'm looking for?


texts: How do I use URL parameters to filter a channel by a date field?

texts:
How do I filter entries by URL parameters. The url is /booking?month=november&year=2015.

So far I have:

{% set allEntries = craft.entries.section('availability').order('availabilityStartDate').limit(null) %}

where availabilityStartDate is a date field.

How do I return entries that match November and 2015.

Thanks for any ideas or code!


texts: Is it possible to determine if a script is running within a task?

texts:
I have a chunk of PHP code which should not be run if the script is being executed from a task.

We already have these methods, which are similar to what I'm looking for:

craft()->isConsole() - Whether the script is running in the console.
craft()->request->isCpRequest() - Whether the script is running in the CP.

Is there a way to tell if the script is running inside of a task?

(Since my research has turned up nothing so far, I opened a related feature request...)


texts: Sprout Forms: Map Element ID to Content Field on Save Entry Event

texts:
What is the right way to save the entry id of a sprout form submission to a custom field in that form?

I've been fiddling with the SproutForms_EntriesService, but is that the completely wrong way to go about it?

This post was helpful, but the setContentFromPost threw errors for me. I've had success with getContent though:

$entry->getContent()->title = yourValue;

Still, I'm missing something:

Specifically, I've played with the saveEntry function, and I can save values before the event is validated (where the title is updated at line 156), but since I need the element ID, the value should be set after the entry has been successfully saved. But, if I move my code inside the successful new entry block at line 176, it's a dud:

Starting @176

// Now that we have an element ID, save it on the other stuff
if ($isNewEntry)
{
$entryRecord->id = $entry->id;
  // my crappy code:
  $entryId = $entry->id;
  $entry->getContent()->formEntryId = $entryId;
  // end crappy code
}

I could be going about this totally wrong. You'll have to forgive the ignorance; I'm a Front End Dev with general Craft skills who's delving into plugin dev for the first time. So, I'm at the beginning, studying the Craft Plugin Mijingo Course and just straight up reading through plugin files…

Thanks for your help!

L


texts:
I'm trying to update the context from within a macro. Is this possible at all? I'm pretty close with the below code.

The var_dump within the below function shows the updated context. But when doing a {{ dump(_context|keys) }} after the macro call the context is unchanged.

Any ideas, much appreciated.

<?php
namespace Craft;

class TwiggedTwigExtension extends \Twig_Extension
{
  public function getName()
  {
    return 'Twigged';
  }

  public function getFunctions()
  {
    return array(
      'addVar' => new \Twig_SimpleFunction('addVar', array($this, 'addVar'), array('needs_context' => true)),
    );
  }

  public function addVar($context, $str, $val)
  {
    $context['context'][$str] = $val;
    var_dump(array_keys($context['context']));
  }
}


texts: Urgent question - failed plugin and now getting internal server error

texts:
Hope someone can help asap - we tried to install a plugin through craftcms 3 (Cache Flag) and now getting 'The configuration for the "gc" component must contain a "class" element.'

Does anyone know how to resolve this?


texts: Styling Subsequent Pages in Craft Pagination

texts:
I am building my first Craft blog, and can't figure out how to get the CSS styling to apply to pagination beyond the main blog index page. When I click through subsequent blog pages, the URL adds 'p2', 'p3', etc. as expected, and all of the HTML content and links are there and work fine. But no styling beyond the first page. Any ideas? Here is my pagination code in my main blog index.html:

{# Pagination and home page link #}

    {% if pageInfo.prevUrl %}
        Prev
    {% endif %}

    {% if pageInfo.nextUrl %}
        Next
    {% endif %}

    Home


texts: Sprout forms AJAX submission giving Template not found

texts:
I am able to capture submissions from a regular HTML form, however if I replicate the POST with JSON I get the following "Template not found" error.

Template not found: sprout-forms/entries/save-entry
1. in /var/www/Applications/vendor/craftcms/cms/src/controllers/TemplatesController.php
at line 70 61626364656667686970717273747576777879
  * @param string $template
  * @param array $variables
  * @return Response
  * @throws NotFoundHttpException if the requested template cannot be found
  */
 public function actionRender(string $template, array $variables = []): Response
 {
     // Does that template exist?
     if (!$this->getView()->doesTemplateExist($template)) {
         throw new NotFoundHttpException('Template not found: ' . $template);
     }

     // Merge any additional route params
     $routeParams = Craft::$app->getUrlManager()->getRouteParams();
     unset($routeParams['template'], $routeParams['template']);
     $variables = array_merge($variables, $routeParams);

     return $this->renderTemplate($template, $variables);
 }

2. craft\controllers\TemplatesController::actionRender('sprout-forms/entries/save-entry', [])

....

11. in /var/www/Applications/web/index.php at line 21 – yii\base\Application::run() 15161718192021
                     (new Dotenv\Dotenv(CRAFT_BASE_PATH))->load(); }   // Load and run Craft define('CRAFT_ENVIRONMENT',
getenv('ENVIRONMENT') ?: 'production'); $app = require
CRAFT_VENDOR_PATH.'/craftcms/cms/bootstrap/web.php'; $app->run();

I have disabled CSRF for now in the hope of taking that out of the equation.

I believe I have replicated the HTML form request with a JSON POST using Postman but am hitting a dead-end. Any assistance with debug steps, or a sample Postman config to a working solution would be hugely appreciated.


texts: Covering both "www.domain.com" and "domain.com" in config file settings

texts:
How can I cover both "www.domain.com" and "domain.com" with the same settings in my config file? My current file is set up like this:

return array(
    '*' => array(
       // Settings here
    ),

    // Local
    'domain.dev' => array(
       // Settings here
    ),

    // Staging
    'staging.domain.com' => array(
        // Settings here
    ),

    // Production
    'www.domain.com' => array(
       // Settings here
    )
);

Can I just remove the www from the last entry under “Production” to have those settings apply to both the naked domain and the www subdomain?

And if I'm including the www in my siteUrl config setting in Production, will that create any conflicts if visitors end up at a naked url without the www subdomain specified?

Thanks!


texts: Live preview option not working for multi-site functionality

texts:
I am working on a site which has the multisite concept. Each site has its own base URL. The issue is that, if I have logged in to the admin with the primary site and access the preview option for the secondary site in the system then it is showing the cross-domain error in the console of the browser.

Is there any way to solve the issue?


texts: Neo plugin - Displaying an image from a Matrix field

texts:
I am using the Neo plugin in my project. I have made a Neofield article content with several block types in it. Amongst the block types that I have in it, is a gallery as well. Gallery block type has amatrix field imageWithCaption, and the field imageWithCaption has fields file which is the assets field, and fields imageTitle and caption which are plain text fields. I am able to display imageTitle and caption in my template but not a file, or the image itself. This is my template:
     {% for image in block.imageWithCaption %}

{{ image.title }}

{{ image.caption }}

      {% endfor %}

I get an error:

Object of class Craft\ElementCriteriaModel could not be converted to
string

What I am doing wrong and how can I display the image?


texts:
I have content which needs to go into a certain column so I have a field called 'column' there. I can create the array I want by hand:

{%
    set items = {
        1 : {
            0 : 'Quick Facts',
            1 : 'Agencies'
        },
        2 : {
            0 : 'Inspiration',
            1 : 'Industry Experience'
        }
    }
%}

Where 1 and 2 are the columns, and 0,1 is just a normal index. In a loop it is different. I have tried the same syntax but of course setting the variable in the loop will set the new variable every time and replace the old one. Using merge like below always gives me new keys. Is there a way to do this as easily as PHP?

{% set blocks = {} %}

{% for tab in tabs %}
    {% for key,block in tab.tabItem %}

        {% if block.type == 'about' %}
            {% set blocks = blocks|merge({ (block.column.value) : block.aboutTitle}) %}
        {% endif %}

    {% endfor %}
{% endfor %}

This is the output of the two pieces of code (first being what I want). I'd like the block.column.value to be the key.


texts: Issue with rendering a template from a plugin function

texts:
I have an issue with rendering a template from within my controller in my plugin. It just seems to re-direct to the dashboard instead of bringing up the template.

I have a widget on the dashboard that calls an action in my plugin's controller file. This works as I can print_r the object I am creating. However when it gets to the render code it just keeps re-directing back to the dashboard. I've even tried stripping out all the code apart from the render call and it still does it. The code making the call is:

return craft()->templates->render('pluginName/index.html');

Which is currently the only code in the plugin function. The plugin has a templates folder where the index.html is held. I've also stripped the template down so it only contains the following:

{% extends "_layouts/cp" %}
{% set centered = true %}
{% set title = "The Title"|t %}

{% set content %}

List the users

{% endset %}

Any clues anyone.


texts: Why won't the Import plugin accept this JSON string?

texts:
Importing data.csv using Bob Olde Hampsink's Import plugin. Given that data.csv has a 'table' item string thusly:

"Alcohol and Drug Treatment:RX-8450.3300,Counseling:RP-1400.8000-145,Mental Health Services:RR-5150.1500,Support Groups:PNPH-8100.4500-050"

(two columns, four rows. dead simple)

Lindsay tells us here that:

  a table field contains a simple JSON string

So we are writing a plugin using Import's modifyImportRow hook and here's what we have in the hook loop:

...
// Arrange your content in a way that makes sense for your plugin
foreach ($fields as $handle => $value) {

    if ($handle=="myTableHandle"){

      $rows = explode(',', $value);

      $tabledata = array();

      foreach ($rows as $row) {
        $rowarray = explode(':',$row);

        $rowdata['col1'] = $rowarray[0];
        $rowdata['col2'] = $rowarray[1];

        $tabledata[] = $rowdata;
      }

      $value = json_encode($tabledata);

   }

   $content[$handle] = $value;

}
...

The import works, but the table field data (myTableHandle) remains NULL.

What else can we do to that string of table data to get the Import plugin to accept?


texts: How can I keep the Compiled Templates from caching during development?

texts:
I'm currently developing some templates in Craft. My work flow is

> Make a change to the template file
> Save the file, which automatically loads to the server
> Reload a test page in a web browser

About half the time, and somewhat erratically the adjusted template does not load. Once it is not loading, no amount of browser reloading, clearing local caches etc will help. The only thing that I have been able to find that will consistently fix this is to go in CP Settings and clear the Compiled Template cache. Obviously this is a pain to do each time, and slows my development time considerably.

Initially I tried to set a Craft config of 'cache' => false, because I read this advice somewhere, but I see it doesn't appear in the documentation, and it doesn't work. I've also tried  'cacheDuration' => 'PT1S' to no avail.

The cacheMethod is set to Default. Craft version is current.


texts: How to render an entry type of a Matrix in HTML?

texts:
<a href="{{box.learnMoreLink}}"> {{ box.learnMoreText }} </a>

Currently I have a Matrix field that has two plain-text fields. I want to change the href ({{box.learnMoreLink}}) from plain-text to an entry. I am trying to figure out how to render the entry field. Just changing the field type in the CMS is resulting in content loss. Anyone know the best way to go about this?


texts: Is it possible to cache a faceted search form?

texts:
I have created a search form which allows user to search multiple categories groups and multiple categories within those groups.

So I have

Type

[] Category 1

[x] Category 2

[] Category 3

...

Location

[] Category 1

[x] Category 2

[] Category 3

[] Category 4

I've chosen to use slugs as the search parameter for usability purposes but that means that I have to get the element of each slug and then pass it into the entries query. Long story short,lots of queries to my database before I even get started outputting the categories above.

I'm interested in caching the category queries and I'm doing as follows

{% cache using key "restaurant-filter-type" %}

    {% set typeList = craft.categories.group('restaurantType') %}

    {% for type in typeList %}

            <input type="checkbox" name="type[]" id="{{ type.slug }}" value="{{ type.slug }}">
            {{ type.title }}

   {% endfor %}

{% endcache %}

The problem I run into is when the user submits the form and the checked form elements arent being persistent because of the caching I've set.

I've tried looking at this SE question to help but the stumbling block for this is that there is the possibility that the parameter holding my restaurant type slugs may hold multiple values, hence the name="type[]". A simple replace filter doesn't look likely to work in that situation.

Would anyone have any ideas how I could get around this?


texts: CP Gear Icon missing? Created new Super Admin account

texts:
Having a bit of an issue with user accounts. I created a new user account group (Super Admin) and assigned my user account to this group. Now that I've done that, I can no longer access the main settings area to edit file permissions, fields, sections, etc.

How can I reset my user account so I can access the settings? More importantly, how will I be able to add additional users with the same admin level as my user account?


texts:
Does Craft have built-in queue handling for outbound mail? For example if Settings -> Email -> Protocol is set to "SMTP" and the mail server is temporarily down when an email is to be delivered, the email will then be delivered later when the mail server is online again?

I guess the answer is no, and that it's better to use sendmail if it's important messages?


texts: `onBeforeSaveUser` - Access existing user data

texts:
I'm trying to run a quick check to see if any of my user's data has changed before saving them. However, I'm running into a situation where I can only access the new data.

I can't tell if this is a bug, or simply a misunderstanding of how it works...

craft()->on('users.beforeSaveUser', function(Event $event) {

    // Only do this for existing users
    if(!$event->params['isNewUser'])
    {

        // Get ID of user about to be saved
        $userId = $event->params['user']->id;

        // Look up existing user data
        $existing = craft()->users->getUserById($userId);

        // Why does this contain the NEW data?
        Craft::dd($existing->myField);

    }

});

There may be a reasonable explanation as to why the pre-existing user data is not available. If that is the case, then how can I access the pre-existing data for this user?


texts: How to display entries by descendants of a particular category slug

texts:
I'm trying to display entries (with a category heading) by only the descendants of a particular category slug.

So it would be similar to this:

Display entries by category (multiple categories)

but instead of showing an entire category group it would just be the children of a particular slug.

Thanks!


texts: How to add custom user fields to the front end registration page

texts:
This question is similar to this post, but more of the next logical step.

I have added custom fields to my user profiles, but would like these attributes to be part of the registration page.

For example I'd like the user to specify their address on sign up, but I haven't found a way to reference this field correctly in the page.

Something like:

Address

<input id="Address" type="text" name="Address"
    {%- if account is defined %} value="{{ account.Address}}"{% endif -%}>

{% if account is defined %}
    {{ errorList(account.getErrors('Address')) }}
{% endif %}

This doesn't work because account.Address doesn't seem to be the correct way to access custom user fields on registration, and the only way I currently know how to access this field would be through currentUser.Address, but that relies on the account all ready being created.

Does anyone know how to access these fields to save during registration, or am I going to have to create the account first then have a second page that allows the user to set these fields?


texts:
I'm trying to get the actual file name of each images when looping through the image assets folder, which looks like:

{% for image in craft.assets.kind('image').folderId('1').order('filename') %}

{% endfor %}

I need to be able to include the filename of the image as a data attribute in the  tag. I tried all sorts of variations of {{ image.fileName }} but have had no luck. Can't find a solution searching here. Does anyone know how? Better yet - is there a documentation somewhere showing all the available twig attributes for assets/images?


texts: siteUrl config and Control Panel conflict

texts:
I have set up environments in my config file and included a different siteUrl for each. This is so I can change the navigation on the fly.

I have noticed however that siteUrl when defined in the CP is being used instead of the defined value in the config file. I was under the impression that the CP setting for siteUrl got ignored. What am I doing wrong?

I'm using the same database across both environments - would that be an issue?

return array(
     '*' => array(
         // ...
     ),
     // Local Dev
     'test.dev' => array(
         // ...
         'devMode' => true,
         'environmentVariables' => array(
             'assetsBasePath' => '/Users/joebloggs/Sites/work/example/shop/assets/',
             'assetsUrl' => 'http://test.dev/shop/assets/',
             'siteUrl'  => 'http://test.dev/',
         )
     ),
     // Live Dev
     'test.example.com' => array(
         // ...
         'environmentVariables' => array(
             'assetsUrl' => 'http://test.example.com/shop/assets/',
             'assetsBasePath' => '/home/example/public_html/shop/assets/',
             'siteUrl'  => 'http://test.example.com/',
         )
     ),
);


texts: Site URL displays "Page Not Found The requested URL was not found on this server." but the backend loads fine

texts:
I've recently installed Craft on a Digital Ocean Ubuntu 12.04 droplet. After finally getting all the permissions set and everything set up I get "Page Not Found. The Requested URL was not found on this server." when I visit the site URL but the admin area loads just fine.

Anybody have an idea of what could be going on? Or maybe a way to debug it? I've checked the Apache and PHP error logs (I think) but they don't show anything strange.

I've also tried a brand new install but also had no luck. I'm guessing it's Apache related but I'm not an apache expert.

Any help would be appreciated.

Thanks!


texts:
How would I add more information (custom fields) to a variant's snapshot?

The custom field I'm adding will change over time, but I need it to stay consistent on invoices etc.


texts: The license located at config/license.key belongs to X

texts:
I have an error appearing on my site:

This site is the production version of the site - before hand there was a staging version and a test version.
The test version (hosted on the same server, does not have this error).
So my question is how do I generate a new License? this is a solo version of craft btw not a pro.
I have deleted the license in config/license.key - hoping this would generate a new one and the problem would be over - a new license was generated but the message remains.
Any help would be great -
Thanks - W


texts:
I want to get list of entries in my section video related to my current entry

{% for video in craft.entries.section('videos').limit('3').relatedTo({targetElement: entry.title, field: 'talents'}) %}

problem is entry.title is text, but talents is array.


texts:
I want to utilise the Category field type but with the ability to choose from multiple category sources (as with Entries).

I noted in cms/src/fields/Categories.php that $this->allowMultipleSources is set to false. What is the simplest way of changing this to true without changing the source file?

Can I create a custom field that essentially just extends the original Category field but with $this->allowMultipleSources set to true?


texts: Display freeform entries with a status on open – on the front end

texts:
I'm using this code in my template

{% set formHandle = 'toad' %}
                         {% set submissions = craft.freeform.submissions({
                              form: formHandle,
                            status: ["open"],
                         }) %}

                         {#
Submissions for {{ form.name }}
 #}

                         {% if submissions is empty %}

There are no submissions

                         {% else %}

                                        {% set myfield = (submissions|first).fieldMetadata.status('open) %}

                                        {{ myfield.toadName.label }}
                                        {{ myfield.toadProfile.label }}

                                   {% for submission in submissions %}

                                             {{ submission.toadName.value }}

                                             {{ submission.toadProfile.value }}

                                   {% endfor %}

                         {% endif %}

But get the error:

Error Info: Array
(
    [0] => 42S22
    [1] => 1054
    [2] => Unknown column 'sub_freeform_statuses.handle' in 'where clause'
)
↵
Caused by: PDOException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sub_freeform_statuses.handle' in 'where clause'

Is it possible to show just form entries with an open status only? without
 status: ["open"],
the template works fine


texts: I want my custom field values to be stored on a per-locale basis, but can't seem to do this.

texts:
Currently building a multi-lingual site. Developing locally using WAMP. Using trial version of 'Craft Pro'. Followed the step-by-step instructions of Craft's Setting Up a Localized Site

All works well except for one thing: Step 3: Define your translatable fields.

I can't make this work. When I check/tick my custom field's “This field is translatable” checkboxes, they don't seem to work as expected.

Problem

When I create an entry, put some values in the English locale, then hit save, all values get copied over to the French locale.

This means the moment I hit save, the French version of my site will display English content until I update it with the translation.

Am I doing something wrong?

I'm considering creating locale-specific sections to get around this problem.

Any help, much appreciated.

My current folder structure is as follows:

assets
craft
french
uk


texts:
I get this message while trying to access embedded Asset with the plugin Embedded Assets 1.0.2:

Calling unknown method: craft\web\twig\variables\CraftVariable::embeddedAssets()

I was fiddling around with the code all evening and aint got no idea,
how to get embedded Assets out of my matrix block.

{% case "externeLinks" %}

        {% for asset in block.externalAssets.all() %}

        {% set embeddedAsset = craft.embeddedAssets.get(asset) %}
            {{ embeddedAsset ? embeddedAsset.html }}
        {% endfor %}

{% endswitch %}

If someone could help me, I would really appreciate it. I am new to Craft. If you need any more code, I will provide it.

Thanks in advance.


texts: A-Z filter menu - limiting output to one when there are multiples

texts:
I have a A-Z menu to filter entries by their first letter.

ALL

    {% for entry in craft.entries.section('membershipDirectory').order('title asc') %}

{{ entry.companyName|slice(0, 1) }}

    {% endfor %}

Issue I have is if there are 4 entries beginning with 'C' the output will be:

A B C C C C D E F...

Can I limit each letter once so I'll get 1 'C' is there are 1+ entries starting with 'C'?

UPDATE:

I'm now getting the right number of instances created but no text inside my . Likely a rookie error somewhere:

{% set allEntries =
craft.entries.section('membershipDirectory').order('title asc') %}
{% set allEntriesByFirstCharacter =
 allEntries|group('companyName|slice(0, 1)|lower|replace("/[^a-z]/",
 "0-9")' ) %}

ALL

    {% for allEntries in allEntriesByFirstCharacter %}

{{ entry.companyName|slice(0, 1)|lower|replace("/[^a-z]/", "0-9") }}

  {% endfor %}


texts: How can I have a dynamic/virtual attribute AND have as an attribute of the Model?

texts:
Take the example of a model with a firstName and lastName.

I know I can add a getFullName method to the model, and $model->fullName will run through the getter.

However, I'd like the attribute to also remain part of the model (accessible through $model->attributes), which if I use the getter, it isn't.

If I use the getter AND include the same name in defineAttributes, the getter is ignored.

Is there a way to achieve this?


texts: Hosting Craft on Heroku, problems with Asset uploads and thumbnail generation

texts: Has anyone had success hosting Craft on Heroku? I got it up and running, but can't get file uploads to work. Also image thumbnails don't get generated. I am using Craft PRO and Assets are hosted on Amazon S3. I understand that you can't upload assets to Heroku, I thought using S3 should be sufficient to circumvent that fact.


texts: Linking a page in a multilanguage website

texts:
Currently i am using this approach for linking to a entry(single page) of a structure, for example a cta button on the homepage which links to the contact page.

{% cache %}
    {% set single = craft.entries.id('14').first() %}
    {% if single %}
        {{ "Neem contact op" | translate }}
    {% endif %}
{% endcache %}

Or for example a "read more" button next to some results of some structure without a index. Because thats set in the structure "pages" as a entry type.

But i feel like this is somewhat hacky..
Of course you can link to a page like so:

{{ url('contact') }}"

or

href="{{ "contact"|translate }}

But url() doesn't translate and what if the slug is changed by a user of the CP.
So what is the usual way to get around this, are there any best practises?
So far i can only think of linking all the individual buttons/links to entry fields in the CP, which the user has to fill in.


texts: How many simultaneous visitors Craft CMS can handle?

texts:
I am looking for a CMS as a backbone for front-end work and I like CraftCMS by its interface and structure, so I wonder if CraftCMS is capable for this project. In practice, most of the work will be done on front-end, but next to pageloads, there will be some Ajax requests to the server too and also will users need to log in.

Is Craft CMS (v3) realistically capable of handling around 10.000 logged in visitors simultaneously? I don't know all the details about the project yet, but is there something to say about this so far? Is it critical in CraftCMS? Or should it handle these amounts just fine? As 10.000 simultaneous users on the website looks like a lot to me.

Also, do you guys perhaps know what to look for in hosting specs in order to allow these amounts of simultaneous visitors to all have performant experience (both pageloads and ajax)?

Thanks a lot in advance!


texts:
I'm using Neo to allow my client to be able to create a content grid with child blocks. Now I'm wondering, is there a way that I can change the class of the output based on the number of items?  For example, if there are two items I'd like to have the class grid-one-half and if there are three grid-one-third etc. to give my client more flexibility in making grids.

Thanks!


texts: Can the Lightswitch field have a default 'on' setting?

texts:
I'm creating a new lightswitch field and adding it to an entry type in a section which already has dozens of entries. I want the lightswitch to be default set to 'on'.

When I save the entry type with the lightswitch field added to a tab, then inspect an entry in that section, the new lightswitch field is set to 'off'. Is this a bug?


texts: Creating new assets subfolder throws error

texts:
right click on source > add new subfolder > dialog box asks for subfolder name > submit = "There was an error while creating the folder."

Any ideas here?


texts:
I need to embed some coding into an entry, but I'm unsure how to do it.
I understand that I need to put the code into a Plain text field, so I've created a Plain Text field in Settings, but I now don't know how to bring that field into an Entry- I can't see how to select it. All I can select is a Standalone or Informative text content block.
Thanks


texts: Why would Craft produce a template loader error (TemplateLoaderException) when rendering its default error pages?

texts:
I'm getting a Template Loader Exception when I hit a 404 on my site:

Craft\TemplateLoaderException

Unable to find the template “error”. (/craft/app/etc/templating/twigextensions/TemplateLoader.php:123)

#0 /craft/app/etc/templating/twigextensions/TemplateLoader.php(71): Craft\TemplateLoader->_findTemplate('error')
#1 /craft/app/vendor/twig/twig/lib/Twig/Environment.php(312): Craft\TemplateLoader->getCacheKey('error')
#2 /craft/app/vendor/twig/twig/lib/Twig/Environment.php(378): Twig_Environment->getTemplateClass('error', NULL)
#3 /craft/app/etc/templating/TwigEnvironment.php(23): Twig_Environment->loadTemplate('error', NULL)
#4 /craft/app/vendor/twig/twig/lib/Twig/Environment.php(347): Craft\TwigEnvironment->loadTemplate('error')
#5 /craft/app/services/TemplatesService.php(225): Twig_Environment->render('error', Array)
#6 /craft/app/controllers/BaseController.php(74): Craft\TemplatesService->render('error', Array)
#7 /craft/app/controllers/TemplatesController.php(201): Craft\BaseController->renderTemplate('error', Array)
#8 /craft/app/framework/web/actions/CInlineAction.php(49): Craft\TemplatesController->actionRenderError()
#9 /craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#10 /craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#11 /craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#12 /craft/app/framework/web/CWebApplication.php(282): CController->run('renderError')
#13 /craft/app/framework/base/CErrorHandler.php(368): CWebApplication->runController('templates/rende...')
#14 /craft/app/etc/errors/ErrorHandler.php(281): CErrorHandler->renderError()
#15 /craft/app/framework/base/CErrorHandler.php(351): Craft\ErrorHandler->renderError()
#16 /craft/app/framework/base/CErrorHandler.php(218): CErrorHandler->renderException()
#17 /craft/app/etc/errors/ErrorHandler.php(145): CErrorHandler->handleException(Object(Craft\HttpException))
#18 /craft/app/framework/base/CErrorHandler.php(131): Craft\ErrorHandler->handleException(Object(Craft\HttpException))
#19 /craft/app/framework/base/CApplication.php(740): CErrorHandler->handle(Object(CExceptionEvent))
#20 [internal function]: CApplication->handleException(Object(Craft\HttpException))
#21 {main}

I haven't added a custom 404 error page, or changed the error template paths in my config, so I would expect Craft to serve up its default error page.

What gives?


texts: Craft Commerce Categories and Product Types

texts:
I've just started using craft Commerce. What's the accepted way to categorise products? For example, i’m trying to replicate this structure:

Bags and Scarves (shows all products in this category)

Hand Bags (shows just hand bags)
Overnight Bags (shows just overnight)
Purses (shows just purses)
Scarfs (shows just scarfs)

Hair Accessories (shows all accessories)

Hair Bands (shows just hair bands)
Hair Clips (etc)
Brushes (etc)
Combs (etc)

Hair Care Products (shows all hair care ‘HERO’ products)

Product with variations
Product with variations
Product with variations
Product with variations
etc
etc

Jewellery  (all jewellery, no sub cats)
Gift Vouchers

£10
£20

I can’t see how product types would work?  I added the top level as if they were “departments” but the front end doesn’t show these?

Any help and code examples appreciated to get me going.

Thanks


texts: Is it possible to change admin Actions URL (not only the URI)

texts:
When Craft is in headlessMode my URLS for admin actions (ex. /admin/set-password) are set to the frontend URL (SITE_URL) instead of the Admin URL (SITE_ADMIN_URL).

Is this behavior as expected?

As my Frontend is using angular I would need to add a redirect on the NGINX server to get the links to work which is kind of a strange workaround. Shouldn't the Action urls use the Admin URL by default instead?

Current behavior:

www.example.com/admin/set-password

Expected behavior:

cms.example.com/admin/set-password


texts: Trouble Installing Craft 2.5 on Windows 10 Using Wamp 2.5

texts:
I am trying to install Craft CMS 2.5 on a Windows 10 machine using WAMP 2.5.

I just downloaded both Craft and WAMP this morning — so both are fresh installs.

I believe I have done everything properly, but when I navigate to localhost/sitename/public I get the following message:

  Service Unavailable

  Our site is temporarily unavailable. Please try again later.

If I try navigating to localhost/sitename/public/admin OR localhost/sitename/admin I get the following message:

  Not Found

  The requested URL /sitename/admin was not found on this server.

  Apache/2.4.9 (Win64) PHP/5.5.12 Server at localhost Port 80

These are the steps I took when setting up:

Created a folder in wamp/www called sitename
Copied the craft and public folders into the sitename folder
Changed htaccess to .htaccess (using windows command line)
Created database in phpmyadmin
Updated db.php in craft/config folder

(the only change I had to make was to add the database name — I left server as localhost, user as root and password blank.  I did change the tablePrefix to five different letters — i.e., no numbers or special characters)

I did NOT change the permissions on any of the app, config or storage folders for the simple reason that I do not know how to do that on Windows.

Unless the permissions are the problem, then I do not know why I am having this problem.

Any ideas?


texts: Create Craft 3 Plugin - Call to a member function getVersion() on null

texts:
I'm trying to write my own Craft 3 TWIG filter / functions.

For this purpose I created a scaffolding using pluginfactory.io. I did a composer require and composer correctly symlinks the plugin to the Craft project's vendor directory. When I click "Plugins" in the CP it shows my plugin, but when I click "Install" I get the error:

Call to a member function getVersion() on null

caused in /var/www/html/vendor/craftcms/cms/src/services/Plugins.php on line 328 which is

$info = [
  'handle' => $handle,
  'version' => $plugin->getVersion(), // <== Line 328
  'schemaVersion' => $plugin->schemaVersion,
  'installDate' => Db::prepareDateForDb(new \DateTime()),
];

Why? I compared my composer.json with e.g. nystudio107/craft3-pathtools and it's almost identical and I definitely have a version defined in my composer.json.

Why is $plugin null?

Any suggestions?


texts: How may I restrict uploads to a single folder with variables within a Rich Text Field?

texts:
Craft's Asset Fields allow you to restrict uploads to a single folder—and even pass through a variable to create a dynamic path. How may I restrict uploads to a single folder with variables like this within Craft's Rich Text Field?

I would like to collect images added within the Redactor-powered editor within folders that are unique to each entry within Craft.


texts: Email Field Being Dropped on sendMessage (Craft Contact Form Plugin)

texts:
New to Craft CMS and trying to solve a mystery.  When this contact form sends, the recipients don't get the email field.  We get the others, including the consent, but the email field is missing.  Any help would be appreciated.

Here's the code.  Is there somewhere else it could be missing from?

{% macro errorList(errors) %}
    {% if errors %}
        {% includeJsFile(siteUrl~'js/validate-form.js') %}
        {% includeJsFile(siteUrl~'js/contact-scroll.js') %}

            {% for error in errors %}

{{ error }}

            {% endfor %}

    {% endif %}
{% endmacro %}

{% from _self import errorList %}

<form method="post" action="" accept-charset="UTF-8" id="ask-scigrip">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="contactForm/sendMessage">
    <input type="hidden" name="redirect" value="contact/thanks">
    <input type="hidden" name="toEmail" id="toEmail" value="{{ 'info@scigrip.com'|hash }}">
    <input id="composite" name="composite" type="text">

        Your Data Permissions

        Under the new GDPR Regulations. We require your consent to use the above data we collect from you.
        We use this data to send you various communications for product updates and marketing purposes.
        This information will be sent by periodic emails to your email address.
        To enable us to do this you must check the below consent box.
        The data we hold for you will be inline with our privacy policy which can be viewed here.

If you do not consent then we will only use your information for this enquiry and only hold it for the time it takes to finalise your request.

I Consent<input id="gdprConsent" type="checkbox" name="message[GDPR][]" value="Consent Given" style="width:30px;margin-top:17px;">

    {{ 'POST YOUR QUESTION HERE' | translate }}
    <input id="message" name="message[body]" value="{% if message is defined %}{{ message.message }}{% endif %}" required>
    {{ message is defined and message ? errorList(message.getErrors('message')) }}

    {{ 'WHAT IS YOUR EMAIL?' | translate }}
    <input id="fromEmail" type="email" name="fromEmail" value="{% if message is defined %}{{ message.fromEmail }}{% endif %}" required>
    {{ message is defined and message ? errorList(message.getErrors('fromEmail')) }}

    {{ 'TELL US YOUR NAME' | translate }}
    <input id="firstName" type="text" name="message[FirstName]" value="{% if message is defined %}{{ message.messageFields['FirstName'] }}{% endif %}" class="inp-sml">
    <button type="submit" id="submit" name="submit" value="SEND">ASK SCIGRIP </button>

    {#

    <input type="submit" value="Send">
    <button type="submit" id="submit" name="submit" value="SEND">SEND</button>

#}
</form>


texts: Installing Craft 3 RC on MAMP Pro - Pointing to the file directory

texts:
After a successful install I point the (MAMP PRO 4+) Document Root to the Craft /web folder, which allows the final setup process. (via www/admin) However pointing at the site root (www) triggers this error; HTTP 404 – Not Found – yii\web\NotFoundHttpException

I am missing a final step?


texts: Best approach for building a webshop with more than one URL to the same product (entry)

texts:
What would be the best approach to a webshop in Craft, for solving the possibility of having products on more that on URL. Is there a best practice for one entry being accessible from more than one url? We use canonical for SEO.

Here is a quick summary of the current approach that works, but may be totally overkill :)

Products are stored in a Channel.
A product can be related to several entries in Structures > Product Categories.
The product uri is for example /shop/category/subcategory/product - meaning that one product can have more than one location (url). The SEO issue with this is handled with canonical URLs (further down). The reason we want the product in several locations is that the store is for example selling a certain boot both as a "hiking boot" and a "hunting boot", so the context is different and it won't work as well going to domain.com/products/name without the category (keyword rich) structure in the url. Also having all product entries at the same base url like that (/products/name/) takes the user out of their current context in general (breadcrumb + section specific content/design) if they clicked the product at domain.com/shop/boots/hiking/high/.
3 routes are setup to send /shop/* (1-3 levels adding /* for each) to the ecommerce/_product template.
Entry is not found when entering a product in this way, so if entry is not defined, it is set to be the one matching the last segment of the current URL (matched by slug).
Now we're good to go to show the actual product entry.
The issue of SEO (penalty for duplicate content) is handled with "canonical". I get all entries from Product Categories with a relation to the product (reversed relation), and defining the first one in that loop to be the main location (random - could be set as a relation on product level for the user to decide, but that requires "manual control" and may be hard for the client to relate to), and all other URLs showing the product in a different category that the main location will get  in the header.
In product listings we find the uri to each product again with reversed relations to all categories that has a relation to that product, and we prioritize the product category we are currently in. If the product is listed outside any of its product categories (like on a product page as a related product) it ends up with the base url from the last reversed related product category.

If you think this approach works well or if you have any other ideas.

UPDATE:

I started out with native Categories for product categories. But the client is a brand selling their own product on their site, and each product category is a page with quite a bit more content than just the products, so I have a structure with an entry type for productCategory with several tabs (not possible for a Category).


texts: Use Entries fieldtype functionality in plugin populated by REST api data

texts: Is it possible to use the Entries FieldType widget in my plugin and populate the modal with data from a third party REST API?


texts:
I try to upload a file larger than the 16 MB Craft limit. The file I try to upload is 61 MB.

I have set the maxUploadFileSize to 256000000.
My hosting company changes the server PhP settings to this:

max_file_uploads = 20
upload_max_filesize = 256M
max_input_time = 180
memory_limit = 256M
post_max_size = 256M

The file starts to upload but when the progress bar is at 50%, it just stops. It keeps "uploading" (wheel keeps spinning in the top right corner) but nothing happens anymore.

I don't get a front-end error either. But in my browser console it says: ERR_CONNECTION_RESET

Anyone who can help me find a solution?

UPDATE

So, my hosting company made the time-out longer and the error dissapeared.
But I still can't upload the file as I get this error in the console window now:

POST http://krycer.be/index.php/admin/actions/assets/uploadFile 502 (Proxy Error ( The specified network name is no longer available.  ))

When I diasble my proxy I get this error:

POST http://krycer.be/index.php/admin/actions/assets/uploadFile 500 (( The specified network name is no longer available.  ))

The file upload completes, but the status bar remains visible, allthough full, and the file is not visible in the assets folder.


texts: Stripe Payment Plugin - custom amount/quantity

texts:
With the Stripe Payments plugin for Craft is it possible to allow customers to change the quantity (and thus the price) then pass this onto the Stripe Checkout page? I can see its possible to allow users to enter a custom amount and so could work something in there to change the total price but i wanted to use the inventory feature so wanted to change the quantity also.
I have tried using custom templates but even changing the quantity value in there to something else it just defaults back to 1 when i test in the browser.
Malcolm


texts: Is it possible to override the product URI for Craft Commerce when using Headless Mode?

texts: I've tried using an alias to override the product URI when using Craft Commerce, but it's not working, it doesn't go to the correct URL associated to the FrontEnd.


texts: Create Model relationship with just an ID rather than full Model?

texts:
Is it possible to just assign the ID to the owning side of a relationship rather than querying the DB, loading the record and assigning it?

Something similar to Doctrines _getReference()

http://www.doctrine-project.org/api/orm/2.1/class-Doctrine.ORM.EntityManager.html#_getReference
https://stackoverflow.com/a/9308576/1982031


texts: Craft 3 Redactor Link no longer has target option

texts: The option for opening a link in the Redactor WYSIWYG no longer includes a field for opening it in a new tab? I haven't been able to find any docs that indicate any options for the Redactor config file to add this back in?


texts:
I am using saveUser and i am trying to save a value to a user's custom field.

        $userModel = new UserModel();
        $userModel->mycustomfield = 'test value';
        craft()->users->saveUser($userModel);

This is what i have so far.

I am getting this error:

Internal Server Error
Property "Craft\UserModel.mycustomfield" is not defined.

How do i save to a custom user field?

EDIT

Also tried:

        $user = craft()->userSession->getUser();
        $userModel = new UserModel();
        $userModel->id = $user->id;
        $userModel->getContent()->setAttributes(array(
            'mycustomfield' => 'my field value'
        ));
        craft()->users->saveUser($userModel);

No error, doesnt save either.

EDIT

$userModel->getContent()->mycustomfield = 'my value';

No error, doesnt save.

SOLUTION

    $user = craft()->userSession->getUser();
    $userModel = new UserModel();
    $userModel->id = $user->id;
    $userModel->username = $user->username;
    $userModel->email = $user->email;
    $userModel->password = '';
    $userModel->getContent()->mycustomfield = 'my custom value';
    $success = craft()->users->saveUser($userModel);
    if (!craft()->users->saveUser($userModel))
    {
        $errors = $userModel->getErrors();
    }


texts:
My Entry URL Format looks like this: {section}/{slug} and I am using the standard breadcrumbs code;

   {% if entry.level > 1 %}

        {% for crumb in entry.getAncestors() %}

{{ crumb.getLink() }}

        {% endfor %}

{% endif %}

This will parse:

Home > article > entry-title

how can you add the {section} in as:

Home > section name > article > entry-title


texts: Redirect user to language site of choice

texts:
On this multi-language site (NL, FR, EN) we're using the saml plugin to single sign on users into the craft site. That part is working fine. Every user has a preferred lanuage returned into a user custom field userLanguage.
What I'm trying to do is simply redirect the French language users to https://mysite.com/fr and the English language users to https://mysite.com/en
In my index template I have the following

{% requireLogin %}

{% if currentUser %}
    {% switch currentUser.userLanguage %}

      {% case "NL" %}
        {% redirect 'https://mysite.com'  %}
      {% case "FR" %}
        {% redirect 'https://mysite.com/fr'  %}
      {% case "EN" %}
        {% redirect 'https://mysite.com/en'  %}
      {% default %}
         {% redirect 'https://mysite.com'  %}

    {% endswitch %}
{% endif %}
{# rest of homepage template here #}

On visiting https://mysite.com/ I'm redirected to the sso page and after login back to https://mysite.com/ and there I get a "too many redirects" error, in firefox it's "The page isn’t redirecting properly Firefox has detected that the server is redirecting the request for this address in a way that will never complete."
What am I missing here?


texts:
Is there a way to place matrix fields inside of matrix fields or also to setup a matrix field with existing fields?

We are currently trying not to have duplicate content in terms of fields, but that doesnt seem possible?


texts: How do I output a matrix block type only once when looping through entries?

texts:
My matrix field has a block type called photo. When looping through entries I only want to output the first instance of this block type (although it will have been used multiple times), i.e. the first photo.

The code below loops through the entries, but for each entry it's outputting every photo for the entry - not just the first.

What do I need to change to get just the first photo of each entry output.

{% for entry in craft.entries.section('mySection') %}

    {% for block in entry.tactics %}

        {% if block.type == "photo" %}

                {% set photo = block.photo.first() %}

                {{ entry.title }}

        {% endif %}

    {% endfor %}

{% endfor %}


texts: Display entries related to Category Field

texts:
I'm sorry If this has been answered before, but I couldn't find any answer that would work for me. Maybe I'm just treating category fields the wrong way and I should be trying to do this with tags.

Basically, I created a category group called colors. I also have several categories like green, blue, red...
I assigned URLs that look like mysite/colors/red, mysite/colors/blue.

All of the colors point to the same template colors/index.html

How can I display only the entries in craft.entries.section('news') that are in the "red" color category when I visit mysite/colors/red?

Thanks in advance.


texts: Commerce: How can I check if I am on a specific product page?

texts:
I know there are ways to check current section. I would like to check if I am on a specific product (commerce) page.

I am able to do this in a plugin by checking line item(s) and the product type. Is there a similar way to do the same at the twig level?


texts: How to show entires from past 12 months?

texts: I need to display entries from the past 12 months. I'd like to create an entry query and set the timeframe of the entries I need.


texts: Image transform is turning my jpegs dark

texts:
I'm experiencing a strange effect where an image transform is causing my images to turn very dark when compared to their originals. I have ImageMagick and gd installed. The images are all sRGB. Some have Adobe RGB profiles, some have no profiles.

The image transform makes the jpeg 1200px wide, height auto, quality high. Not sure what could be causing the problem.


texts: Getting a new cart after adding the product in decoupled frontend

texts:
I'm using the headless Craft together with decoupled frontend on Nuxt.js.
I have to implement Craft Commerce 3 cart logic on the frontend, for that purpose I'm using graphQl/axios requests.
However each time I call http://example.com?action=commerce/cart/update-cart&note=from+ajax with cart payload it returns me a new cart with added product (doesn't update the current cart, but returns a new cart each time).
Is there something I'm missing in my payload/headers to keep the same cart?


texts: Add matrix block content to newly created Entry

texts:
Help. I feel this is almost basic and many have asked similar questions, but I cannot get this to work.
I have an entry type which amongst other things has a Matrix field ph_selectorViews, which has one configured block type in it: phaseView. The block is composed of two fields; an Asset field called viewImage and a Supertable field (not relevant).
After a new entry is created in the CP, I need to create a matrix block (phaseView) in the matrix field (ph_selectorView) and attach an asset to the asset field (viewImage). The asset IDs are valid.
Event handler:
Event::on(
  Entry::class,
  Entry::EVENT_AFTER_SAVE,
  new EntryCreated
);
.
.
.
$entry = $event->sender;
if ($event->isNew && ! ElementHelper::isDraftOrRevision($entry)) {
    // does its thing with $entry, assembles an array of custom field data.
}

Add the field data to the entry:
$entry->setFieldValues($data);
$success = Craft::$app->elements->saveElement($entry);

dump($data):
array:2 [▼
  "ph_aerialViews" => array:1 [▼
    0 => 1322
  ]
  "ph_selectorViews" => array:1 [▼
    "new1" => array:2 [▼
      "type" => "phaseView"
      "fields" => array:1 [▼
        "viewImage" => array:1 [▼
          0 => 1323
        ]
      ]
    ]
  ]
]

$data contains another, Asset field ph_aerialViews which saves just fine.
As far as I can tell, that array that I'm passing to setFieldValues() is correct but the MatrixBlock just isn't being created or added to the Entry. This process works fine with a single Asset field on the entry (ph_aerialViews) - I can add assets to that programmatically without issue. saveElement returns true, no errors are returned, no exceptions, nothing in the logs.


texts: Is it possible to include a Users Fields Type on a front end form? I'd like to allow people to choose existing users on a front end form rather than giving them access to the admin area of the Craft site.


texts: Include a template that sets variables (global template variables)

texts:
I'm essentially looking for a way to have a template that runs through a bunch of sets that I might use throughout my templates.

The problem is, if I include in a template with an extends, it dies up with:

  A template that extends another one cannot have a body.

{% include '/_resources/variables.twig' %}
{% extends '/_layouts/default.twig' %}

Some research indicates that maybe this isn't easily done with Twig parsing alone:
https://stackoverflow.com/questions/20410194/use-twig-custom-set-variables-from-an-include
https://groups.google.com/forum/#!topic/twig-users/QKdpWAxLdjE

So, what would be the best way to achieve this? My initial thought would be a plugin that you gave the path of a template, which preloaded things into variables.

I realize some variables (strings) could be done via macros. But, for example, I have a set usStates = {...} that is a big hash of state codes and names.


texts: How do I install Craft in shared hosting that doesn't allow index.php in a sub-folder

texts:
I’ve got a small, low traffic site that I’ve rewritten with Craft and a Bootstrap responsive grid, mainly as a learning exercise. The original site has just a dozen static pages, and is hosted with Fasthosts UK-based shared hosting. My new site, although small, makes extensive use of Craft’s Matrix. I’ve learned a lot and I’m really pleased with it.

I’ve started to install the new site (alongside the old one) and I’ve discovered that Fasthosts shared hosting doesn’t allow the new index.php file to be located inside a ‘public’ sub-folder – it has to be at the root of the htdocs folder. So my first option seems to be to empty the contents of my ‘public’ folder into my htdocs folder, to live alongside the craft folder.

There are stern, but mysterious, warnings about doing this in Craft’s installation documentation: "We recommend that you upload the folder above your web root if possible, which will ensure that no one can access any of its files directly. (Your web root is the folder that your domain name points to.) That’s not a requirement, but do it if you can. For the children.”

Could someone please explain what bad things might happen if I take this first option?

I did a bit of research before I posted this question, and I came across a second option to leave everything in the public folder and to use mod_rewrite code in the .htaccess file to re-route requests for index.php into the public folder.

Lastly, I found a third option of creating an extra index.php file located in the htdocs folder to point to index.php the public folder, with this re-direction code:

<?php
header('Location: http://mydomain.com/public');
exit;
?>

Which of these three options is the best compromise from a security / SEO / performance perspective?


texts:
Can't figure out how to create a dynamic route for the categories in this format:

site.com/news/category-1-and-category-2-and-category-3

That would bring the results from these slug categories.

Trying to build a complex query and I'm sure there is bound to be a better way of doing it that.

'news/<categories:.*>/<categorySlugs:{slug}(\-and\-{slug})+>' => ['template' => 'news/index']


texts: How to create a new site (locale: de-AT) based on another site (de) within same installation?

texts:
I manage a website with multiple languages. Each language has its own site and domain. Think: website.de and website.co.uk

I have to add another site with different locale (de-AT) to the Craft CMS installation. It should run on website.at

The Austrian site should be initialized exactly the same as the current German (de) site.
Afterwards some content will be edited but the foundation but the base should be the same (around 1000 entries).

What would be the best way to 'clone' the German website within the installation to the Austrian website?

It would be okay to manually configure all Sections but I don't want to add every entry manually.


texts: Trouble getting a list of categories that have entries for a specific category group

texts:
I have a long list of categories in a specific category group, but only want to show a list of the categories from this group that currently have an entry associated with them.

I've been trying to implement the solution that I found at this thread: How can I output a list of categories that are not empty?

Only categories with related entries are showing. However, it's not being narrowed down to specific to a specific category group. Here's my code below:

{% set handshapeCategories = craft.categories.group('handshape').limit(null) %}
{% set entriesWithHandshapeCategories = craft.entries.relatedTo( handshapeCategories ).limit(null) %}
{% set handshapeCategoriesInUse = craft.categories.relatedTo(entriesWithHandshapeCategories) %}

{% for handshapeCategory in handshapeCategoriesInUse %}
    <h3>{{ handshapeCategory }}</h3>
{% endfor %}

Any ideas why the shown categories are not being limited to categories from the 'handshape' category group?


texts: How can I pass variables to email's template onBeforeSendEmail

texts:
I'm trying to add some variables to email's template to be rendered before email is sent.

I was able to modify emailModel like customHeaders and subject but I couldn't pass custom variables to the template.

How can I pass variables to email's template using onBeforeSendEmail event?


texts:
Any idea why the following would be ignored following a frontend new password form? The user group does not have access to the control panel.

'setPasswordPath' => 'account/login/password/new',

The following success path on the next line works fine:

'setPasswordSuccessPath' => 'account/login/password/done',

The user workflow:

Start on frontend Register form with firstname, lastname, email and password.
Account created and user is logged-in. No email confirmation needed.
User logs out.
User completes Forgotten Password form and email is sent.
User clicks password link in email and sees the Craft CMS password form.

I've tried this with and without the email address having a pre-existing Craft Commerce order associated with it. The result is the same.


texts: Does anyone know or have a solution for a live search filter on the frontend for Craft.  I can muscle through putting something together but if you have used something that is friendly enough, would like to see the solution for Craft.


texts: Show custom field on Submissions page in CP

texts:
In A&M Forms, I'd like to show a custom field on the Submissions page in the control panel to make it easier to quickly reference the submissions.

Is this possible?

Thanks]1


texts: After migrating, I am getting this error for several of my buttons and menus on Craft 2.6

texts:
Internal Server Error
Craft\MatrixBlockModel and its behaviors do not have a method or closure named "header".

Apache Version  2.4.37
PHP Version 7.1.24
MySQL Version   5.7.24
Architecture    x86_64
Operating System    Linux Cent OS


texts: Importing assets with Feed Me using Element Exporter data

texts:
When I export data using Craft's built-in Element Exporter, asset fields are exported with an element ID. This is the same as Category and Entry fields, for example.

However, when mapping fields in Feed Me, asset fields do not allow you to select ID as the provided data, like a Category or Entry field would. When you run import, these fields seem to be skipped as the provided data is not what Feed Me is looking for.

Perhaps I'm missing something here, but Element Exporter and Feed Me don't seem compatible when it comes to asset fields at the moment. Has anyone else had any luck using these two programs together with regards to assets?


texts:
I am building a site where I have users, companies and content.

Currently my users are standard Craft users, and my companies and content are entries within a channel.

I have a field in my content called company name which is an asset field and lets me create a relationship between a piece of content and a company and now I want to create a comaopny page that lists all content "owned" by that company.

I have the below as a starting point which is listing all of my content but any help on what I'd need to do to tweak it so that it only displays content where company name is equal to the entry title (which is the company name)? Hopefully that makes some kind of sense!

Many thanks in advance!

{% set relatedEntries = craft.entries()
    .companyName(':notempty:')
    .all() %}

{% if relatedEntries|length %}

        {% for rel in relatedEntries %}

{{ rel.title }}

        {% endfor %}

{% endif %}


texts:
Craft updates come fast and frequent which introduces a problem when working with lots of people in a team.
Don't get me wrong, this is a good problem to have!

How are dev shops handling the update process when sites have multiple developers on them with multi feature branches running all at once?

The main issue is the strong dependency each feature branch has with the database. Once you implement a craft update, craft doesn't like jumping around on older versions as you switch feature branches.

What we're currently doing:

Disabling the ability for people to be able to update on the live production server.
Creating an "Upgrade" branch on git and doing the updates in that before merging them into the develop branch.

We still seem to be occasionally getting the odd issue of an old feature branch that is out of sync with the database/new install because of this we are still looking to improve this workflow.

Ideas we are tossing up:

Making a private repo of the /app directory a submodule so the sites repo is rather clean.
Disabling the ability to upgrade by default on all domains and treat updates as a "big thing" similar to how you would on an Expression Engine upgrade.

Would love to hear how others are tackling this "convenient" problem.


texts: How do I create a Human readable sitemap in Craft CMS

texts:
I'm just getting started with Craft (and digging it).

I've seen lots of xml sitemap plugins available already.  How do I create a human readable sitemap that will be browsable from the front end and that I can link to in the footer.

Thanks for your help in advance!


texts: Sprout Forms - Custom Form Notification Recipients With sproutForms.onBeforeSaveEntry

texts:
I've got an existing service based site that uses Sprout Forms to request quotes. The quote form lives on all services pages in a sidebar (and the submissions have an entries field keeping track of which service the submission came from).

I've just added some fields into the services entry to allow them to override where the quote form goes.

Now I need to make this work. I have a plugin listening for sproutForms.onBeforeSaveEntry events, and when it receives them I'm wanting it to adjust where it sends the notification to.

Is this possible? Is it possible to modify notificationRecipients on an individual event or is this against the form (and in either case how do I do this if I have a SproutForms_OnBeforeSaveEntryEvent)?

In either case (as I can live with the former) a code example would be amazing.


texts: onBeforeSendEmail event triggered from Commerce_EmailsService

texts:
I'm trying to access the order and orderHistory model via onBeforeSendEmail event. I can see that in Commerce_EmailsService.php file on line 311 the event is created with those params and passed to onBeforeSendEmail, but when I try to access them from my plugin, they are not there. I thought they would be available in the variables param, but they are not (or I'm doing something wrong here).

Does anyone know if/how I can access those models from onBeforeSendEmail event?


texts: How do I delete or remove temporary assets?

texts:
Images were uploaded to a matrix field and then the changes were not saved, but the assets still show up in the control panel as selectable.

The asset seems to be stored here:

http://example.com/admin/resources/tempassets/field_51/file_name.jpg

I'd like to delete or remove these so that we dont't have them laying around taking up the desired file name. If I upload the same image again it appends a _x to the end of the file name as the number of times it's been uploaded.

I can't find the assets anywhere in the assets page in the control panel.


texts:
I have an old craft 2 installation.
When I want to go to the frontend I get:

mkdir(): Permission denied

745     {
746         if ($permissions == null)
747         {
748             $permissions = craft()->config->get('defaultFolderPermissions');
749         }
750
751         $path = static::normalizePathSeparators($path);
752
753         if (!static::folderExists($path, false, $suppressErrors))
754         {
755             $oldumask = $suppressErrors ? @umask(0) : umask(0);
756
757             if ($suppressErrors ? !@mkdir($path, $permissions, true) : !mkdir($path, $permissions, true))
758             {
759                 Craft::log('Tried to create a folder at '.$path.', but could not.', LogLevel::Error);
760                 return false;
761             }
762
763             // Because setting permission with mkdir is a crapshoot.
764             $suppressErrors ? @chmod($path, $permissions) : chmod($path, $permissions);
765             $suppressErrors ? @umask($oldumask) : umask($oldumask);
766             return new Folder($path);
767         }
768
769         Craft::log('Tried to create a folder at '.$path.', but the folder already exists.', LogLevel::Warning);

Where can I read out the folder which has no permission?
I've set recursive chmod 777 on all files in the project (yes I know).
But this doesn't change anything.
It is on a local MAMP Pro install. Nothing is showing in any logs.
But the Control Panel is working fine.
I also tried to change the user in mamp. As suggested on discord. But that does nothing.
♂


texts: If user has no access to email how to give them a temp password?

texts: In Craft 2.3 admins aren't able to edit users passwords. So I'm wondering if they have no access to email how can we give them a temporary password?


texts: Config option to disable update capability per environment

texts:
In our workflow, we run a shared development server. Each developer develops locally but points to the development database. All Craft software updates need to happen while in the local environment and then changes need to immediately be committed to the git repo otherwise things could get really screwed up.

I would the option to disable the update capability using a multi-environment config setting so we could prevent anyone from running those updates on the shared development server.

I know we could set up user permissions to lock this down, but I think it would be much handier to be able to do that at the config level.

Thoughts?


texts: Is there a JS event triggered when a new widget is created?

texts:
Pretty straightforward problem...

On the dashboard, I click "New Widget".
I select "My Custom Widget" type.
A new instance of "My Custom Widget" appears on the dashboard, ready to be edited.

How can my widget be self-aware that it has just been created?

I need the widget to perform some very minor JS when it initially loads. Is there an existing JS event which would be triggered in this scenario?


texts: Nginx config for craft working for everything but admin url's

texts:
I am trying to configure NGINX to serve a craft 2 site.  I am getting the requests being routed through index.php for template url's but not for any admin routes which are redirecting to index.php?p=/admin/**/*.

I am assuming this has more to do with my NGINX config than craft as I have the following option enabled:

'omitScriptNameInUrls' => 'true',

Is there any craft related reason that admin URL's would redirect that way whereas template url's wouldn't?

here is my nginx config:

server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;

index index.html index.htm index.php;

server_name _;

error_log  off;
access_log off;

root /code/public;

charset utf-8;

location / {
    try_files $uri/index.html $uri $uri/ /index.php?$query_string;
}

location ~ [^/]\.php(/|$) {
    try_files $uri $uri/ /index.php?$query_string;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass php:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    include fastcgi_params;
}

# Disable reading of Apache .htaccess files
location ~ /\.ht {
    deny all;
}

# Misc settings
sendfile off;
client_max_body_size 100m;

# 404 error handler
error_page 404 /index.php?$query_string;
}

Update:

just deployed this same app to AWS elastic beanstalk and am running into the same issue with Apache.  This leads me to think maybe it's not related to nginx?


texts: How do you format a date for saving with users/saveUser on the front end?

texts:
Currently using a date picker to select a date and submit it on user registration, formatted as m/d/Y, have played with various formats but can't one that works.

Any ideas?


texts: How could I make related entries load faster?

texts:
I need to show a list of users (around 400). No problem, the list loads in 1.5s, for which I could use {% cache %} to speed it up.
Now, the problem arises whenever I want to display the title of an entry related to the user. The log shows 400 extra queries, so a query per user, if I do this:

{% for user in user %}
    {{ user.relationFieldName.first() }}
{% endfor %}

This seems a bit faster, but not fast:

{% for user in user %}
    {{ user.relationFieldName.find()[0] }}
{% endfor %}

Is there a way to get this information directly when querying for users? Or is there another way to speed this up?

Would eager loading these relations through a plugin help? And if so, what service/model/record would I have to extend to go about this?


texts:
I'm trying to do something akin to Andrew's excellent article whereby I have a 'more' button that spits out 6 more entries at a time. I'm nearly there, but running into some issues. I don't get past the spinner, and looks like I have some syntax issues lines 17 and/or 24 (because it works if I comment those out). Pretty new to Element API and working this way, and can't Google up anything that makes sense to me as a fix. Anyone help me out?

Here's my element-api.php:

<?php

use craft\elements\Entry;
use craft\helpers\UrlHelper;

return [
    'endpoints' => [
        'api/news.json' => function() {
            return [
                'elementType' => Entry::class,
                'criteria' => ['section' => 'news'],
                'elementsPerPage' => 6,
                'transformer' => function(Entry $entry) {
                    // Generate new image transforms right away
                    craft()->config->set('generateTransformsBeforePageLoad', true);
                    // Get card image
                    $srcImage = $entry->cardImage->one();

                    if ($srcImage) {
                        $imageUrl = $srcImage->getUrl();
                        // Check if Imager plugin installed
                        if (craft()->plugins->getPlugin('Imager')) {
                            $image = craft()->imager->transformImage($srcImage, [
                                'width' => 800,
                                'format' => 'jpg',
                                'ratio' => 3/2,
                                'allowUpscale' => false,
                                'mode' => 'crop',
                                'jpegQuality' => 60,
                                'position' => $srcImage->focusPctX() . '% ' . $srcImage->focusPctY() . '%',
                                'interlace' => true
                            ], null, null);
                            $imageUrl = $image->url;
                        } else {
                            $imageUrl = $srcImage->getUrl(['width' => 800, 'height' => 533]);
                        }
                    } else {
                        $imageUrl = null;
                    }

                    return [
                        'title' => $entry->title,
                        'url' => $entry->url,
                        'jsonUrl' => UrlHelper::url("news/{$entry->slug}.json"),
                        'postDate' => $entry->postDate->format(\DateTime::ATOM),
                        'author' => ['name' => $entry->author->name],
                        'cardImageUrl' => $imageUrl,
                        'summary' => $entry->summary,
                    ];
                },
                'meta' => [
                    'description' => 'Latest news',
                ],
                'pretty' => true,
            ];
        },
    ]
];


texts: How to process CSV files within a Matrix field?

texts:
I'm trying to import and process CSV data within a matrix field.
My situation is the following:

I have a matrix field with one block and several fields inside. One of these is an asset field to upload a CSV file. Now I don't just need to upload this file to a specific destination but also directly want process the given data inside of my CSV file to write it into the database and also display the data in the backend after saving the entry. Furthermore I need to be able to edit the output of the CSV in the backend. The best case would be a table.
I specifically don't want to have a standalone plugin which provides the given data to a matching entry. That would kinda ruin the workflow for editors.
I would really love to have the upload inside of the suitable entry.

Maybe I'm just overlooking one simple solution but I don't see how I should do it.

I hope I explained it good enough and am looking forward to some solutions.

Thanks in advance and best regards,

JohN


texts: Is there a way to create a "sticky" asset

texts:
I have a list of images that are loaded directly from the content of a specific asset folder.

{% for image in craft.assets.find({ folderId: 18, limit: 240, order: filename }) %}

What I want to achieve is that one (or more) images from that assets folder are listed first (second etc.) before the actual ordering by filename starts place.
Much in the same way as sticky entries (EE).


texts: Craft newbie : can anyone recommend a simple image slider?

texts:
I have just started working with Craft and I'm learning as I go, by porting over an existing site to it. It's mostly going well.

However, I stumbled when I tried integrating an imageslider on the Homepage. It's a slider called Flexslider, and I've been unsuccessful in integrating it as a series of entries for each slide. When the browser tries to render the page it stops at the "data-bg" tag...

Here is my code :

{{ entry.slideTitle }}

{{ entry.slideSubtitle }}

        ...

I'm open to replacing Flexslider with a more Craft-friendly slider, if anyone can point me in the right direction?

Many thanks!
Ric


texts: How to fire flash messages when using Event::on()?

texts:
I'm looking to hook into an Asset::EVENT_BEFORE_HANDLE_FILE event and toss up a JS flash error if it's above a certain file size. However, the registerJs() function never runs and I assume it's because this is some sort of anti-pattern. What is the more proper way to achieve this sort of thing?

Event::on(
    Asset::class,
    Asset::EVENT_BEFORE_HANDLE_FILE,
    function (Event $event) {
        $asset = $event->asset;

        if (filesize($asset->tempFilePath) > 100000) {
            Craft::$app->getView()->registerJs('Craft.cp.displayError("Example error message")');
        }
    }
);


texts:
Anyone have experience updating a CraftCMS site from 2.* to the 3-beta? I'm not in dire need of this at the moment, but can't seem to find it in the developer resources.

EDIT: Found the upgrade guide https://docs.craftcms.com/v3/upgrade.html


texts: Prevent ALL templates from being rendered directly?

texts:
I attempted to set the privateTemplateTrigger to an empty string in my config/general.php file, because I don't ever want Craft to serve up a template file on its own just because a visitor happens to put in a URL that matches its name, and I was hoping to avoid prefixing every single file in my /templates directory with an underscore. Unfortunately doing so breaks several CP pages (like Globals and Plugins)...

I'm guessing it's because some CP files are relying on this feature? Surely there must be some way to disable this "direct rendering of template files" thing that doesn't break the CP?


texts:
OK, setting up a production server (not live yet) and I am encountering a strange issue that I have not seen previously.

Issue:
Installed Craft on an Ubuntu 16.10 LAMP server. When all commands for installing were completed, I tested my site with its IP address to make sure everything worked and I got the following:

Then when I got to 192.168.5.254/public/index.php/admin/install -- which has worked on the two test servers I have built previously -- I get this:

An to make sure that I have tried another method of gaining access to the installer, I went here 192.168.5.254/admin which redirected to 192.168.5.254/admin/login, I get this:

Clearly Craft is working as these are not Apache 404's; however I never got the install screen at all. Just the homepage and login screen. Did I miss or mess something up during this specific install?

As usual, if you need additional information, let me know I will post it in here for visual use. Thank you very much for your assistance!


texts: Custom fieldtype to add text field to dropdown, radiobuttons and checkboxes

texts:
In my plugin I need to create a fieldtype of a dropdown, radiobutton or checkbox combined with a textfield.

I've gone ahead and created a custom field type using the description here https://craftcms.com/docs/plugins/field-types#modifying-your-fieldtypes-stored-data-for-use

Now I'm trying to save the field to the database using the saveField function, but it gives me the following error:

Fatal error: Call to a member function prepSettings() on null in dev/craft/app/services/FieldsService.php on line 503

It seems to fail because $field->getFieldType() returns null, which is weird because $field->type returns the name of my custom fieldtype.

I went deep into Craft code and ended in getComponentByTypeAndClass, where $pluginHandle is the name of my custom field type, instead of the name of my plugin.

Could that be the issue? If not, what could?

Thanks a lot


texts: control panel login redirects back to login

texts:
First, I just took over administration of our Craft site from a previous employee, and the original site was set up by a contractor, so I'm still trying to figure things out.

Yesterday it was reported that people can't log into the control panel anymore.  The login page loads, you enter your creds, and it just brings you right back to the login page, no errors.  We've tried entering an invalid password, and then we do get an error message, so it's checking something.

Any assistance would be greatly appreciated.  I feel like I have inherited a mess where the Craft site is running in Azure as a web instance along with the MySQL, but some assets are coming from AWS.

Thank you in advance.


texts: HappyLager Demo Site Forcing 'https://' on XAMPP

texts:
When I try to load the demo site in my browser I get the following error:

https://imgur.com/8jVvweN "Your connection is not secure"

I have added the following to my hosts file:

127.0.0.7        happylager.dev

and this to my httpd-vhosts.conf file:

<VirtualHost *:80>
    DocumentRoot C:/xampp/htdocs/HappyLager/public/
    ServerName happylager.dev
    ServerAlias http://happylager.dev
</VirtualHost>

Content of .htaccess files:

The .htaccess file in the public folder contains:

<IfModule mod_rewrite.c>
    # Send would-be 404 requests to Craft
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
    RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>

The .htaccess file in the craft folder contains:

deny from all

XAMPP versioning information:

PHP Version 7.04
phpMyAdmin version 4.5.1

This error occured during step 7 and 8 on this page:

https://github.com/pixelandtonic/HappyLager

Rebooted as well just in case. When I try to resolve 'happylager.dev' or 'http://happylager.dev' the error still persists. The virtual hosts resolve other names without error. Any idea what I might not be considering? Any help will be greatly appreciated.


texts:
I recently started a new Craft 3 project and am having some trouble with Feed Me. I haven't had this problem in the past with Craft 2.

The Feed URL I'm using is giving me this error:

Unable to reach assets/data/clients.xml. Message: cURL error 6: Could not resolve host: assets (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

When I try to use the siteUrl it seems like that isn't resolving either:

Unable to reach {siteUrl}assets/data/clients.xml. Message: cURL error 6: Could not resolve host: %7BsiteUrl%7Dassets (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

The file exists at that location and is accessible through the browser.

Any thoughts?


texts: Is it possible to define a 'richtext' fieldtype as 'MEDIUMTEXT' in DB?

texts:
Some articles are very long and getting cut off when saved to the database.

Is it possible to define a 'richtext' fieldtype as 'MEDIUMTEXT', or would I have to write a plugin to replicate the 'richtext' fieldtype with a different field attribute defined in defineContentAttribute? Any other considerations to take into account? Such as search, indexing, redactor or otherwise?

Part 2 of this question would be: what is the simplest way to duplicate the RichTextField in a plugin? Can I just extend 'RichTextFieldType' and redefine getName and defineContentAttribute? I tried the following with no luck.

Update: This creates a 'Rich Text (Medium)' field with the correct DB column type of 'MEDIUMTEXT', but causes the 'Edit Entry' screen in the CP to be blank below the entry title (silent fail?); and if switching to entry type with this field getting a garnish error 'Double-instantiating a transparent text input on an element'.

class LongTextFields_MediumRichTextFieldType extends RichTextFieldType
{
    public function getName()
    {
        return Craft::t('Rich Text (Medium)');
    }
    public function defineContentAttribute()
    {
        return array(AttributeType::String, 'column' => ColumnType::MediumText);
    }
}

Another option might be to just redefine the columntype manually in the database. Is there any chance this value will ever get overwritten? (i.e. upgrades, migrations, etc).


texts: I'm repeatedly setting the same variables. How to reuse code block to make this DRY?

texts:
I have a very complex layout which is requiring me to have quite a few {% for %} loops on the page and in each loop I need to set a bunch of variables. In order to make my template more DRY I was hoping I could save that block of code where I set the variables as a partial so I could simply include that partial in each loop rather than writing out each variable that needs to be set every time.

But that doesn't work. Variables in the parent templates are available to imported partials, but variables in partials aren't available to the rest of the parent.

What other templating options does Craft/Twig supply that would allow me to make this DRY?

Example of the variables I'm repeatedly setting on multiple loops in the page:

{% if article.newsHero | length %}
  {% set photo = article.newsHero.first().url('w600') %}
  {% set w = article.newsHero.first().width() %}
  {% set h = article.newsHero.first().height() %}
{% endif %}
{% set cat = article.newsCategory.first().title %}
{% set summary = article.newsArticle.type('text').first().text|hacksaw(words='35', append='...') %}
{% set count = loop.index %}


texts: Why does Craft set no-cache headers for all requests?

texts:
Craft seems to be setting headers to tell the browser not to cache anything it serves, which seems bad.

Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0

Why it do dat?


texts: Treat links in redactor/rich text field differently depending on entry type

texts:
I'm looking for a way to handle links to entries in a Redactor (Rich text) field such that a different class gets added to the  tag depending on the type of the entry.

For example, a link to an "event" entry type would be modified to look like: Event name.

I assume that some kind of plugin would be needed for this, but I have been able to find anything similar I could learn from. So any pointers to this end would be really helpful!

Many thanks.


texts: Twig template outputting blank page on non-"dev" environment

texts:
I've created a base twig template which contains some basic "maintenance mode" logic. This works perfectly as long as the main ENVIRONMENT in the .env file is set as dev, but fails for staging or production.
{% if site.maintenanceMode is defined and site.maintenanceMode %}
    {% if site.maintenanceIpAddress is defined %}
        {% set currentIpAddress = craft.app.request.userIP %}
        {% if currentIpAddress != site.maintenanceIpAddress %}
            {% include('/maintenance') %}
            {% exit %}
        {% endif %}
    {% else %}
        {% include('/maintenance') %}
        {% exit %}
    {% endif %}
{% endif %}
<!DOCTYPE html>
<html lang="en"…

Being fairly new to CraftCMS, I'm somewhat at a loss as to why this might be occurring and there's nothing in either the …/storage/logs/web.log file or the main nginx error log file. (In short no errors appear to be being thrown.)
I've tried flushing all of the available caches (including the template cache, etc.) and rebuilding the config, etc. to no avail.


texts: How can I add custom field to order by on the admin CP in Craft 3?

texts:
I would like to add a custom field for order by on the drop down menu on admin CP. How can I do it, is there any event for this in Craft 3?

It is a plugin related question, we are using custom plugin to customize our application


texts:
How much data can I push into one craft()->cache key?

Let's say I have a json string that's reaaaallly long.


texts: How to add Image or any field on Calendars section for Solspace Calendar?


texts: How can I set up sources based on my custom field data?

texts:
Now that I have my custom field displaying in the Entries Table, how can I set up sources to view entries containing specific data from my custom field? My custom field holds several different values, but I want to have a filter set up to view specific things.

Note: this is being copied from the Craft Slack channel so we don't lose it


texts:
I'm working on one Craft project with two sites (which have one shared page that is translated and possibly more in the future.) Is there a way to make the global header & footer for Site 2 redirect back to Site 1 pages instead of having to enable all of the Site 1 pages for Site 2 or hard code the links in?
English page - www.mysite.com/
French page - www.mysite.com/fr
Essentially I do not want any of the French header and footer links to go to, for example,  www.mysite.com/fr/about-us, just to www.mysite.com/about-us.
When I'm changing one of the link entry destinations in the global, it looks like it will let me choose between the English and French, but when I save it it just shows a disabled entry.


texts:
Im looking for a good way to setup paging for new items with a simple "load more" button at the bottom.

I know i'd use something like

{% if craft.request.isAjax %}

on the listing template to not include the main _layout file for the ajax requests and then using the paginate tags to control which entries to return.

Curious is anyone has a more streamlined approach


texts: Dynamically update line item in Commerce 2

texts:
I'm currently trying to adjust the line items in a particular cart/order after an event is triggered.

I've got:

use craft\commerce\Plugin as CommercePlugin;

$this->requirePostRequest();
$request = Craft::$app->getRequest();

$cart = CommercePlugin::getInstance()->getCarts()->getCart(true);

$lineItem = CommercePlugin::getInstance()->getLineItems()->getLineItemById($cart->lineItems[0]->id);

$lineItem->price = 100.0000;
$lineItem->salePrice = 100.0000;
$lineItem->qty = 1;
$lineItem->note = '';

$cart->addLineItem($lineItem);

$cart->email = $request->getParam('orderEmail');

if (!Craft::$app->getElements()->saveElement($cart)) {
   return false;
}

But this seems to not do anything, except update $lineItem and not update the line item when the cart is then saved.


texts: Can I give every structure entry a custom layout by using the same template?

texts:
I want every structure entry to have a follow up page, http://thisismysite.com/handle/slug/followuppage.

So every slug, get a follow up page with different content but the same template. Is there a simple way of doing this?

Thank you in advance!


texts: Craft 3 plugin - how to update entry with field of Entries type

texts:
Using PHP, I want to update a field of Entries type of an existing entry.

Fields of type Text and Number will update with the following code:

$entry = Entry::find()->id($entryId)->one();
$entry->textField = 20; // works
$entry->entriesField = Entry::find()->id($relatedEntryIds)->all(); // doesn't work
Craft::$app->elements->saveElement($entry);

I looked into the source code and it seems to be expecting a craft\elements\db\EntryQuery object but I can't get it to work.

Can anyone please help?


texts: How do I sort and display event entries when each event can have multiple start times?

texts:
I have two different event types in my Events channel. The first one is events and it is very straightforward: Title, Description, Date. The other one is films and it is a little more complex: Title, Description, Screening(s) - which is 1 or more Date/Time. (I am using a supertable to allow the user to add as many screenings as they would like).

I have it set up like this to keep the administration of the content as DRY as possible - as all screenings of a movie will share the same description, title and other meta data.

I need to display all of my events and film screenings in an agenda view - sorted by date. How do I accomplish something like this?

The problem, if it isn't obvious, is that screenings from films could be staggered amongst screenings from other films so a simple for loop doesn't do the trick. I need to get all of the events and screenings (an individual screening being an "event" in this case) into an array that I can sort.

Thank you for any ideas or tips ahead of time.


texts: Stripe Bitcoin Support for Craft Commerce

texts:
Curious if anyone knows how we would setup Bitcoin support for Craft Commerce.

We know how to handle it on the user and Stripe site to enable the checkout but will we need a custom payment handler on the PHP side to handle the responses or will the built in Stripe support work the same way?


texts: Composer Issue When Doing exec From a Plugin

texts:
Curious if anyone has ever run into this before or may know what's going on here. I'm using the execWidget plugin (https://github.com/marionnewlevant/craft-exec_widget) to run a script from Craft's dashboard that does a composer install when the lock file has changed.

Here is the configuration for the plugin:

<?php
return [
  '*' => [
  ],
  'local' => [
    'commands' => [
      'composer install' => '../scripts/ed-day_composer.sh',
      'pull assets from production' => '../scripts/pull_assets.sh',
    ]
  ],
  'staging' => [
    'commands' => [
      'composer install' => '../scripts/ed-day_composer.sh',
      'push everything production' => '../scripts/push_all.sh',
    ]
  ],
];

Here is the composer install script:

#!/bin/bash

# Get the directory of the currently executing script
DIR="$(dirname "${BASH_SOURCE[0]}")"

# Include files
INCLUDE_FILES=(
            "common/defaults.sh"
            ".env.sh"
            "common/common_env.sh"
            "common/common_db.sh"
            )
for INCLUDE_FILE in "${INCLUDE_FILES[@]}"
do
    if [ -f "${DIR}/${INCLUDE_FILE}" ]
    then
        source "${DIR}/${INCLUDE_FILE}"
    else
        echo "File ${DIR}/${INCLUDE_FILE} is missing, aborting."
        exit 1
    fi
done

(cd "${LOCAL_ROOT_PATH}/craft"; HOME=${LOCAL_HOME} composer install)

I get a returned 127 error from the queue.log and the scrip does not actually work:

2018-06-25 14:10:12 [50.200.203.190][1][-][info][craft\queue\QueueLogBehavior::beforeExec]  [45] ExecWidget Task (attempt: 1) - Started
2018-06-25 14:10:12 [50.200.203.190][1][-][info][marionnewlevant\execwidget\jobs\ExecWidgetTask::log] executing ../scripts/ed-day_composer.sh
2018-06-25 14:10:12 [50.200.203.190][1][-][info][marionnewlevant\execwidget\jobs\ExecWidgetTask::log] returned 127

Based on testing I've done, I'm almost certain the issue is with composer because I get a success error message when I remove just the composer part of the line.

Composer works when SSHing in. Any idea what might be causing the issue?


texts: How can i check an entry author's user group?

texts:
I'm trying to check if a user is part of a user group but not having any success!
I tried this:

{% if entry.author.groups == 'authors' %}

But even though the user is definitely in a user group with that handle, the output inside that if statement doesn't show up.

I also tried this:

{% if entry.author.admin != 1 %}

That DID work, but unfortunately i don't just want to check if the user is not an admin, i want to specifically check their user group.


texts:
I have again some trouble with a Neo field.

I've a Neo field with different layouts. In one I will output content from some entries with a entries field.

The problem is: Sometimes I get output, sometimes I get only some of the selected entries as output and sometimes I don't get any output.

Here is my code:

{% nav block in entry.myContent.level(1) %}
    {% switch block.type.handle %}

        {% case 'team' %}

                    {% include "_includes/elements/teamGetMember" %}

    {% endswitch %}
{% endnav %}

And here is the call of the entries field

{% set entries = entry.teamGetEntres %}

{% if entries | length %}
    {% for entry in entries %}

{{ entry.description }}

    {% endfor %}
{% endif %}


texts:
I use a front-end entry form based on the official documentation (https://craftcms.com/docs/templating/entry-form), but after saving the entry, I am running in an error 404 on the entry page.

<input type="hidden" name="redirect" value="viewentry/{id}">

But if I replace the entry id with the slug in the browser (example.com/viewentry/example), then it works.


texts:
I'm building an entry type's menu, automatically populated with several sections. A route for dynamic menu had to be also created.

Code

{% set section = craft.sections.getSectionByHandle('sectionHandle') %}
{% set entryTypes = section.getEntryTypes() %}

{% for entryType in entryTypes %}

            {{ entryType.name|ucfirst }}

{% endfor %}

Output

craft.dev/sectionHandle/types/entryType.handle

When I access the link, It gets crazy.

Output

craft.dev/sectionHandle/types/sectionHandle/types/entryType.handle

I was trying everything I know, but Whatever I add in front of {{url('types/'~entryType.handle) }}, it gets duplicated.


texts:
This is really a Redactor-specific question, but I wondered if there is a simple way for clients to view what H1, H2 etc. text is formatted as? I currently instruct them to click on the HTML button whilst selecting the text / having the cursor on the text to view what heading the text is, however it would be really nice for them to be able to see what the text is formatted as without having to look at HTML code.

This is the 2nd or 3rd client now that has asked me the same question. I wonder if anyone has experience in providing a cleaner solution?

Thanks


texts: Fetching & Displaying an API Request using 'Fetch'

texts:
I'm currently in the process of calling an API endpoint and trying to display the data relating to it. But I'm having a bit of trouble using 'Guzzle/Fetch' in this scenario. I have the following code but it seems to be outputting nothing at all. (Plugin is all installed)

Template.html

{% set client = {
    base_uri : 'https://api.tickets.com/rest/v2/Events/2704/Reviews?order=1&count=30',
    timeout : 10
} %}

{% set options = {
    headers: new Headers({
      'Content-Type': 'application/json',
      'apiKey': 'aaabbbcccdddeee',
    })
} %}

{% set request = fetch(client, 'GET', options) %}

{% echo $request->getReasonPhrase(); %}