texts:
I'm running into an issue here, hopefully someone can shed some light.
I'm in a news category template,

{% for entry in craft.entries.section('news').relatedTo(category) %}
  {% for image in news.newsimage %}

  {% endfor %}
  {{ entry.title }}
{% endfor %}

My entry.title, date, etc. all output correctly, I can't figure out how to output the image asset associated with newsimage.


texts: How do I use Guzzle to send a post request from my plugin?

texts:
I have a plugin that listens for new users to be created. I am then sending that user to system "B" via an API call.

All is working fine the old fashion way, I am curious how to accomplish the same using Guzzle.

$client = new \Guzzle\Http\Client('http://api.site.dev/');
$uri = 'my/endpoint/path';

$request = $client->post($uri, array(
   'headers' => array('Content-type' => 'application/x-www-form-urlencoded'),
   'body' => array(
       'craft_id' => $event->params['user']->id,
       'name' => $event->params['user']->friendlyName,
       'email' => $event->params['user']->email
    ),
    'timeout' => 10
));

$response = $request->send();

Each time I get this response/error back:

Client error response
[status code] 422
[reason phrase] Unprocessable Entity

Which tells me that system "B" isn't getting the information in the correct format. The docs aren't so great with post examples, so I'm not quite sure where I'm going down the wrong path.

Thank you for any suggestions!


texts: Is it possible to skip entries with children?

texts:
Hi I m using elementapi plugin to create an json object from my elements. I would like to get all entries, but not those ones who have a children.

My criteria it looks like this now

'elementType' => 'Entry',
'criteria' => ['section' => ['pages', 'home']],
'transformer' => function (EntryModel $entry) {

this returns all entries. For example I have one single home and some other pages the result looks like this:

Home
About us <- this one has children
---------
test1
test2
test3
---------
Contact us

I would like to have result like this

Home
About us
Contact us

Is it possible to achieve this whit some criteria attribute. I've already tried to add level, like this

'criteria' => ['section'=>['pages','home'], 'level'=>'!=2' ]

not working

'criteria' => ['section'=>['pages','home'], 'level'=>1 ]

it's working but returns only pages not giving me the home section

I've tried hasChildren, hasDescendants none of this is working.

If someone can help, thank you in advance.


texts:
Is there a clean way to use angular in a dashboard widget for Craft 3 or craft 2? When the widget is created I can use it after a site refresh with no problems but I don't know if there is a hook or some kind of a javascript callback after the html is loaded so I can use my $compile function.

I'm not that experienced with angular yet so maybe my question is wrong here but since I'm able to run angular after every other dynamic html change I want to ask here. I know I can use this function in order to compile the template

angular.element(document).injector().invoke(
    [
        "$compile", function ($compile) {
            var scope = angular.element(document).scope();
            $compile(document)(scope);
            scope.$apply();
         }
    ]
);

But I need some callback event to fire it


texts: Is there a way to limit output of Tags related to an entry?

texts:
I've checked it with documentation but, tag model doesn't have limit() property as entries have.

Wondering, If there is any way around to achieve it?


texts:
Got myself into a seemingly simple dead-end block with twig syntax. I need to test against multiple items:

{% set segment1 = craft.request.firstSegment %}
{% if segment1 == 'one OR two OR three' %}
DO SOMETHING
{% endif %}

What's going wrong with this bit 'one OR two OR three'? brackets?


texts: Search for related entries based on tags

texts:
On an entry page I search for related entries based on the tags assigned to the respective entry. The following example works:

{% set tags = entry.q_tags.first %}

{% for tag in entry.q_tags.offset(1) %}
    {% set tags = tags ~ ' OR ' ~ tag  %}
{% endfor %}

{% set entries = craft.entries.search(tags).order('score') %}

I just wonder whether there is a smarter solution?


texts: How do I set up the Rich Text Editor Field (Redactor) for code snippets?

texts:
I'm trying to set us the Rich Text Editor for inputting code snippets. I've almost got it working except when I go back to edit the entry Redactor removes spaces I entered to format the code. Also setting the tabAsSpaces doesn't seem to work. It still adds tab space.

Here is what I have in Redactor config.json

{
    toolbar: false,
    visual: false,
    tabAsSpaces: 2,
    cleanOnPaste: false,
    cleanSpaces: false,
    cleanStyleOnEnter: true,
    paragraphize: false,
    minHeight: 200
}

And in the template

{% spaceless %}

    {{- block.html|replace({'&':'&amp;', '<':'&lt;', '>':'&gt;'})|raw -}}

{% endspaceless %}


texts: Is it possible to password protect a single page in Craft? Wordpress has this functionality built in. I would love to do it in Craft as well.


texts: How do I insert a special entry into a sections list?

texts:
I want to apologize if I'm not asking the question correctly, but basically this is what I want to do:

I have this craft.entries:

{% paginate craft.entries.section('example').limit(10) as entriesOnPage %}
  {% for entry in entriesOnPage %}

{{ entry.title }}

  {% endfor %}
{% endpaginate %}

How do I insert another list-item with a different class that has to always stay in same position. For this example in the 3rd spot, to look something like this:

I'm a title

I'm a title

I'm am different

I'm a title

....

Once again, I apologize if I'm not using the right terms, but hopefully the code can explain it.

Thanks!


texts: How do I call a service from my controller in a plugin?

texts:
I'm writing a plugin, and used plugin.io to generate my scaffolding.  In my controller I am attempting to call a service, and getting an error.

This is my service code from my generated plugin it lives at fulcrumdonation/services/FulcrumDonation_FulcrumCyberSourceService.php:

class FulcrumDonation_FulcrumCyberSourceService extends BaseApplicationComponent
{
    /**
     *
     * From any other plugin file, call it like this:
     *
     *     craft()->fulcrumDonation_FulcrumCyberSource->exampleService()
     */
    public function exampleService()
    {
    }
}

And just as the scaffolding suggests, I'm attempting to call this function in the controller:

craft()->fulcrumDonation_FulcrumCyberSource->exampleService();

But when I add that line of code in the controller I get the following error:

  Property "Craft\WebApp.fulcrumDonation_FulcrumCyberSource" is not
  defined.

What am I missing here?


texts: getPath() does not return subfolder for S3 asset source

texts:
I'm reading through the Craft docs in relation to the AssetFileModel.

Looking at the getPath() method, this reads in theory that it should return the full path to the asset relative to the root, with any sub directories etc.

https://docs.craftcms.com/api/v2/models/AssetFileModel.html#getPath-detail

Yet this doesn't to appear to be the case, I seem to be getting /filename.ext

If however I was to use folderPath() this then provides the subfolder name configured in the relevant S3 asset source.

https://github.com/craftcms/cms/blob/master-v2/src/models/AssetFileModel.php#L384

Is this correct? Is getPath() meant to behave this way with S3 asset sources?


texts: An SEO software tool says 'keywords' meta tag is obsolete

texts: Can anyone tell me where on the Craft dashboard I can correct this and upload new keywords?


texts: I try to add element to structure, and I want to add to this element parent ID

texts:
Form code:

    Date
    <select name="fields[parent][]">
    {% set entries = craft.entries.section('order').level(1) %}
        {% for entry in entries %}
            <option value="{{ entry.id }}">{{ entry.title }}</option>
        {% endfor %}
    </select>

I want to choose Parent from list, and I want to add the element to parent.


texts:
I want to extract data from Craft to a Vue component.

I create a vue component like this:

{% set entry = craft.entries.section('homepage').first() %}
<template>

{{entry}}

</template>

When I run the app it doesn't show the value of entry, but I created a file title.twig like this and it works:

{% set entry = craft.entries.section('homepage').first() %}

{{ entry }}

In vue project I added this line Vue.config.delimiters = ["${", "}"];in main.js file and I addedindex.twig file to templates/ like:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <title>Test</title>
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,700&display=swap" rel="stylesheet">

How do I retrieve data directly from the Vue component? Thanks!


texts: Editing assets custom fields in a full page publish form

texts:
So this is just a question to see if something is actually doable.

When you double click an asset, you get a little modal opening where you can see see custom field attached to said asset.

Would it be possible (plugin work I'm guessing) to open this model as a full publish form like entries have..?

Just wondering... :)


texts: White screen trying to install, log shows call to undefined function ctype_alpha()

texts:
I have looked through every resource I can find for this question and haven't had any luck.

OS: Ubuntu 16.04
localhost successfully shows Ubuntu landing page
localhost/info.php successfully shows PHP page and extensions
ctype is NOT listed on the info.php page
Wordpress functions properly
I am using the LAMP stack
I created a database for craft, renamed htaccess to .htaccess in public, altered db.php in the craft/ directory, ensured there are no
syntax errors, etc, etc.
Essentially, any of the go to responses I have already tried. I've been dealing with this for 3 days now.
localhost/craftCMS/public/index.php/admin sends me to a blank white page
phperrors.log file shows "called to undefined function ctype_alpha()"
When I try to install php7.0-ctype it installs php7.0-common, but ctype doesn't seem to be there
This might be a dumb question, but am I actually supposed to go to "example.com/admin"? If so, I receive an "XML parsing error: not well
formed" when I try that.

I probably missed some details that would be helpful to know, so please let me know if you need any further info. Help on this would be greatly appreciated... I want to compare Craft and WordPress but that's difficult when I can't get Craft running.

EDIT:
Brad's comment about multiple PHP installations prompted me to uninstall and reinstall PHP alone. I had uninstalled and reinstalled everything at some point, but not just PHP. After a purge and fresh installation, and remembering to install libapache2-mod-php7.0, I FINALLY see the craft installation page. Thank you guys for your help!


texts: Grab first  or  src from Rich Text field

texts:
I've had the unfortunate task of importing thousands of entries in to Craft from Worpdress.

Each of the entries has a Rich Text field and within the first couple of paragraphs there is an image.

I need to use this image as the overview thumbnail on a listing page. How can I extract that image tag, or just the src attribute from it to get the url.

Example of the image tag

<img class="size-full wp-image-13325" src="https://www.domain.com/news/wp-content/uploads/2015/12/image.jpg" alt="etc" width="620" height="385" />

I have tried to use the |split filter and some others with no success.

Thanks in advance for any help/direction


texts: Have some categories NOT linked to a category entry

texts:
So my client has thrown a curve ball!  I've set-up a list of categories for the types of work they cover.  However, they DON'T want all of the categories to actually link to an entry.  In other words, they don't have content for some of the category pages, they would still like to SHOW the category on the front end but not have it clickable.

So, some category links are clickable, others not :/

Any ideas?

Thanks

Martin


texts: German locale & English CP language resulting in disappeared entries

texts:
I have just one locale (German, de). Now, I've changed my CP language to English ('defaultCpLanguage' => 'en' in general.php).

But now, all my entries have disappeared in the CP (Craft Pro 2.4.2670).

What am I doing wrong?

Thank you very much for your help!
MISc


texts:
I've got a content type for team members but whenever I try to add one it gives me an error saying "the URI 'team' has already been taken".

I assume the URI is made from the slug, which is where I get the error.
The title of the team members is made automatically from the first name and last name.

And even when I type in the slug myself it keeps giving the same error. What's weird is that I was able to create one team member successfully but it started failing afterwards.

URI error:

Title settings:


texts:
I currently have a plugin that's successfully sending email using EmailModel(). The problem is: it's sending a multi-part email with HTML and plain text components. For this particular email, it would be best if I could just send the plain text portion.

Is there a way to disable the HTML segment when sending via EmailModel()?


texts: Access optimizedTitle field within Twig template

texts:
I'm trying to access the value set for my optimized title within Sprout SEO. I've had a read through this page: https://sprout.barrelstrengthdesign.com/craft-plugins/seo/docs/advanced-customization/custom-metadata-variable - but have had no luck.

Why I want to do this is because I'm loading my pages via AJAX and need to set the title once the content is loaded. I've tried various iterations of {{ entry.metadata.metadata.optimizedTitle }} but to no avail.

Alternately, do you know how to set the metadata to update upon each AJAX page load?


texts: Does Craft Have a URL Rewrite Vulnerability?

texts:
We could use some help tracking down a consistent error on our Craft installs according to Acunetix Security Audits.

URL Rewrite Vulnerability

  It was identified that this application supports the legacy headers
  X-Original-URL and/or X-Rewrite-URL.

  Support for these headers lets users override the path in the request
  URL via the X-Original-URL or X-Rewrite-URL HTTP request header and
  allows a user to access one URL but have web application return a
  different one which can bypass restrictions on higher level caches and
  web servers.

  Many web frameworks such as Symfony 2.7.0 to 2.7.48, 2.8.0 to 2.8.43,
  3.3.0 to 3.3.17, 3.4.0 to 3.4.13, 4.0.0 to 4.0.13 and 4.1.0 to 4.1.2 , zend-diactoros up to 1.8.4, zend-http up to 2.8.1, zend-feed up to
  2.10.3 are affected by this security issue.

https://symfony.com/blog/cve-2018-14773-remove-support-for-legacy-and-risky-http-headers

https://framework.zend.com/security/advisory/ZF2018-01

These sites are hosted on Forge / Linode servers.
Versions vary, but most are recent-ish Craft 2.X
A couple (though not all) use the Redirect Manager plugin


texts: How to set other fields as required in Craft Commerce checkout process?

texts:
I'm using Craft Commerce with the default checkout template. At the step of completing addresses, only First Name, Last Name & Country are required fields by default.

As I'll sell non-digital products, other fields like Address, City, Zip Code must be required and the next step of the checkout process (i.e. Shipping) should not be reached if some fields are still empty.

How can I make these other fields required with Craft validation ?


texts: Class '...SiteModuleService' not found when used inside scout.php

texts:
I have a custom SiteModule that is used inside scout.php to deliver indexing data to Algolia.
I have followed CraftQuest's tutorial on creating a custom SiteModule for handling the indicies.
The setup works when running locally. But when I run it on my host (Hyperlane), I get the error:
Class 'modules\sitemodule\services\SiteModuleService' not found
I reference the SiteModule in scout.php thus:
'indices'       => (new \modules\sitemodule\services\SiteModuleService)->getIndicies()

App.php contains:
return [
    '*' => [
        'modules' => [
            'site-module' => [
                'class' => \modules\sitemodule\SiteModule::class,
            ],
        ],
        'bootstrap' => ['site-module'],
    ]
];

Composer version (local/prod): 2.0.12
PHP version local/prod: 7.3.12/7.3.3

What am I doing wrong?


texts: Seeing some odd behavior in Chrome where we can no longer log into our dev site, which is currently served over HTTP.  But, if we try logging in using an incognito window, it works.  It looks like the CRAFT_CSRF_TOKEN cookie is not getting written - error message in the console (under headers->set-cookie) is "This Set-Cookie was blocked because it was not sent over a secure connection and would have overwritten a cookie with the secure attribute". Have cleared out all cookies, but this does not help.  The login DOES work using an incognito window, but hoping to be able to get it working on a regular window as well, if possible.


texts: Show Matrix Assets from German language in other locales

texts:
I have a website with three locales (de, fr, it). On a Matrix Field i have Assets where are only uploaded in German language. Now i'm trying to show those assets also in French and Italian language.

Any ideas to solve this? I have tried to put a .locale('de') to get the german fields, but if i change the language, the assets are not displayed.

Here is my code:

    {% for entry in craft.entries.section('sitemap','staticContent').status('live').slug(lastSegment).limit(1) %}

    {% for block in entry.multiContent %}

        {% if block.type == "documents" and block.downloadbarAlsDigitalesDokument == "1" %}

                    {% set items = block.datei %}

                        {% for item in items %}

                                 {{ item.title }}

                        {% endfor %}

        {% endif %}

    {% endfor %}

{% endfor %}


texts:
One of my clients' sites is https://anovaworks.com/. The second section on the homepage looks like this:

There's some small black text in the top left of the image that's coming from a matrix field.

It's supposed to look like this, and if you go to https://anovaworks.com/index.php or https://anovaworks.com/?, it looks correct:

I cannot figure out what's causing this. Anyone have any ideas?

Template code:

        {# blue circle svg #}
        {% for matrix in entry.homepageTagline.all() %}

{{ matrix.firstLine}}
{{ matrix.secondLine }}

        {% endfor %}
          <button class="button">{{ entry.homepageTaglineButtonText }}</button>


texts:
Having issues getting Craft to use a transform I set in the CP: squarePhoto. I keep getting a template error, even though that transform exist.

  Variable "squarePhoto" does not exist

The template code in question is:

{% for asset in block.photoImages %}
    <img src="{{ asset.getUrl(squarePhoto) }}" alt="{{ asset.title }}">
{% endfor %}

After digging through other threads, I saw that Craft adds a subfolder to the directory with the transform name–this has not been generated. What am I missing?

I've also added the config var 'generateTransformsBeforePageLoad' => true, to my general.php to see if that made a difference.


texts: Can Craft or any of its plugins render down flat html files for speed

texts:
Having spoken to our 'ops guy' I've come to understand that if Craft CMS can render flat html or cache some of the pages then it makes thing a lot quicker to load etc.

Is this something craft can do? Also will it will be ok using assets from a cloud front CDN setup too?


texts: Dynamic Reply-To In Sprout Forms Notification

texts:
Is it possible to get Sprout Forms built in notifications to have dynamic reply to details? Or even from name etc?

I'm wanting my client to be able to respond directly to the client when Sprout Forms notifies them that a new submission has been posted.

Putting {{ formFieldName }} with the relevant field name in the "Reply To Email Address" field made the email not send (so obviously doesn't work).

Thanks.


texts:
We have set up a Craft 3 installation with composer to serve as boilerplate for a number of upcoming projects. The installation sits in a private git repository and the plan is to clone it when we start a new project.

Everything works fine, but since new projects will spawn from the boilerplate, the Security Key is the same for all of them - which probably is a bad idea.

Is there a way to assign a new security key when we clone the boilerplate for a new project? Are there other security considerations to take into account?

Thanks a lot!


texts: How do I grab the label of a LJ Dynamic dropdown fields

texts:
I have a LJ Dynamic field set up with the following code that pulls in a list of stores to an event section.

{% for store in craft.entries.section('stores').order('title') %}
  { "value":"{{ store.storeId }}" , "label":"{{ store.title | raw}}"}
  {% if not loop.last %},{% endif %}
{% endfor %}

My problem is that I can't seem to get the label from the field to display on the front end as I keep getting the error message
"Impossible to access an attribute ("label") on a string variable ("412")" 412 is the value of the particular store I have selected for my event.

Where: {{ entry.stores.label }}

If I add just { entry.stores } it will output the value.

This is probably something very obvious but got me a bit stuck.


texts: Dynamic Subfolders leaving empty folders behind

texts:
I have {status}/{category}/{slug} as the path for uploading photos. When the status changes on the entry, then the photos associated with that entry move to the correct folder.

However, it leaves behind empty {category}/{slug} folders in the {status} folder it used to sit in. I don't believe it did so when I tried {status}/{slug} -- is it possible to do this without leaving debris in the previous folders?


texts:
Been trying for days to figure this one out. How do I extract entries from a channel and display only entries related to a category? How do I pull in the related photo? I have this code below but it pulls in all the photos. I don't think I'm doing doing this right.

{% set category = craft.categories.slug('spring-summer').first() %}

{% for post in craft.entries.section('product').relatedTo({targetElement: category}) %}

{{ post.title }}

{{ post.price }}

    {% for product in craft.entries.find() %}
        {% for image in product.photo %}

        {% endfor %}
    {% endfor %}
{% endfor %}


texts: Payment Method and Discount elements query by ID in Twig

texts:
In Craft 2, is it possible to query a specific element by ID in Twig?  They aren't mentioned in the docs.

I was trying things like these but without success:

{{ craft.commerce.paymentMethods.id(1).name }}


texts:
I want to add a 301 redirect plugin to a Craft CMS 2.6 website. I only have user permission as well.

Please give me steps on how to add my redirects to the back-end of the site?


texts: Is there a way to divide an entry's data into multiple subviews with unique URLs?

texts:
I have a one-level structure where I am storing a client's projects, with the ability to reorder them by dragging the entries in the structure.

Each project has been designed to have multiple subpages of information available, accessible by clicking on tabs, where each tabbed view shows a subset of the project data.

Ideally, each tab would have its own URL so I can deep-link to the subpages, each served by a different template, but load in the views via ajax when a tab is clicked on. Is it possible to derive multiple child views with distinct templates from a single entry, without having to manually add child tab entries for every project, which I definitely don't want to make the client do?

The alternative would be to load in all the tabs on initial page load, and show and hide them as they're clicked on, and use pushstate to deep link to those tabs, but I'd rather have them as proper server side URLs, I think.

Does anyone know if this is possible?


texts: Any examples of Craft Commerce checkout process for PayPal or any other gateway?

texts: I'm unable to find much documentation nor examples for how to actually utilize Craft Commerce and successfully convert a cart to a completed order.  Any help would be greatly appreciated!


texts: When creating a fieldtype how do I provide methods to be used in the templates?

texts:
I have created a fieldtype that saves a single integer to the database, it has some settings that defines the maximum value that integer can be:

protected function defineSettings()
{
  return array(
    'maxNumber' => array(AttributeType::Number, 'min' => 2, 'default' => 12)
  );
}

What I want to do when outputting my field in the templates is something like this:

The value is {{ entry.myField }} of {{ entry.myField.maxNumber }}

Anyone have any ideas? Do I need to create a data class like the options-based fields use or something? I'm just stabbing around in the dark here...


texts: Creating and saving a GlobalSet element type in Craft 3

texts:
The following code is in a migration. It runs fine and there are no errors and prints SAVED, but nothing is saved in the globalsets database table.

All my other content migrations run fine so it is not a DB issue.

    $globalConfig = [
      "type" => \craft\elements\GlobalSet::class,
      "settings" => [
        "name" => "Meta",
        "handle" => "meta"
      ],
    ];

    $element = Craft::$app->getElements()->createElement($globalConfig);

    if (Craft::$app->getElements()->saveElement($element)) {
        print "SAVED";
    }

Why is this not saving ?


texts: Is it possible to have different fields associated with users in different groups?

texts: We're developing a client site in CraftCMS that has 2 different frontend user groups. I know it's possible to set up custom fields for users but I'd like to set up different additional profile fields for each Group i.e. Group A has one set of custom fields and Group B has another. Is that possible?


texts: SEO titles/descriptions for tags and archive pages

texts:
I have a blog setup with a Categories, Archive and Tags.

In my _layout template I've been using the following to pull in SEO titles from fields, or Page/Category Titles is that's not been defined.

{% if entry is defined %}
    {% set seoTitle = entry.seoTitle %}
    {% set seoDescription = entry.seoDescription %}
    {% set seoImage = entry.seoImage %}
    {% set seoType = entry.seoType %}
    {% set title = entry.title %}
    {% set url = entry.url %}
{% endif %}

{% if category is defined %}
    {% set seoTitle = category.title %}
    {% set seoDescription = category.title %}
    {% set seoImage = category.seoImage %}
    {% set seoType = category.seoType %}
    {% set title = category.title %}
    {% set url = category.url %}
{% endif %}

<title>{{ siteName }} - {% if seoTitle is not empty %}{{ seoTitle }}{% else %}{{ title }}{% endif %}</title>
<meta name="description" content="{% if seoDescription is defined %}{{ seoDescription }}{% else %}{{ title }}{% endif %}"/>
{% if url is defined %}<link rel="home" href="{{ url }}" />{% endif %}
<meta name="twitter:card" content="summary" />
{% if url is defined %}<meta property="og:url" content="{{ url }}" />{% endif %}
<meta property="og:title" content="{% if seoTitle is not empty %}{{ seoTitle }}{% else %}{{ title }}{% endif %}" />
<meta property="og:description" content="{% if seoDescription is defined %}{{ seoDescription }}{% else %}{{ title }}{% endif %}" />
{% if seoImage is defined %}
    {% for image in seoImage %}
        <meta property="og:image" content="{{ image.getUrl()}}" />
    {% endfor %}
{% endif %}

How should I approach this for the archive and tag pages as simply doing something like the below doesn't work?

{% if tag is defined %}
{% set seoTitle = tag.title %}
....
{% endif %}


texts: Create entry from template / UI without a form

texts:
I need to create an entry from my UI after the user triggers a particular event on the page.

I want this to happen automatically and not rely on the user to submit a form.

Is there a way to create an Entry from a twig template (i.e. by calling the required controller function)?  If not, is there an existing plugin that could work?

My content structure is something like this:

mySection = name of Channel that the entires will belong to.  Has the following fields:

myField1 = number
myField2 = text
myField3 = number
user = craft user field (relates the entry to an appropriate user)

I was hoping I could set those variable and call some sort of submit/save function to create the new Entry.


texts: Multi-environment database config being ignored

texts:
The 'localhost' array is not being recognized. If I add :3307 to the '*' array's server attribute, it works. Here's the contents of my db.php:

return array(

  '*' => array(
    'server' => 'localhost',
    'user' => 'av01759',
    'password' => '*******',
    'database' => 'av01759_maltaministries',
    'tablePrefix' => 'craft',
  ),

  'localhost' => array(
    'server' => 'localhost:3307'
  )

);

This a fresh Craft install with no tweaks. Any ideas?


texts:
There is a set of entries:

{% set entries = craft.entries.section('news') %}

Each entry has a custom field customUserField.  customUserField this is a field Users. How do you fetch entries where customUserField === currentUser?


texts: Revoke user permissions but not change the usergroup

texts:
I have  a client who would like to edit a users permissions. However instead of adding permissions on a per user basis, they would like to remove permissions for that user by unchecking the item. However because it's enabled for the users usergroup it's not possible to uncheck. Am I missing something? Or should we create a new user group?

So in the above photo I'd like to uncheck, for this user only, a couple of different permissions.


texts: Selecting entries with min value through search param

texts:
Trying to do something quite basic but can't seem to get it right..

I'm searching through a form, and want to select entries where the value 'pax' is equal or more than the searched value.

{% set params = {
section:    'ships',
limit:      null
} %}

{# pax #}
{% if craft.request.getParam('pax') %}
  {% set pers = craft.request.getParam('pax') %}
  {% set params = params|merge({'pax' : '>= pers'}) %}
{% endif %}

Now, this doesn't seem to work. However, if I'd change the last line to:

  {% set params = params|merge({'pax' : '>= 30'}) %}

It gives me excellent results. So, what am I doing wrong here?

Much appreciated!!


texts: Unable to Update Entry - Table doesn't exist

texts:
I am trying to update an entry in a structure but getting the error:

CDbCommand failed to execute the SQL statement: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'nisp.craft_matrixcontent_colcontent' doesn't exist. The SQL statement executed was: SELECT `elements`.`id`, `elements`.`type`, `elements`.`enabled`, `elements`.`archived`, `elements`.`dateCreated`, `elements`.`dateUpdated`, `elements_i18n`.`slug`, `elements_i18n`.`uri`, `elements_i18n`.`enabled` AS `localeEnabled`, `content`.`id` AS `contentId`, `matrixblocks`.`fieldId`, `matrixblocks`.`ownerId`, `matrixblocks`.`ownerLocale`, `matrixblocks`.`typeId`, `matrixblocks`.`sortOrder`
 FROM `craft_elements` `elements`
 JOIN `craft_elements_i18n` `elements_i18n` ON elements_i18n.elementId = elements.id
 JOIN `craft_matrixcontent_colcontent` `content` ON content.elementId = elements.id
 JOIN `craft_matrixblocks` `matrixblocks` ON matrixblocks.id = elements.id
 WHERE ((((((elements_i18n.locale = :locale) AND (content.locale = :locale)) AND (elements.archived = 0)) AND (elements.enabled = 1)) AND (elements_i18n.enabled = 1)) AND (matrixblocks.fieldId=:matrixblocksfieldId1)) AND (matrixblocks.ownerId=:matrixblocksownerId1)
 GROUP BY `elements`.`id`
 ORDER BY `matrixblocks`.`sortOrder` LIMIT 100. Bound with :locale='en_gb', :matrixblocksfieldId1='285', :matrixblocksownerId1='1656'

The table it mentions is a matrix related table which does not exist - it was deleted a while back.
It was used in a Matrix - Super Table - Matrix test but I was getting errors with it and decided not to use this then so deleted it.
I only started to get this error when I added a new Matrix Field to this entryType. But I have emvoed the Matrix field and now I am still getting the error and can't update.
Any idea's as to the resolution?


texts: "An unknown error occurred" in assets screen

texts:
I have a number of assets resources all set to upload to the same amazon s3 bucket. Two of my four assets resources show "An unknown error occurred" twice when I view them in /admin/assets.

The files in the folder do not show up. In the logs the following error appears:

Error: Call to a member function format() on null in /apps/cms/craft/app/helpers/AssetsHelper.php:81

When I click Upload files I can upload files, but they do not show up once the upload has finished (no files are shown). They do get uploaded to s3 though. The message "an unknown error occurred" appears again.

Subfolders in that same folder show up perfectly and have all of their content visible and it is possible to upload new images without a hitch.

How can I get the top level folders to work again? What could cause this?


texts: Possible to change style of password reset page

texts: Is it possible to change how the password reset box appears when a user requests a password reset? Ideally we would like to include the same functionality but within a page that we have control over so that it looks like the same website users are used to.


texts:
I've just launched my new site here and I'm playing around with the caching options with Craft. I'm hosting my site with Siteground which gives me access to their Supercacher option, it offers Static cache and Memcached, both of which I have enabled.

I have configured Craft to use Memcached via the general.php config file 'cacheMethod' => 'memcache' and placed the memcache.php file into the config directory as well with 'useMemcached' => true, set to true and my host to 'host' => 127.0.0.1, plus the correct port that is provided by my host. I've also got Cloudflare CDN running which is taking care of a lot of the heavy lifting.

I've also wrapped {% cache %} tags around the mainly static content.

However I'm still left feeling slightly uneasy about my TTFB and site performance, so I have some questions:

Should the IP address for 'host' in memcache.php be wrapped with quotes? I saw "localhost" was in the default file but typically IP addresses are not, so I didn't
My TTFB has been wildly inconsistent, ranging anywhere between 200ms up to 2s. What is the best way to troubleshoot such an issue with Craft? Or is this more of a host issue?
I'm using AJAX page transitions based off this article: https://designbycosmic.com/journal/craft-cms-ajax-page-transitions-with-history-pushstate - could this be messing things up?

I appreciate any feedback or pointers people may offer because I'm feeling a little lost/overwhelmed at the moment. cheers!


texts:
This may be basic but not finding the right way to do it so here is a question.
I have a category page where each has its own url and have custom fields on it. But for some reason the author is not showing on the right side like the entries do?

Is there a reason categories dont have authors or am i missing something?


texts: Best Technique for have sections in display in same page with anchor link to each section

texts:
I'm currently in the process of making a website for a restaurant and using Craft CMS & I'm not sure how to go about making the menu page.

It is a very complete page with a bunch of different categories of food & a bunch of items and pictures for each category. My goal is to have a subnav on the left be Sticky & have them scroll down with anchor links to the corresponding section.

I'm still relatively new with Craft CMS and wanted some opinions/tips on what the best and cleanest way of doing this would be.

Here is a wireframe so I could show you guys what I'm trying to accomplish.

Have the left Nav with anchor links to the corresponding food section.
What is the best technique to create those food category sections & put them into the page.


texts: Frontend form to change Craft Commerce user's password?

texts:
I'm trying to modify Craft 3's example 'Change password' form to work with a logged in Commerce 2 user, and have copied that code to templates/setpassword.twig.

Two problems...

(1) The {{ code }} and {{ id }} variables throw Don't exist errors.

(2) If I comment those variables out, I get a Page not found/"Unable to resolve the request: users/setPassword" error when submitting the form.

Clearly I'm doing this totally wrong ... can anyone set me straight?

<form method="post" accept-charset="UTF-8">
{{ csrfInput() }}
<input type="hidden" name="action" value="users/set-password">
<input type="hidden" name="code" value="{{ code }}">
<input type="hidden" name="id" value="{{ id }}">

New Password

<input id="newPassword" type="password" name="newPassword">
{% if errors is defined %}

        {% for error in errors %}

{{ error }}

        {% endfor %}

{% endif %}

<input type="submit" value="Submit">


texts: Load category values based on another category field

texts:
I'm really new to Craft CMS,
I have a site where I need to do something like this:
There are 2 categories, Brand and Model (Models have a relation to Brands via category field).
In entries I have 2 fields set for both of the categories and whenever I choose a brand in entries I want to be able to filter automatically the Model dropdown to show only categories that have the brand as the selected one.
I hope this is not a duplicate question.
Thanks in advance


texts: How I can output Craft Commerces Stripes Publishable Key in a template

texts:
I would like to know how I can output Craft Commerces Stripes Publishable Key, which I define under Payment Methods, in a template?

The value I set is settings[publishableKey].

Thanks
Stefan


texts:
I'm trying to render a template from a console command, but i'm getting the following error:

Craft\ConsoleApp and its behaviors do not have a method or closure named "getTheme"

The code looks like this:

public function actionIndexTemplate ($id = null)
{
    $criteria          = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->section = 'products';
    $criteria->limit   = 1;
    $criteria->id      = $id;
    $entry             = $criteria->first();

    if ( $entry ) {
        $output = craft()->templates->render('indexer/Product', [
            'element' => $entry
        ]);
        $data       = json_decode($output, $assoc = true);
    }
    else {
        echo "No entry found\n";
    }
}

And here is the stack trace:

CException: Craft\ConsoleApp and its behaviors do not have a method or closure named "getTheme". in /craft/app/framework/base/CComponent.php:266
Stack trace:
#0 /craft/app/framework/base/CErrorHandler.php(390): CComponent->__call('getTheme', Array)
#1 /craft/app/framework/base/CErrorHandler.php(340): CErrorHandler->getViewFile('exception', 500)
#2 /craft/app/etc/errors/ErrorHandler.php(233): CErrorHandler->render('exception', Array)
#3 /craft/app/etc/errors/ErrorHandler.php(137): Craft\ErrorHandler->handleTwigError(Object(Craft\TemplateLoaderException))
#4 /craft/app/framework/base/CErrorHandler.php(131): Craft\ErrorHandler->handleException(Object(Craft\TemplateLoaderException))
#5 /craft/app/framework/base/CApplication.php(750): CErrorHandler->handle(Object(CExceptionEvent))
#6 [internal function]: CApplication->handleException(Object(Craft\TemplateLoaderException))
#7 {main}%

Here is the underlying error:

2016/11/23 18:15:13 [error] [exception.Craft\TemplateLoaderException] Craft\TemplateLoaderException: Ikke i stand til å finne malen “indexer/Product”. in /craft/app/etc/templating/twigextensions/TemplateLoader.php:123
Stack trace:
#0 /craft/app/etc/templating/twigextensions/TemplateLoader.php(71): Craft\TemplateLoader->_findTemplate('indexer/P...')
#1 /craft/app/vendor/twig/twig/lib/Twig/Environment.php(312): Craft\TemplateLoader->getCacheKey('indexer/P...')
#2 /craft/app/vendor/twig/twig/lib/Twig/Environment.php(378): Twig_Environment->getTemplateClass('indexer/P...', NULL)
#3 /craft/app/etc/templating/TwigEnvironment.php(61): Twig_Environment->loadTemplate('indexer/P...', NULL)
#4 /craft/app/vendor/twig/twig/lib/Twig/Environment.php(347): Craft\TwigEnvironment->loadTemplate('indexer/P...')
#5 /craft/app/services/TemplatesService.php(253): Twig_Environment->render('indexer/P...', Array)
#6 /craft/plugins/indexer/services/Indexer_IndexService.php(136): Craft\TemplatesService->render('indexer/P...', Array)
#7 /craft/plugins/indexer/consolecommands/IndexerCommand.php(93): Craft\Indexer_IndexService->renderTemplate(Array)
#8 [internal function]: Craft\IndexerCommand->actionIndexTemplate('35262')
#9 /craft/app/framework/console/CConsoleCommand.php(172): ReflectionMethod->invokeArgs(Object(Craft\IndexerCommand), Array)
#10 /craft/app/framework/console/CConsoleCommandRunner.php(71): CConsoleCommand->run(Array)
#11 /craft/app/framework/console/CConsoleApplication.php(92): CConsoleCommandRunner->run(Array)
#12 /craft/app/framework/base/CApplication.php(185): CConsoleApplication->processRequest()
#13 /craft/app/etc/console/yiic.php(81): CApplication->run()
#14 /craft/app/etc/console/yiic(4): require_once('/Ind...')


texts: Why is Sprout Forms returning 302 for ajax requests?

texts:
I am using Sprout Forms on a Craft 3 site and trying to submit my form via ajax.

I've been able to do this many times in Craft 2, but not having much luck with 3 (yet). The docs look mainly for Craft 2 - is there a better way to find examples for Craft 3?

Here is what the headers look like that I am sending:

CRAFT_CSRF_TOKEN: <huge string hash>
action: sprout-forms/entries/save-entry
redirect: <long redirect hash>
handle: contact
fields[fullName]: Damon
fields[email]: name@test.com
fields[phone]: 211-111-1111
fields[message]: Hello.

I am always getting a 302 response back - without any error or other indication of what might be missing. If I remove the handle field, I'll get a 400 error, so I know I'm hitting the correct method.

Status Code: 302 Found

Here is what my js looks like:

$.ajax({
    type: 'post',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    cache: false,
    data: $('#contact-form').serialize(),
    url: $('input[name=action]').val(),
    processData: false,
    dataType: 'json',
    timeout: 50000
}).done(function (response) {
    console.log(response);  // nothing.
}).fail(function (error) {
    // Total fail.
});

Here is what I am including in my form that is Craft/Sprout specific.

{{ csrfInput() }}
<input type="hidden" name="action" value="sprout-forms/entries/save-entry">
<input type="hidden" name="redirect" value="{{ form.redirectUri|hash }}">
<input type="hidden" name="handle" value="{{ form.handle }}">

Thank you for any suggestions!


texts: Commerce - How do I add the purchaser of a specific product to a user group?

texts:
I want all buyers of a specific product to automatically be added to a specific user group.

How do I do this?


texts: Query only returning 100 records at a time?

texts:
I am trying to export data from a database to a csv file, I am using the code below to retrieve the data from the DB, but it only returns 100 rows, how can I fix that?

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'educators';
$query = craft()->elements->buildElementsQuery($criteria);
$query->order('title asc');
$queryResults = $query->queryAll();
$educators = EntryModel::populateModels($queryResults);

foreach ($educators as $educator) {
   //Write to file
}


texts: Load a page via HTTP and make an AJAX request via HTTPS afterwards using CSRF-Token

texts:
I have the following scenario:

A page is loaded via HTTP
The user fills out a form and submits its contents via HTTPS
The craft CSRF prevention is enabled, so the previousy generated CSRF-Token is submitted along with the form
Craft responds with a HTTP 400, because the Token is not valid for the request being send over HTTPS

Is there a way to use Crafts CSRF prevention feature in this scenaria? So say for example tell Craft to generate the token for an expected HTTPS request?

Regards,
Clemens


texts: Performance hit from Entry Url Format with multiple {% if %} clauses?

texts:
With help from this answer, I've got an Entry Url Format that can include top, 2nd, or 3rd-level categories.  It works for any of these situations:

top-level-category/entry.slug
top-level-category/second-level-category/entry.slug
top-level-category/second-level-category/third-level-category/entry.slug

{% if object.mainCategory.last().level == 3 %}{mainCategory.last().parent.parent.slug}/{% endif %}{% if object.mainCategory.last().level > 1 %}{mainCategory.last().parent.slug}/{% endif %}{mainCategory.last().slug}/{postDate.year}/{slug}

It's ugly, but it works. But I'm wondering if it is slowing things down a bit.  Does anyone have any knowledge in this area?


texts: How do I show something only for a parent segment and not it's children?

texts:
How do I display something only for one of the parent Structure sections and not others or this sections children?
I was thinking of using

{% if craft.request.segment(2) == 'modules' and craft.request.lastSegment|length %}''

but that still shows for its children.


texts:
So, in my template I get what I'm calling parentCategory, and I can output what I need:

{% set parentCategory = craft.categories.slug(craft.request.getSegment(2)) %}
{# parentCategory.title and parentCategory.slug output fine #}

But shortly after, I'm wanting to get all the descendants of parentCategory, like so:

{% set cats = craft.categories.descendantOf(parentCategory.id).find() %}
{# outputs all categories, whether descendants or not #}

It seems parentCategory.id is empty:

{{ parentCategory.id }}
{# outputs nothing #}

Any ideas where I'm going wrong here? Why is no ID being returned while title, slug and my custom fields are working fine?

Here's line 1 and 2 from my template:

{% if craft.request.getSegment(3) %}
    {% set parentCategory = craft.categories.slug(craft.request.getSegment(2)) %}

If I change line 2 to:
{% set parentCategory = craft.categories.slug(craft.request.getSegment(2)).first() %}

I get the following error:

Craft\CategoryModel and its behaviors do not have a method or closure named "first".

Yet, I can repeat line 2 later in the template and include .first() and not get the error. What go on?


texts:
I have added additional fields to my user profiles. I need to be able to change and save these via my plugin. How do I set those values before calling

craft()->users->saveUser($user);


texts: How do I output a dropdown's values if I'm on a registration form not tied to an entry?

texts:
I have a registration form on my website. All of the fields here so far have been text, which is no problem. However, I've just been asked to create a dropdown box for users to select their salutation (mr, mrs, doctor etc).

I've created the field in the backend and linked it to Users, and I can update it through a front-end form no problem using the value="users/saveUser" method, and pulling the values using currentUser.salutation.options. However, when registering, I can't output the values like that as the user isn't signed in (because they're registering), so there is no currentUser. I can't use the documentation code:

{% for option in entry.dropdownFieldHandle.options %}
    <li>{{ option }}</li>
{% endfor %}

as there is no entry, I'm just on a template with a registration form on it. How do I output the dropdown options?


texts: Disabling individual sites on a Craft 3 multisite

texts:
Is there a way to disable non-primary sites on a multisite setup so that users are redirected to a 503 template?

I can't see any configurations that allow me to to this. All sites are either disabled or live.


texts:
The Feed Me documentation says

  "Provide the URL for your feed. This can be an absolute URL, relative (to the web root) and make use of any aliases"

That's pretty confusing language. I thought I could create a folder in public called "feeds" that would contain my .csv. For example, /public/feeds/feed.csv. So I entered feeds/feed.csv in the Feed URL field. That didn't work. I was confused because "relative (to the web root)" doesn't really mean a relative path.

Is it true that the Feed URL needs to be an absolute URL in the form of http(s)://domain.tld/feed/feed.csv? I understand that aliases can be used and you wouldn't necessarily need to enter the domain in this field, but in general is this the required format?


texts: Default Formatting Templates don't add "required" to input tag

texts:
I've just started using FreeForm and so far it's fantastic after moving away from another solution.
One thing I'm struggling with is how the "required" option works for fields. I would have expected it to add a required attribute to the input field, but all it does is add a required class to the label of that input.
I know I can add the required attribute myself and that's what I'm doing now but wanted to check I'm not doing something wrong? The formatting template I'm using is Bootstrap 4 and I can see it only uses required in relation to labels.


texts: Possible to filter an entry based on property?

texts:
Trying to pull in a limit of 2 events that are upcoming (so the event's eventDate should be newer than today). I currently have this:

{% set entries = craft.entries.section('events').order('eventDate asc') %}
{% set today = now|date('Y-m-d') %}

{% for event in entries %}
  {% if today <= event.eventDate %}
    <!-- markup here -->
  {% endif %}
{% endfor %}

However, this returns all events that are upcoming. I would like to only limit it to 2. The problem when I put the .limit(2) on my for loop is that it chooses the first two (and those happen to be older events). Do I need to do another loop within the if statement and add .limit(2) to that or is there a better way?

Thanks!


texts: Is it possible to populate admin form with data supplied by an external API?

texts:
I've been tasked with reviewing Craft as a potential solution for the company I work for and one of the requirements is that we need to be able to provide data from a external API in the page creating/editing interface in the backend.

Is this possible and if so how?


texts: When a locale is first created, it seems it receives all of the default locales content. Is it possible to have this happen for a specific field after the fact? I have a large matrix (with subtle locale differences) I'm hoping to not re-enter a second time ;)


texts:
Does Craft CMS have an API that third-party webapps can access?

Maybe a REST API which you can log in to and send GET, PUT, POST, DELETE commands to, from a third-party app?

It seems like it should have an API, by the statement of the creator:

  A key part of the architecture is our service layer. All of the
  business logic in Craft happens in service classes, which provide APIs
  that anything else in the system (including other services) can talk
  to.
   - http://www.thenerdary.net/post/48123188844/interview-with-brandon-kelly-creator-of-craft

But then again, some other people who have tried integrating towards Craft CMS says it doesn't:

  I ran into some trouble with the API. Shit, Craft doesn’t freakin’
  have one! I assumed it would, oops.. So I researched how to do it. I
  knew I could probably fake it and output json using template tags but
  no-one wants to do that. I looked at some API controllers but non of
  them worked very well. In the end I found a nice plugin called JSON
  Expand that converts entries from Twig into JSON. -
  http://abandon.ie/notebook/using-angularjs-with-craft-cms

I'm confused. If it has an API, what kind is it, and what protocol does it use? REST? SOAP? RPC? Something else?

And where is it documented? A simple 'hello world' or 'transmit som data into Craft CMS' example would be really helpful.


texts: Getting the last X number of pages in pagination

texts:
I am working on a pagination for some articles. I am using a for loop to get the 3 pages after and before the current page .getPrevUrls(3) and .getNextUrls(3)
So far it looks like this, where 35 is the last page and the black one is the current page.

The problem I'm trying to fix is when the current page is within the 3 page range .getNextUrls(3) of the last page.

How can I create an if statement to hide the dots and the last page if my current page is within 3 pages of the last one so that I don't get the last page number twice.?

Here's my current code

{% paginate craft.entries.section('mySection').limit(10) as pageInfo, pageEntries %}

{% for page, url in pageInfo.getPrevUrls(3) %}
  {{ page }}
{% endfor %}

{{ pageInfo.currentPage }}

{% for page, url in pageInfo.getNextUrls(3) %}
  {{ page }}
{% endfor %}

...

{{pageInfo.totalPages}}

Thanks in advance.


texts:
I've seen how you can remove html tags with twig in other posts here so I am using:

{{ product.intro|striptags('
')|raw }}

To remove the
 tag that redactor adds automatically. However for some reason it is not removing it. Anyone have any ideas. Have I missed something glaringly obvious?

Cheers


texts: What changes are needed if I change directory structure?

texts:
I can't have a mess of craft stuff at the root of my server so I try to use the following directory structure, with craft files and folders gathered in a craft directory :

craft
-- config
-- modules
-- storage
-- vendor
-- etc...
www
-- index.php
-- web.config
-- etc.

This structure gives me a 500 error.
I assume I can change a path variable somewhere, but I just can't find where. Any ideas ?


texts:
I have 2 plugins I created that store similar data:

Plugin 1: id, name, panel_id, price

Plugin 2: id, name, test_id, price

I want to attach my plugin data to an entry, and I need to make sure they can only select one Panel or Test. I want to know if there is a way to add them as a source for Entries as a new field. Or can I create a similar custom fieldtype to be used for both plugins and have that kind of validation?

I'm using Craft V2.6


texts: Sprout Email: Notification unable to create "Craft\WebApp.userGroups

texts:
just bought the Sprout Business Collection since i've been playing around with Sprout forms during the beta periode and now needed to implement email features.

One problem i'm running into. After installation i tried to create a new notification. First screen no problem. Enter name, template, field layout. After saving the ADD NOTIFICATION ENTRY button appears. But clicking that gives me the following error (translated from dutch so possibly not exact).

The attribute "Craft\WebApp.userGroups" is not defined.

Below you'll find a link to the craft.log since it contained more detailed information about the error.

https://www.dropbox.com/s/svebqtfgppnhvug/sprout_email_error_craft.log?dl=0

Hope someone can point me in the right direction.

Bas


texts:
I have a Countries dropdown menu for signing up that i didn't have before. It used to just be a text field where they can input their own country. It works on the front end sign up form properly, but for the users who don't have the country selected from the new dropdown need to select a country. I have the dropdown on a front end profile form, however when the user "updates" their profile if they don't choose the country it just resets.

For example, I signed in and my country is set to USA and i go to my account to update my password, it resets what's selected on the countries dropdown.

I would like to show the County dropdown for the users who hasn't selected their countries and if the user already selected their country to just show the value they selected.

The code below is the code for the select.

{% set dropdownField = craft.fields.getFieldbyHandle('country') %}
<label for="country">Country</label>
<select class="form-control" id="country" name="fields[country]">
    {% for option in dropdownField.settings.options %}
        <option value="{{ option.value }}" >{{ option.label }}</option>
    {% endfor %}
</select>


texts: What is the checkbox for when editing Matrix fields?

texts: Referring to the screenshot below; I've just added a Matrix field to a new site, and I'm not sure what the checkboxes are for? The Matrix field just has two plain text fields. As far as I can tell, checking the box does nothing, and saving the entry unticks it. Might be a bit confusing for the client; any ideas?


texts: entry is available without query when templates are set in the CP, is this an acceptable method?

texts:
Craft Pro 3.4.20

New to craft development. I was following the documentation and calling my entries via the suggested method as outlined https://docs.craftcms.com/v3/dev/element-queries/entry-queries.html#example.

However I have found that I can access any fields via entry.<fieldName> within my twig templates without setting the entry query, so long as that template has been assigned to that section.

For example, my homepage has a template set in the cp, and I can access all its field entries without any query within the twig template, I just call entry.title like anything else and it works.

My question is this—is this an acceptable method? Are there any performance issues with this?


texts:
I save image files from within my plugin through assets->insertFileByLocalPath().
Unfortunately, i can't give the image title as paramter to the method.

What is the easiest way to change the image title after insert, espacially considering different languages?

UPDATE

Ok, i found a solution (moved to the answer), but how do i save values for different languages?


texts: P&T Contact Form plugin: How to display error messages in other languages via Ajax

texts:
The validations error message get displayed in main language instead of being translated, you can try here (contact form at bottom):
http://lequartiergeneral.be/en/

The form is being displayed and get response via Ajax.

How to display them correctly in each language?

Thanks


texts: Retrieve Asset Filename from an entry, inside a matrix field

texts:
I must simply be blanking this morning, but for whatever reason, this has me stumped... I have a Structure section I use for the different sections of my site which sets titles for each page, etc.

Additionally, I have another section called "Widgets". These widgets are stored in the template folder and each widget is linked up to a dedicated entry in an Asset field. Finally, each Structure entry (take the home page for example) has a Matrix field. This allows me to rapidly add new pages from templates I have already built. Unfortunately this time around I am having trouble pulling the filename for the widgets, though I seem to be able to grab the asset IDs. Following is the code. Thank you in advance for the help; I am sure it is simple but I've been banging my head against my desk for a little too long now...

                {% block contentPrimary %}
                {% switch entry.type %}
                    {% case "mainContentLeft" %}
                        {% for block in entry.contentPrimary %}
                            {% switch block.type %}
                                {% case "text" %}
                                    {{ block.text }}
                                {% case "widget" %}
                                    {% if block.widgetPrimary|length and block.entry[0].widgets|length %}
                                        {{ block.widgetPrimary[0].widgets[0].filename }}
                                    {% endif %}
                            {% endswitch %}
                        {% endfor %}
                    {% case "mainContentRight" %}
                        Main Content Right
                    {% case "singleColumn" %}
                        Single Column
                {% endswitch %}
            {% endblock contentPrimary %}

After trying a few different things, I've seen a couple different errors, but the error I see at present states:

  Craft\MatrixBlockModel and its behaviors do not have a method or closure named "widgetPrimary".

Thank you again, in advance!


texts:
I'm building a website for a restaurant and I wanted to make the back-end as easy to use as possible. So I thought of a system like this.

Allergens - Contains name and icon
Ingredients - Contains allergens
Recipes - Contains ingredients and text about the dish
Menu - Contains recipes

So the concept is that they can just add as many recipes as they want. And just drag and drop/select the ingredients. And never ever worry about which allergens is present.

Thing is, I'm not sure what's the best way of achieving this. Would allergens, ingredients and recipes need to be separate entries in separate channels? Since I want to be able to attach an icon to an allergen, I guess that needs to be a channel?


texts: Showing/Hiding children of a Structure based on categories

texts:
I'm a newbie, so please excuse this if its a super simple question. I have a structure set up like so:

• Parent Section 1
  - Child 1A (category: pro-users)
  - Child 1B (category: pro-users)
  - Child 1c

• Parent Section 2
  - Child 2A
  - Child 2B

I am wanting to output a navigation/landing page with the children viewable or not based on what category they are set to. So for example, on a specific page, I just want items with category "pro-users" (two entries specified above) to show up, with their parent title, and not any of the others. I also don't want the parent titles of sections that don't contain matching elements (Parent Section 2) to show. So, in this example where I just want the children with category "power-users" to show up, it would only show me:

PARENT SECTION 1
   Child 1A
   Child 1B

And nothing else. Please ask for more specifics if this doesn't make sense. I just can't figure out how to a) only show the children that are matching the categories I specify (in this case "pro-users") and to also not show the subsequent parent title if there are no matching children (as is the case for Parent Section 2).

Thanks in advance for your help, I really really appreciate it!


texts:
I have a Craft 3 site. For some reason the before filter isn't working when pulling entries from a channel, but after does. This is not a data issue.

{% set start = "2 months ago"|date() %}
{% set end = "next week"|date() %}

{% set listings = craft.entries({
    section: "tvListings",
    limit: null,
    with: "channel",
    before: end
}).all() %}

For clarity the dates result in:

Start: Feb 4, 2018
End: Apr 9, 2018

And one of the example entries is definitely in that date range (April 2nd).

If I ditch the "before" and go "after: start" it does work. If I try to say "give me all entries before Apr 9, 2018", the "Thunderbirds are go" (or any other listings) do not show.

Surely I'm not doing something super stupid right?

I'm running Craft 3.0.2.

Thanks.

EDIT: I've started pulling apart the CMS to debug. EntryQuery->beforePrepare() builds the query that filters by date. Although the props before and after are set, once they're passed through Db::parseDateParam() it mutilates the dates and somehow comes out with "2017-12-31 11:00:00" for both - so no bloody wonder it's not working. If this is a date format thing for those props I'll update the answer.


texts: Where to enter URL for Live Preview in Craft 3?

texts:
Pretty sure I've seen where you can enter the URL for an entry type so Craft knows what page to display during live preview. But I can't find that now. I'm looking in the entry types, and I can't think of anywhere else it would be.

Am I going crazy? Where is that feature?

I see a field in the section settings called "Preview Targets". It says:

  Additional locations that should be available for previewing entries
  in this section.

If this is it, the term "Additional" is a bit misleading.


texts: My provider upgraded to PHP7 and deleted all files outside of the public folder, where I had the system files (...). Is it possible to find out from the database which version (of Craft 2) I need to restore the website?


texts: Set Recipient in Sprout Email Notification

texts:
Okay, so similar issue to this question (Sprout email notifications - setting the recipient?). I must be doing something stupid here because. Trying to set the recipient from an entry form, with a hidden field:

<input type="hidden" name="recipient" value="{{ 'name@address.co.uk'|hash }}">

Then in the control panel, the Recipients field has {recipient}. That should work right, but I don't receive the email. If I manually set an email address in the control panel Recipients field, it works fine.


texts:
I was wondering if Craft supported having multiple stocks for one product.
Something that Magento for example would call stock source.
I'm looking at having one set of stock associated to trade customers, and one for regular customers.
I could potentially look at them being different products and have different stock for it, but that would mean all the products would be duplicated, which is not great.
Thanks for your time


texts: Incorrect user-level lock name - Local Vagrant Environment - Craft 3

texts:
When creating a new field, I received a Database Exception error -

  SQLSTATE[42000]: Syntax error or access violation: 3057 Incorrect user-level lock name '/var/www/storage/runtime/compiled_classes/ElementQueryBehavior.php'.

Loading an older database backup did not resolve the error, and neither did checking out an older branch. I am unable to access the panel or the site itself.

Installed Plugins

SEOmatic
Element API
SuperTable

Any assistance would be greatly appreciated

Edit: After dropping/creating the database multiple times, I am now getting this error instead

Edit 2: Here is a link to the full stack trace, which was posted to imgur due to the length

https://imgur.com/a/ADSvGCj


texts: Can I use Twig in a FreeForm html field?

texts: Is it possible to use the {{ siteUrl }} Variable in a html Field in freeform? I tried it and it threw an error that the variable was not valid. Is it possible to use twig in a html field?


texts: Custom Module: new element type index page access

texts:
Hello I've created a new element type in a module (a web app within Craft) that I'm developing.
I have initially created my models to be craft\db\ActiveRecord and save directly to their tables, but that is not the "craft" way.
I decided to extend from craft\base\Element and do the needful in order to leverage elementindex.html (search, sort, filter), but going to /admin/custom/index gives a "404 Not Found". Do I need to create my own CustomController.php ?
I did the configuration needed in my Module class, as well as creating the Custom.php and CustomQuery.php according to the documentation here
   // CP Routes
    Event::on(
        UrlManager::class,
        UrlManager::EVENT_REGISTER_CP_URL_RULES,
        function (RegisterUrlRulesEvent $event) {
            $event->rules['custom'] = '/app-module/custom/index';
        }
    );

    // CP Nav Items
    Event::on(
        Cp::class,
        Cp::EVENT_REGISTER_CP_NAV_ITEMS,
        function (RegisterCpNavItemsEvent $event) {
            $event->navItems[] = [
                'url' => 'custom',
                'label' => 'Custom',
                'icon' => 'share',
            ];
        }
    );

    // Custom Element Types
    Event::on(Elements::class,
        Elements::EVENT_REGISTER_ELEMENT_TYPES,
        function(RegisterComponentTypesEvent $event) {
            $event->types[] = Custom::class;
        }
    );


texts: I am trying to find a field type that lets me select one or more fields. I want to use this on a category to let the user select which fields should be used a faceted filters on the product listing.


texts:
I have a people channel that historically has used another field to decide if they're a "featured" person or not.

The field set for "featured" people has now diverged from what a normal person has, so I'm wanting to create a new entry type in the people channel (featuredPeople) and programatically shift these people to the new entry type.

The field set is additive to the old one, so I'm hoping due to there being no field/structural changes this isn't too hard?

I've got the bones of a script together to do this, but I'm struggling to find any info on how to actually change the entry type on the entry.

# Get all people
$peopleCrit = Entry::find();
$peopleCrit->section = "people";
$people = $peopleCrit->all() ?? [];

foreach ($people as $person) {

    # If this was a "featured" person, shift to new featuredPeople entry type.
    if (historical "is featured" check) {

        # Move to featuredPeople entry type
        ???

    }

}

Any help would be greatly appreciated.


texts: How does craft deal with Plugin databases when updating plugin versions?

texts:
Quick scenario.

I build a plugin with a database. Few months down the line I want to upgrade this plugin which will alter the plugin DB. If installing an update to a plugin how does craft deal with not over writing the existing database data? I know in EE you set up separate install and update functions but I can't find anything in the documentation in craft regarding this and the plugins I've pulled apart don't seem to include anything to deal with updates?

Any advice or pointers to some good documentation on this would be appreciated.

Cheers


texts: How can I replace a newline (in a plain text field) with a comma?

texts:
I need to convert a new line in a plain multiline text field in Craft into a comma.
My text looks like:
1 Infinite Loop
Cupertino, CA

and I want to convert it to: 1 Infinite Loop, Cupertino, CA
I tried doing {{ text|nl2br|replace({ '<br>', ', ' })|raw }} but that didn't work.


texts:
I see Craft does support regex in replace search. But there is no info on using regex groups, ie string | replace('/this is a (string)/', 'This is another $1').

Is this feature implemented? If so - how?


texts:
I'm trying to use flickity to create a draggable gallery on a single entry template, but I'm having issues with the output.

In the backend it looks like this. A field using multiple assets.

Without flickity I'd put them out like this which lists each image from the field.

{% if entry.gallery|length %}
    {% for image in entry.gallery.all() %}

    {% endfor %}
  {% endif %}

For flickity to work it needs to look like this

I have trouble combining these two things successfully. The goal is to dynamically output each image from the assets into a carousel-cell div. Does anyone have pointers how to do so? Thank you!


texts: How do I set the value of a custom entries order field from a plugin?

texts:
I'm trying to set the value of a custom field on an order when saving an entry. I found an example of how to do this for a simple text field, but the field I'm trying to set is an entries field, not just a text field. I've attempted to set the value using the following code in my entries.saveEntry event. I'm assuming I'm doing this wrong since this is an entries field, not a simple text field, but I don't know the syntax for setting content on an entries field.

$cart = craft()->commerce_cart->getCart();
$cart->setContentFromPost(['entriesFieldHandle' => $entry->id]);


texts: Importing voucher codes from Espresso Store to Verbb Gift Vouchers

texts:
I'm doing some messing with MySQL to import some Espresso Store voucher codes into a Craft Commerce site as Verbb Gift Vouchers.

I've got a long query that basically reads the data from the EE table(s) and creates rows in giftvoucher_codes table.
It also creates a corresponding row in the elements and elements_sites tables.

Everything seems to join up and get created but I still don't see the imported vouchers in the Gift Vouchers area of Craft's control panel.

I've tried clearing caches with no luck.

What am I missing? What else needs to be updated to get them to show up?


texts:
First of all, the last time I did php was 10 years ago in school, so I'm basically a noob :D
I have two channels, let's say shops and products. Shops contains a matrix field composed of a product entry field and a price field to make an ultra simple pivot table like behavior (like proposed in a previous question), so I can have shops linked to products with a specific price per shop.
I made a controller to have a custom api endpoint with a basket parameter, where multiple users can select products in a vue frontend.
The goal is to calculate per shop the price of all products for all users and sort it.
It works the way I did it, but there is a lot of room for optimisation.
Here is my code, keep in mind that the business case here is fake to simplify the code;
public function actionResults($basket): String
{

    $shops = Entry::find()->section('shops')->all();
    $profile = json_decode($basket);
    $results = [];

    foreach ($shops as $shop)
    {
        // basket contains users that contains the selected products
        $price = $this->calculatePrice($shop, $basket->users);
        // fill $results array with total price and other fields to be sent back
    }

    usort($results, function($a, $b) {
        if ($a->totalPrice == $b->totalPrice)
        {
            return 0;
        }
        else if ($a->totalPrice > $b->totalPrice)
        {
            return -1;
        }
        else {
            return 1;
        }
    });

    return Json::encode($results);
}

private function calculatePrice($shop, $users)
{
    $totalPrice = 0;

    foreach ($users as $user){
        foreach ($user->products as $userProduct){
            $product = NULL;
            // search a corresponding matrix row
            foreach ($shop->products->all() as $shopProduct) {
                // have to get the entry to access the slug and other fields (I work with slugs
                in the front)
                $shopProductEntry = $shopProduct->product->one();
                if ($shopProductEntry->slug == $userProduct->slug) {
                    $product = $shopProduct;
                    $product->shopProduct = $shopProductEntry;
                    break;
                }
            }

            if ($procut)
            {
                 $totalPrice += $product->price;
            }
        }
    }

    return $totalPrice;
}

What do you think about this ? Kind of crap right ? I have like 40 shops and 10 products for few users and it takes one to two seconds to get a response with 0 load on the server since the website is not public yet.
Thanks for reading me,
Antoine


texts: Removing the LivePreview and Share Buttons?

texts:
Is there a way to deactivate this functionality? We dont want our clients to use it just yet.

I could delete them with my Module's js, but it is triggered after the site is build and the "popping" away of the buttons is not really pretty.


texts: Additions to extraAllowedFileExtensions not showing up in the checkbox list

texts: When adding 'extraAllowedFileExtensions' => 'css' to /craft/config/general.php it doesn't show up in the list below Restrict allowed file types?. Am I missing something? Is it just not "restrictable" to an added filetype?


texts:
Craft seems to create asset files and folders with permissions 775 and 664. My host has restrictions in place to not serve folders/files with these permissions.

Where can I change this?


texts: How can I add Google MarkerClusterer library to Smart Map?

texts: I started to work with Craft CMS a couple month ago, I have a client that wants to have a clustered map, I went over Smart Map documentation but I couldn't find anything about on how to add Google MarkerClusterer library.


texts: Override a portion of an extends template

texts:
I'll give you my specific use-case here and then see if it might also be more generally applicable in other scenarios: We have a new Craft PRO site running happily, and in our /templates/ we have a _layout.html file that every other template then uses and extends. That _layout includes common <head> content, main navigation, footers, etc. Nothing surprising.

But on one sub-page we are displaying Google Maps using various calls to Google's Mapping API. One requirement for the Google Maps, however, is that the  tag trigger Google's JS when the page loads and unloads:

  <body onload="load()" onunload="GUnload()">

Currently that <body> tag is in _layout.html so that it can be consumed by the mapping page. But for all other pages it's superfluous, and throws a minor error in the JS console when you inspect the page.

My question is: Is there a way to write a page template so that it _extends another base template but also overwrites just a small portion of it? For instance, could I remove the onload / onunload values from _layout.html and somehow have my mapping page INSERT them back into the <body> tag for just that page?

Or is there a more elegant way to have my mapping page draw upon _layout.html but keep the onload / onunload calls isolated to just that page? Or maybe have _layout.html look for what page is calling it and then return one <body> tag for the mapping and another <body> tag for all other pages?

The Google Maps API makes it pretty clear that this JS function be called at the <body> level, and not just on a <div>.


texts: Query on Super Table field's entry field

texts:
I have a section with a Super Table field that has an entry field.
Now I want to find the entries that have a relation to that entry.

I found this answer here. This but I can not get it to work with the entry field type.

query on Super Table field's date field

Thank you for your help

 $events = Entry::find()
        ->section('foo')
        ->leftJoin('supertableblocks', 'supertableblocks.ownerId = entries.id')
        ->leftJoin('stc_foo', 'stc_foo.elementId = supertableblocks.id')
        ->groupBy('supertableblocks.ownerId')
        ->where(I don't know what to do here with the entry field)
        ->all();


texts:
I've hooked up search and if I run a query on 'Second Presbyterian' for example, I get the expected return.

However, if I search for 'Second Pres' I get nothing coming back as a partial match.

Why would this be?


texts: Neo: children won't display or I get all() deprecation notice

texts:
I have a Neo field set up like so:

-Row
--Column
-Body

Columns can also contain body.

With this:

{% set modules = entry.pageBuilder
        .with([
            'moduleBody',
            'moduleRow',
            'moduleColumn',
        ])
        .level(1)
        .all()
%}

{% for module in modules %}
    {% if module.type != 'moduleColumn' %}
        {% include '_partials/page-builder/_' ~ module.type %}
    {% endif %}
{% endfor %}

{% set moduleArray = [] %}

{# Remove duplicate module types from array #}
{% for moduleType in modules %}
    {% if moduleType.type not in moduleArray %}
        {% set moduleArray = moduleArray|merge([moduleType.type]) %}
    {% endif %}
{% endfor %}

_moduleBody.twig

  {% if module.heading %}
{{ module.heading }}
{% endif %}
  {{ module.body }}

I get body blocks output fine if they're not nested in a row/column.

_moduleRow.twig

    {% set columns = module.children %}
    {% for column in columns %}

    {% for item in column.children %}
        {% include '_partials/page-builder/_' ~ item.type %}
    {% endfor %}

    {% endfor %}

With the above, I get an error:

  Looping through element queries directly has been deprecated. Use the all() function to fetch the query results before looping over them.

If I change set columns = module.children to set columns = module.children.all() I get the same thing. If I change it to

{% set columns = module.children
        .with(['moduleColumn'])
        .level(1)
        .all()
%}

there's no error, but no output either (other than the HTML for the row which is outside the code for the column contents).

What do I need to do to get the columns to output?

I guess I'm also going to have a problem with for item in column.children because inside moduleBody it's calling module.variable not item.variable but if the outer loop uses module, I can't use it for the inner loop too.


texts: Upgrading from v2 to v3 results in internal server errors

texts:
I'm trying to upgrade a v2 site to v3 and have done the following:

Verified that my server meets the v3 requirements using the Craft Server Check.
Followed steps 1-3 on this page.
Followed the directions on this page.

When I go to my control panel's URL, I get the following error: "An internal server error occurred." There's nothing in my server's "error.log" file.

As a test, I even created a fresh install of v2 on a new server instance, imported my site's data, and tried upgrading that, and I still get the server error.

FWIW, I'm running Apache 2.4, Ubuntu 16.04, PHP 7.0.30, and MySQL v5.7.22.


texts: Search question: dot (period) and partials

texts:
We have a job inventory where the jobs are being saved as entries.
When searching against jobs by keyword we search against two fields: the title and a job description field.

However we are experiencing some unusual results when using the search parameter to search against the term ".net". For example:

{% set results = craft.entries()
.search('title:".net" OR description:".net"')
.all() %}

Is there a way to use search() to specifically only return entries where the title or description contains .net as at present it is returning partial matches (eg jobs where the title or description features 'networking').

The description field is a redactor/rich text field. Would this affect it?


texts: Preventing certain queue jobs from being created, or selectively deleting jobs from queue

texts:
Does anyone know how I'd go about either preventing certain jobs from being added to the queue, or, if that isn't possible, deleting jobs given a certain criteria?
The context is that I have a site where lots of users are added every hour, along with lots of Verbb Wishlist items, each of which trigger a search index update job which definitely aren't needed, and if there are too many it can overwhelm the server resources (this is despite my jobs being processed async via a worker).
I want to be able to prevent these from being created, or periodically wipe the queue table of these jobs before they're processed.
I had hoped to be able to run a simple SQL query to delete the non-needed jobs, but since the details of the job is serialised in a blob I can't simply query the jobs I need.


texts: Using craft.entries to return entries with empty entries field

texts:
I'm new to all this. Is it possible to use craft.entries to return all entries with an empty entries field? Something like:

{% set drinksWithNoIngredients = craft.entries.section("drinks").ingredients(":empty:") %}
{% for drink in drinksWithNoIngredients %}

Do something with {{ drink.title }}...

where ingredients is an entries field handle. This doesn't seem to work on entries fields, though. Or maybe I could do some kind of relatedTo magic, where the targetElement is some kind of special null value?

An alternative seems to be this:

{% set drinksWithNoIngredients = craft.entries.section("drinks") %}
{% for drink in drinksWithNoIngredients %}
    {% if not drink.ingredients.total() %}

Do something with {{ drink.title }}...

But doing it that way calls .total() on every drink. Is that going to cause performance problems if I have a lot of drinks?


texts:
I have a set of parameters that need to be checked before outputting an entry in a particular section of a website. The code for that looks somewhat like this:

{% for slide in craft.entries.section('events').featured('1').order('dateTime asc').limit(2) if (slide.dateTime|date_modify("tomorrow 5am")|date("c")) >= now|date("c") %}

The problem is that it obviously is looping through all entries, even those that do not match my conditional based on the date. Is there a way to prevent the loop through entries that don't match that condition to prevent bloat as there will eventually be thousands of entries that it would be looped through that do not end up being output due to the conditional.


texts: Is it possible to duplicate a entry as a draft entry?

texts: I need a function to duplicate an (published) entry as a draft entry. Now if I duplicate an entry it will immediately publics that entry an that fires some plugin events (sends mails) I didn't want.


texts:
I've successfully joined a table to the elements table, however I can't can't seem to add a property so I can use it?

Getting the error Setting unknown property when trying to join table

Entry::find()
    ->addSelect(['craft_event_instances.instance_datetime'])
    ->leftJoin('craft_event_instances', '`craft_event_instances`.`entryId` = `elements`.`id`')

Thanks


texts:
What is the best way to implement a typeahead search in Craft. I looked at using ElementAPI to do something similar at this example but it doesn't seem to allow me to wildcard search

https://craftcms.com/docs/templating/search-form

Here's an example of the endpoints I have configured:

I have one entry with a title of "test" when I call the API doing

When I call /entries/te its returns 0 results. When I call /entries/test it returns 1 result.

<?php

namespace Craft;
return [
    'endpoints' => [

        'entries/<search:\w+>' => function($search) {
            return [
                'elementType' => 'Entry',
                'criteria' => ['title' => $search]
            ];
        }

    ]
];


texts: Is it possible to get all elements in a Matrix field by type or field name

texts:
I found a way to do something like this

 {% set allBlocks =  craft.entries.matrixes %}

Which seems to return all the matrix blocks.. or at least I think it is?

But if try to filter down like:

  {% set allBlocks =  craft.entries.matrixes.type('document') %}

I get nothing.

Any ideas how to get all the Matrix blocks by type or better still all the Matrix blocks in a particular field?

Would i need to setup a plugin for this?


texts: Craft queue keeps sticking despite 1GB memory allocation

texts:
I keep seeing a Craft 3 site with queue sticking and clearing the cache doesn't clear it.

I have been thru plugins fixed some errors and now it all comes down to same issues:

  PHP Fatal error:  Uncaught PDOException: SQLSTATE[HY000]

The specifics are:

    thrown in /home/mydomain/vendor/yiisoft/yii2/web/Response.php on line 366
[30-Oct-2019 19:21:47 UTC] PHP Fatal error:  Allowed memory size of 1610612736 bytes exhausted (tried to allocate 413696 bytes) in /home/mydomain/vendor/
yiisoft/yii2/db/Command.php on line 1290
[30-Oct-2019 19:21:47 UTC] PHP Fatal error:  Uncaught PDOException: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered   queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute. in /home/mydomain/vendor/yiisoft/yii2/db/Command.php:1290
Stack trace:
#0 /home/mydomain/vendor/yiisoft/yii2/db/Command.php(1290): PDOStatement->execute()
#1 /home/mydomain/vendor/yiisoft/yii2/db/Command.php(1158): yii\db\Command->internalExecute('SELECT *\nFROM `...')
#2 /home/mydomain/vendor/yiisoft/yii2/db/Command.php(399): yii\db\Command->queryInternal('fetchAll', NULL)
#3 /home/mydomain/vendor/yiisoft/yii2/db/Query.php(237): yii\db\Command->queryAll()
#4 /home/mydomain/vendor/yiisoft/yii2/db/ActiveQuery.php(133): yii\db\Query->all(NULL)
#5 /home/mydomain/vendor/craftcms/cms/src/services/Categories.php(125): yii\db\ActiveQuery->all()
#6 /home/mydomain/vendor/craftcms/cms/src/service in /home/mydomain/vendor/craftcms/cms/src/templates/_layouts/base.html on line 37

I am not sure how to resolve this. Any ideas?


texts: Craft 3.x Menu : Entry URLs are set by the entry

texts:
I can't change the URL? How can I use a custom URL?
Here is the link to the image:
https://ibb.co/bz9BYnL


texts: Frontend Form - Checkboxes cannot "all" be unchecked

texts:
I have a frontend entry form with some checkboxes that is not behaving correctly.

If you uncheck all options and save, nothing changes (this is bad). However if you uncheck one item and check another item it saves correctly.

Additionally in the Craft CP if you uncheck all items it saves correctly so it clearly works there.

relevant template code:

{% for volunteer in craft.entries.section('careers').search('positionType:volunteerPosition') %}
  <label class="d-block">
        <input type="checkbox" class="form-check-input" name="fields[volunteerPositions][]" class="form-check-input" value="{{volunteer.id}}" {% if volunteer.id in selectedEntries %}checked{% endif %}>&nbsp;&nbsp;{{volunteer.title}}  (created by {{volunteer.author }})
      </label>
{% endfor %}

Please advise.


texts:
when trying to insert a guest entry i get the following response from craft:
You don’t have the proper credentials to access this page.

What can i do to avoid this and still insert the entry to craft? It needs to be an anonymous user.

Thanks in advance,


texts:
We want to use Memcached but are struggling to find Craft 3 specific config examples and documentation.

The docs mention several things that seem to lead to dead-ends:

App config docs here show how to configure the component in config/app.php. But in terms of 'enabling' that component, the docs here say that cacheMethod might need to be used, presumably in config/general.php, but the link to cacheMethod goes nowhere. Also here in the changes in v3 article, is says that cacheMethod has "been removed entirely" and instead point readers to Configuration → Data Caching Config which is a missing section.

In terms of the server setup, Memcached is enabled and we have 2 nodes/hosts available.

Very confused, please help.


texts:
I've set up some dynamic routes to work with categories, so for example the route is set up to load a specific template if the work category appears in the URI, thus:

news-events/image-gallery/category/[slug]

However, if I test with the following URL I get a 404 error:

/news-events/image-gallery/category/drama

Other dynamic routes are working fine. Thoughts on how to debug/resolve appreciated.

Cole


texts:
I made a modal for login at homepage and put {%requireLogin%} tag in "User Profile" page.
My general.php file looks like below:

'dev' => [
        // Base site URL
        'siteUrl' => null,

        // Dev Mode (see https://craftcms.com/support/dev-mode)
        'devMode' => true,
        'loginPath' => '/',
    ],

I hope to prevent users to go to "User Profile" page without login and redirect them to homepage. But the issue is when I login on the homepage, the browser gives an error redirected you too many times.

Any idea how to do that please? Many thanks!!


texts:
I’m trying to implement different hyperlink styles within a rich-text field by adding formatting options via a Redactor config file.

"formattingAdd": [
  {
    "title": "Button",
    "tag": "a",
    "class": "button"
  }
]

This isn’t working as expected though. The above, for example, adds a <span> around or within the <a> tag, occasionally removing the <a> tag altogether.

Is there a way to add classes to hyperlinks within a rich-text field?

Note: This rich-text field is already within a containing Matrix field, so that’s not an option.


texts:
When I output {{ craft.locale }} in my template, I get the current locale’s ID (e.g. “en”) rather than its name (e.g. “English”).

How do I get the locale’s name?


texts: Craft requires MySQL 5.1, got 5.1.73 and an error

texts:
I just moved my website on my production environment, and when I try to login, I get the "MySQL 5.1.0 is required..."

So I did a phpinfo() and got Client API version  5.1.73 for MySQL.

What did I do wrong ?
Thanks a lot !


texts: FreeForm and Vue - Hidden Forms in Modal - Manually refresh the Craft CRSF token and Freeform JS Honeypot field

texts:
Anyone using FreeForm and Vue together?
I have a form that is hidden away in a modal (that is then shown using Vue) via a click of a button. Vue is only used to hide the form and show the form. the form code is all in the page/template.

However, I am having issues with the form being marked as spam and the following error on FreeForm:

  Form honeypot is invalid

FreeForm support suggested that as it is Vue is used - I need to manually refresh the Craft CRSF token and Freeform JS Honeypot field.

I have no idea how to do this? Or where to start. If anyone has done similar or can help point me in the right direction?


texts: How to saveElement in EVENT_AFTER_SAVE_ELEMENT without infinite loop

texts:
I am trying to update an entry's title in a Craft 3 module after an entry is saved. I cannot use EVENT_BEFORE_SAVE_ELEMENT because the title gets updated after this. If I use EVENT_AFTER_SAVE_ELEMENT to update the title and then do saveElement the event gets called again and I get into an infinite loop.

Event::on(Elements::class, Elements::EVENT_AFTER_SAVE_ELEMENT, function(Event $event) {
    if ($event->element instanceof \craft\elements\Entry) {
        if ($element->section->id == 1 && $element->typeId == 1) {
            $element = $event->element;
            $newTitle = "new title"; // logic goes here
            $element->title = $newTitle;
            Craft::$app->elements->saveElement($element); // causes loop
        }
    }
});

Is there a way to do this? Thanks.


texts:
Front-end developer here playing with fire. I'm developing a site that as a specific UI element that I want to reuse throughout the site. Specifically it's a button that has different "configuration" options. You can change the colors, add an icon, etc. It's currently all controlled via CSS classes. You can think of the element as something akin to a Button within Twitter Bootstrap.

I'd like to build a custom fieldtype so that users within the CMS can add in these UI elements throughout the site and change the options such as color, size, name, link, etc. I'd like to be able to place this type inside of Matrix blocks. So doing this within an existing Matrix isn't really feasible.

I'm kind of thinking of it as a mini-matrix or an advanced table element. If someone can point me in the right direction that'd be great. Thanks!

The concept I'm currently struggling with is how to create the fieldtype and have it save the data from the different form elements within my fieldtype to the database.


texts:
I'm used to writing Twig 1 syntax, and since switching to Craft 3 (which uses Twig 2) I keep getting lots of deprecation errors in the control panel.

Is there any reference material that provides the Twig syntax I should be using instead for Craft 3 sites?


texts: Problem with getHeadHtml(), getFootHtml() and caching

texts:
I have two problems when it comes to working with getHeadHtml() and getFootHtml().

But first things first. Here's my setup:

This is my stripped down _main.twig layout file:

<!DOCTYPE html>

    {{ getHeadHtml() }}
    <link rel="stylesheet" media="all" href="/assets/scss/styles.css" />

    {% block content %}{% endblock %}

    {{ getFootHtml() }}

This is my stripped down _entry.twig file:

{% extends "_layouts/_main" %}

{% block content %}
    {% for block in entry.cf_content_matrix %}
        {#
            Include all blocks
        #}
        {% include "_blocks/_block_" ~ block.type ignore missing %}
    {% endfor %}
{% endblock %}

This is the Matrix block that is causing the problems I have.
Basically it is a jQuery slider plugin. I only want the JS and CSS files injected when this block is actually used. So I thought that using includeCssFile, includeJsFile and includeJs would be a perfect fit for this.

{% set images = block.images %}

    {%- for image in images -%}

    {%- endfor -%}

{% includeCssFile "/assets/javascripts/slick/slick.css" %}
{% includeCssFile "/assets/javascripts/slick/slick-theme.css" %}
{% includeJsFile "/assets/javascripts/slick/slick.min.js" %}
{% set owlJs %}
    $(document).ready(function() {
      $("#screenshot-slider").slick();
    });
{% endset %}
{% includeJs owlJs %}

OK. So far so good. It works rather well.

Problem 1

The {{ getHeadHtml() }} in the _main.twig file is somehow ignored. Instead of injecting the CSS files BEFORE my styles.css files, they are injected just before the &lt;/head&gt; tag. As if it wasn't there.

Anybody experienced this behaviour?

Problem 2

This concerns caching.

When I try to cache the content matrix the following way:

{% extends "_layouts/_main" %}

{% block content %}
    {% cache %}
        {% for block in entry.cf_content_matrix %}
            {#
                Include all blocks
            #}
            {% include "_blocks/_block_" ~ block.type ignore missing %}
        {% endfor %}
    {% endcache %}
{% endblock %}

NOTHING get's injected. Neither the CSS files, nor the JS files.

Does anybody know why this is the case, and if there is a solution to it?

Any help appreciated!


texts: Entry next sibling return a deactivated entry

texts:
I got an entry template from a structured section.
With prev / next nav links at entry bottom.
But the next sibling is deactivated.
So the page return is 404 not found !

{% set prev = entry.prevSibling %}
{% set next = entry.nextSibling %}

{% if prev %}
    <&nbsp;{{ prev.title }}
{% endif %}
{% if next %}
    {{ next.title }}&nbsp;>
{% endif %}

Should it be status=live by default no?


texts: Date fields saving the wrong date from front-end form

texts:
I have a front-end form with two date fields. After upgrading to Craft 3 and implementing what I believe to be all the changes concerning front-end forms in Craft 3 I am experiencing some odd behavior.

The odd behavior

When I enter manually or use jQuery UI Datepicker plugin to enter a desired date into any of the date fields associated with this front-end form (this is the only front-end form on the site currently), the date gets saved one day behind. E.g. if I enter 2018-05-01 it gets saved as 2018-04-30. However, if I go to the admin area and add a new block to this matrix field it saves correctly.

What I changed when upgrading from Craft 2 to 3 is the following:

{{ getCsrfInput() }}
<input type="hidden" name="action" value="entries/saveEntry">

to

{{ csrfInput() }}
<input type="hidden" name="action" value="entries/save-entry">

I also checked and confirmed that I am using the most up-to-date version of jQuery UI to rule out the datepicker as the culprit.

Here is a gist of the form: https://gist.github.com/swthate/08152aefe2c481cd792fc156a9ea1bc6

Note: fields/inputs in question are on line 38 and line 49 of the gist (lotMixDate and lotExpireDate).

Thanks!