texts: Can I use relational parameters that query as items on their own?

texts:
I am running a craft site on craft 2.6.2997 and latest craft commerce.

I am building a url query that allows the user to add query params to the url with a bit of js. The url structure is as follows as an example:

?types[]=coffeeAndSide&materials[]=lacquer

On each click of the tags below it adds/removes the query items to the url and then I use an ajax GET request to pull the data from the page url to show the results.

One piece of trouble I am having is that in the url above the results should technically show something because there are relations in the coffeeAndSide types query and it should show regardless of materials having this item in it. My query setup is below:

{% set typesQuery = craft.request.getParam('types') %}
{% set materialQuery = craft.request.getParam('materials') %}

{# Start an array of search parameters (relationParam) with 'and' to match ALL categories #}
{% set relationParam = ['or','and'] %}
{% set productTypes = [] %}
{% set allValues = [] %}

{# Find categories that match the slugs in your query string... #}
{% for querySlug in materialQuery %}
  {% set materialCategory = craft.categories.group('materials').slug(querySlug) %}

  {# And merge them into the relationParam array. #}
  {% set relationParam = relationParam|merge({targetElement: materialCategory}) %}
  {% set allValues = allValues|merge({targetElement: materialCategory}) %}
{% endfor %}

{% for queryTypeSlug in typesQuery %}

    {% set type = queryTypeSlug %}

    {% set productTypes = productTypes|merge([type]) %}
    {% set allValues = allValues|merge([type]) %}

{% endfor %}

{% if relationParam|length < 1 %}
  {% set relationParam = '' %}
{% endif %}

{% set products = craft.commerce.products({
  type: productTypes
}).relatedTo(relationParam) %}

{% set queriedProducts = products.find() %}

For some reason it doesn't show anything when really it should.

Is there a way I can get it to work where both types and materials can query on their own and if either of them have a result that should technically show?

Thanks,
Mark


texts: How do you create pagination links related to entries within a Matrix Field in a single entry?

texts:
I have combed through similar questions, although my pagination links are not performing properly.

I would like to add pagination links to entries within a channel. And I would like for the pagination order to be pulled from an Entries field within a Matrix located within a Single entry.

So far I have:

{% set source = craft.entries.sectionId(10).first().gallery.type('gallery').first().entries.relatedTo(entry) %}

{% set prevEntry = entry.getPrev(source) %}
{% set nextEntry = entry.getNext(source) %}

Next: {{ nextEntry.title }}
Previous: {{ prevEntry.title }}

Where SectionId(10.first() is pulling the Single entry and gallery.type('gallery').first().entries is pulling the Entries field within the Matrix.

Unfortunately this is producing blank Next and Previous links.

Next:
Previous:

I have referred to other questions regarding params and relations, although through experimenting with different solutions I am not queuing up the correct Next and Previous entries.

Neither is Craft providing any error reports regarding the blank state.

Any help is greatly appreciated.


texts: Can you beta build a Craft site in the www directory while the current site is still running?

texts: I'm gungho to get started building in Craft but I don't want the complications of moving the site over from a development directory. Is there a way to easily do this while the current site is up and running?


texts: Craft 2.6.2999 install error: Base table or view already exists: 1050 Table 'craft_entryversions' already exists'

texts:
I keep getting stranded at the "Oops" modal on install. This is on the third Craft site I've started. The other two Craft 2 sites stood up fine, an I've been developing them for nearly a year.

I've seen questions about this but haven't seen a resolution. Maybe my situation will help figure this out.

Log error output:

[error] [exception.CDbException] exception 'CDbException' with message 'CDbCommand failed to execute the SQL statement: SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'craft_entryversions' already exists' in /var/www/thesite/craft/app/framework/db/CDbCommand.php:358

Stack trace:

#0 /var/www/thesite/craft/app/framework/db/CDbCommand.php(1352): CDbCommand->execute()
#1 /var/www/thesite/craft/app/etc/db/DbCommand.php(507): CDbCommand->createTable('craft_entryvers...', Array, NULL)
#2 /var/www/thesite/craft/app/records/BaseRecord.php(301): Craft\DbCommand->createTable('entryversions', Array, NULL, true)
#3 /var/www/thesite/craft/app/services/InstallService.php(172): Craft\BaseRecord->createTable()
#4 /var/www/thesite/craft/app/services/InstallService.php(56): Craft\InstallService->_createTablesFromRecords(Array)
#5 /var/www/thesite/craft/app/controllers/InstallController.php(159): Craft\InstallService->run(Array)
#6 /var/www/thesite/craft/app/framework/web/actions/CInlineAction.php(49): Craft\InstallController->actionInstall()
#7 /var/www/thesite/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#8 /var/www/thesite/craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#9 /var/www/thesite/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#10 /var/www/thesite/craft/app/framework/web/CWebApplication.php(282): CController->run('install')
#11 /var/www/thesite/craft/app/etc/web/WebApp.php(823): CWebApplication->runController('install/install')
#12 /var/www/thesite/craft/app/etc/web/WebApp.php(790): Craft\WebApp->_processActionRequest()
#13 /var/www/thesite/craft/app/etc/web/WebApp.php(203): Craft\WebApp->_processInstallRequest()
#14 /var/www/thesite/craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
#15 /var/www/thesite/craft/app/index.php(62): CApplication->run()
#16 /var/www/thesite/public/index.php(19): require_once('/var/www/thesite...')
#17 {main}
REQUEST_URI=/index.php?p=admin/actions/install/install

I've tried this on a couple of local vagrant boxes:

ubuntu xenial 64, nginx, php7.0-fpm, mysql server 5.7.20
ubutnu trusty 64, nginx, php5-fpm, mysql-server 5.5.58

I have successfully installed an older version of Craft on both of these boxes before.

The DB user was root for both environments, so DB permissions shouldn't be an issue as suggested in another post about this.

I also tried deleting the tables mentioned in the log and tried again, as mentioned in another post about this. I just got an error about another duplicate table.

I also destroyed and recreated each vagrant box, so I don't think lingering sql temp files are an issue as reported elsewhere.

Any new direction on this would be awesome. We already have a Craft site ready for production, but if we can't use it for a related site for the same client, we'll have to move on to something else, and that's the last thing I want to do.


texts:
I have an asset volume which uses dynamic subfolders on the field level.

I have an assets volume called 'members'.
In a matrix field on the user profile tab there is an image field that sets its upload directory to be {owner.author.username} within the members volume.
In my filesystem there is a folder called web/images/members/username (where username is the actual username). This folder contains images.

FYI this Craft site is 5 years old and has recently gone through a major upgrade to Craft v3.

I cannot get the assets field to show existing images when trying to edit it in the admin panel.

I have tried various permutations in the dynamic subfolder path, for example:

{owner.username}
{currentUser.username}
{{currentUser.username}}

But in no situation can I get the field to see the images in the subfolder.

There are fields in matrixes and also basic asset fields not in matrixes that have this issue, so I need assistance in how to set up the matrix asset fields and non-matrix asset fields to be able to see the same folder.

Many thanks


texts: Is it possible to change the default settings of the Rich text field? I know that I can change the configuration in Simple.json and Standard.json but I can't find a Default.json file.


texts: Alter the routing in Craft for every URL independent of language

texts:
How can I alter the routing in Craft? I need to add a (variable) segment to every possible URL.

The reason is we have a multi lingual site with multiple regions. We need to know the correct region in every template to know which data to load. There are many "multi site/multi region hacks" to find on SE to achieve this, but we don't really like any of them.

We want to add the region segment to the URL after the language segment: eg. https://myurl.com/en/region

Problem is of course re-routing that URL.

One option would be to add dynamic routing, but than I need to do this for every template in every language (for translation purposes) and that seems a lot of work. Also, when a new language or template is added later on, all routes must be set anew.
I came upon the getElementRoute hook. That allows me to change the URL as I would change it in my Twig template but nothing more it seems.
A query string is also an option but that's just not pretty.

I would need something like a global dynamic route without a specified template to tell Craft: whatever route you get, just disregard segment 2 (region) and do the routing as you would otherwise do.

So, is there a way to add a segment to Craft without messing up all the routing? Maybe some very base level function?

UPDATE

I was thinking about using the getElementRoute() hook to alter the URL by adding the region segment.

And than somehow create a route dynamicaly in the registerSiteRoutes() hook that corresponds to the URL I retrieved in getElementRoute().

I can do the first part, but not the second.


texts: In Craft Commerce, is it possible to show a more meaningful error when the customer tries to add more of a product than is in stock to the cart

texts:
Currently, if a customer attempts to add a greater quantity of a product to the cart than is in stock, an "Unable to update cart" flash message in shown.  e.g. there are 3 in stock and the customer tries to add 4 to their cart.
Is there any way to change what that error says? As obviously a customer isn't going to know what that means.
Thanks!


texts: How do I use a relation field in an element?

texts:
Currently I have a field that extends BaseRelationField, and 2 types of elements. I want the field on elements A to be able to select from elements B.

So far the field itself works, which I tested by registering it and adding it to an entry. It shows elements B as options and stores it in the relations table.
So far so good.

But I don't want to add this field to an entry, but to elements A. My current attempts revolved around using Craft::$app->fields->createField() and Craft::$app->fields->saveField() to create the field (which also gives it an id) since Craft::$app->getRelations()->saveRelations() requires the field to have an id (which makes sense to me). But this means my field will show up in the settings/fields in the cp. Also using this method, I don't know how to properly retrieve the values to fill the index page of the element and the edit page.

Is there some way to add the field without adding it to the 'normal' part of the cp while being able to use the relations table or am I going at this completely wrong? And also how to retrieve the stored data in the most convenient way?


texts: "Object of class Craft\ElementCriteriaModel could not be converted to string" in Craft CP

texts:
After updating some fields for entry types and submitting new entries, I'm getting a "Object of class Craft\ElementCriteriaModel could not be converted to string" in the Craft control panel upon trying to access any of the entries.

I can still create entries, but once created, I cannot access it again.

Any idea how to troubleshoot this?

The error it's giving back to me is on line 34

craft/app/templates/entries/_edit.html(34)

22         {% if not isVersion %}
23             <input type="hidden" name="sectionId" value="{{ section.id }}">
24             {% if entry.id %}<input type="hidden" name="entryId" value="{{ entry.id }}">{% endif %}
25             {% if craft.isLocalized() %}<input type="hidden" name="locale" value="{{ entry.locale }}">{% endif %}
26         {% else %}
27             <input type="hidden" name="versionId" value="{{ entry.versionId }}">
28         {% endif %}
29
30

31

32

33                     {% include "_includes/tabs" %}
34                     {% include "entries/_fields" with {
35                         static: isVersion
36                     } %}
37

38

39
40

41
42                 {% if showPreviewBtn %}
43                     {% include "_includes/previewbtns" %}
44                 {% endif %}
45
46                 {% if craft.isLocalized() and section.getLocales() | length > 1 %}


texts: Field type for selecting a section (channel / structure / single)?

texts:
I have a channel for products but in some cases I would like to associate a product with a structure containing documentation and release note pages:

http://mysite.com/product/my-product/docs/getting-started
                          ^--------^      ^-------------^
                              |                  |
                           channel             topic (from 'myProductStructure')

Is there an existing field type (or plugin) which would allow selection of the associated structure type:

Title: My Product  [text]
Doc Source: My Product Structure  [drop-down]

Such that I could use that in templates?

{% for entry in craft.entries.section( product.docSource ).slug( craft.request.lastSegment ) %}
    ...
{% endfor %}


texts:
I developed a web site some years ago in PHP and mySQL.  I'm wondering if it would be worthwhile to convert it to a CMS like Craft.

The site -- http://blacksmiths.mygenwebs.com -- displays information on historical figures -- "tradesmen".  These are arranged by region, so "Devon", for example, contains all people who lived in that region and performed that service.
The lady the site belongs to collects the data and puts it into a spreadsheet and uploads the comma-delimited .csv files to the site.  (no, she won't consider abandoning her spreadsheets)
The software reads the .csv files and creates a page for each .csv file
It also uses the CSV file to create the home page (at the link above)

I would like to change the operation slightly

have the uploaded .csv data placed into a database table and the pages be dynamically generated from there (there are only nine fields in each row).
have a form where she can input new data
be able to export the data to the spreadsheet format she likes

There is also an administrative back-end, all in PHP-mySQL, that stores data on contributors, which tradsman they contributed and their email address, if it is to be displayed on one of the pages (right now, the email uses javascript obfuscation, but each should really use a contact form to protect the email addresses).

it would be useful to create links between the tradesman table record and the contributor table record.

I can do all this in PHP, but I'd like to see if Craft could make this simpler.

I'm looking for suggestions as to whether going to a CMS like Craft would be a good idea and perhaps some suggestions on how to go about it.


texts:
I've had to continue with a Craft CMS install somebody else did, now trying to make sense of it.

A client bought a PRO licence, but the CMS seems to still have a SOLO installed. Is there anyway to convert one to another without having down time in the site?

There is no option to upgrade the CMS once you bought the PRO license.

Thanks in advance

Edit: worth noting that clicking "reactivate" results in a "Craft has successfully been upgraded" but does not result in the removal of the "trial" message in the bottom or in added functions.


texts: WARNING: heuristic fragment matching going on! when querying matrix fields or any query with multiple fragment types with Graph QL using Nuxt Apollo

texts:
I am relatively new to using Craft Headlessly and am trying to query matrix fields with Nuxt JS and it's Apollo module.
I have discovered, that although the graphQL queries work in the GraphiQl interface, they do not work with Apollo due to Apollo not knowing the schema for unknown fragments. I've stumbled apon a few others who have had this issue such as this guy but their solution confused me and seemed more complicated than I would expect. I'm sure there must be a simple solution considering this is a widely used system for working with Craft Headlessly.
I also saw this response from someone (see the response from Mylesthe.dev) who gave some instruction but I still didn't quite understand how to apply this. The post above this also mentions that Apollo-client 3.0 should be able to handle unknown fragment types but I'm on @nuxtjs/apollo ^v4 and still experiencing it.
Does anyone have a simple clear fix for this that I can apply to my set up, so that I can query matrix fields with multiple fragment types in Craft CMS?
My Package.json file is:
{
  "name": "nuxtjs-test",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate"
  },
  "dependencies": {
    "@nuxtjs/apollo": "^4.0.1-rc.5",
    "core-js": "^3.6.5",
    "dotenv": "^8.2.0",
    "flickity": "^2.2.2",
    "headroom.js": "^0.12.0",
    "node-fetch": "^2.3.0",
    "nuxt": "^2.14.6",
    "vue-rellax": "^0.2.0"
  },
  "devDependencies": {
    "@nuxtjs/dotenv": "^1.4.1",
    "@nuxtjs/style-resources": "^1.0.0",
    "fibers": "^5.0.0",
    "sass": "^1.32.0",
    "sass-loader": "^10.1.0"
  }
}

My apollo GQL query is (const GET_HOMEPAGE):
{
  entry(section: "homepage") {
    ... on homepage_homepage_Entry {
      homepageBuilder {
        ... on homepageBuilder_sectionHeadline_BlockType {
          typeHandle
          headline
        }
        ... on homepageBuilder_showcase_BlockType {
          typeHandle
          limit
        }
        ... on homepageBuilder_articles_BlockType {
          typeHandle
        }
      }
    }
  }
}

my apollo smart query is:
apollo: {
      entry: {
        query: GET_HOMEPAGE,
        error (error) {
            this.error = JSON.stringify(error.message);
            console.log(error);
        },
        result ({ data, loading, networkStatus }) {
          console.log("[networkStatus]",networkStatus);
          console.log(data);
        },
      },
    },

my apollo settings in Nuxt.config file is:
  apollo: {
    clientConfigs: {
      default: {
        httpEndpoint: process.env.APOLLO_DEFAULT_ENDPOINT,
      }
    },
    defaultOptions: {
      $query: {
        fetchPolicy:'no-cache'
      }
    }
  },


texts: currentUser: Impossible to invoke a method ("isInGroup") on a null variable

texts:
I couldn't find this anywhere else, I'm looking up if the currentUser.isInGroup('verified') and if not, display another link. Works fine when logged in but throws a Template and Runtime error when using the {{logoutUrl}} or viewing any page when not logged in.

I expected this would work the same as currentUser by itself, which throws no errors. But obviously there's something I'm missing. Should I be using something like craft.session in combination with the isInGroup? Or some other method of detection?

Update

{% if currentUser.isInGroup('verified') is defined %}

Seems to get rid of the errors. So a couple of questions:

Is this expected behaviour?

I'm yet to wrap my head around the |length is defined etc methods of checking, and when to use them. I'll have to go over this post a few more times!


texts:
I'm using the following code in my template to truncate the body of an entry (coming from a Rich Text field):

{{ entry.body | slice(0, 500) | markdown }}

To this, I'd like to add ... as a string, so that it will output like:

Words words words...

Since the field part I'm using outputs into its own <p> tag, adding the ... into the HTML itself has them sitting in two different tags. I've tried using |join but I must be doing something wrong, its putting the first part into a separate <p> tag than the ...

Thanks for your help!


texts:
Due to problems I had with Craft 3 Beta 23 I switched back to version Beta 22 (I did this a couple of times)

I do this by importing an sql dump of beta 22 and by directly requesting Beta 22 via composer.

The strange thing: Craft forgets about Plugins it had installed. They simply do not appear anymore in the plugins list, although they are installed via composer and nothing changed in them.

I cleared storage/runtime and I also cleared the DB cache via utilities, that does not help.

Any hints why Craft does not show the plugins anymore in the list? Is there another cache?


texts: Cart Items Total to include qty of variants

texts:
By using line total: {{ cart.lineItems|length }} it returns the number of 'products' in the current sessions cart. However, this doesn't seem to take into account the qty of each variant.

So if I add 3 of variant A and 2 of variant B, the lineItems|length would equal 2. But I want to cart to show there are 5 items added.

How can I get the total of all the items in the cart including qty of each variant?


texts:
I continue to see these pile up. If I clear my template cache, I can hit retry on each and they go away, but that's getting tedious.

I have the following from a P&T support request on these a while back, but is there any way to track down where/why these are happening now? I'm not seeing any deprecated tag errors or anything in the CP, nor am I seeing any template errors on the site, and I have a fair number of pages cached where images are being resized.

Hrm... I see the error that's occurring in your log files when that task tries to complete. What looks like happened was that there was an error in your Twig code somewhere inside of one of your {% cache %} tags and that error actually got cached and saved to the database and that is freaking the DeleteStaleTemplatesCache task out.
Kinda hard to back track which cache tag it occurred in and what part of your template code.
But the way to get it worked again is to clear your template caches manually from Settings->Tools. You should be able to click "retry" on those failed tasks again and they should complete fine.

Thanks!
Mark


texts: Sprout Forms Notifications to Office 365 address failing

texts:
I've got a few Sprout forms on a site that are functioning nicely. Data is being save and notifications are firing to 2 of the 3 addresses. The third address is an Office 365 mailbox on the same domain but hosted elsewhere.

I'v tried updating Craft's Email setting to the SMTP info provided by the IT company in charge of the mail but it's erroring out with:

SMTP Error: data not accepted.

Has anybody else had issues with this? A little Googling has led me to believe that this is a common issue. Wondering if anybody in the Craft community has dealt with it successfully.


texts: Debugging an error ("An unknown error occurred")

texts:
I keep getting an error when I am in the CP. The stack trace of the error that is logged is below:

2016/08/02 01:12:05 [error] [exception.Craft\HttpException.404] exception 'Craft\HttpException' in /home/capspacedevhosti/craft/app/controllers/TemplatesController.php:59
Stack trace:
#0 [internal function]: Craft\TemplatesController->actionRender('(X(1)S(q325ycaz...', Array)
#1 /home/capspacedevhosti/craft/app/framework/web/actions/CAction.php(109): ReflectionMethod->invokeArgs(Object(Craft\TemplatesController), Array)
#2 /home/capspacedevhosti/craft/app/framework/web/actions/CInlineAction.php(47): CAction->runWithParamsInternal(Object(Craft\TemplatesController), Object(ReflectionMethod), Array)
#3 /home/capspacedevhosti/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#4 /home/capspacedevhosti/craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#5 /home/capspacedevhosti/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#6 /home/capspacedevhosti/craft/app/framework/web/CWebApplication.php(282): CController->run('render')
#7 /home/capspacedevhosti/craft/app/framework/web/CWebApplication.php(141): CWebApplication->runController('templates/rende...')
#8 /home/capspacedevhosti/craft/app/etc/web/WebApp.php(279): CWebApplication->processRequest()
#9 /home/capspacedevhosti/craft/app/framework/base/CApplication.php(184): Craft\WebApp->processRequest()
#10 /home/capspacedevhosti/craft/app/index.php(62): CApplication->run()
#11 /home/capspacedevhosti/public_html/index.php(19): require_once('/home/capspaced...')
#12 {main}
REQUEST_URI=/(X(1)S(q325ycazg05lq11ktn1hqjtx))/copyright
---
2016/08/02 01:12:05 [error] [application]

Anyone knows how to fix it?


texts:
I have a problem when trying to put a div into a content of an entry.

I'm creating entries, building a HTML hierarchy that helps me to manipulate the content with JS. I'm adding divs an build something like this:

Hi I am a title

this is the introduction

this is the content

When I create this, the hierarchy is right, but when I edit it from the CP, all the divs change to this:

Hi I am a title

this is the introduction

this is the content

What can I do to prevent this from happening? Hope you can help me, thanks.


texts: Any working RSS feed examples out there?

texts:
Do you only have to build the .rss template file and then you use that URL for your RSS feed? Based on the documentation at hand, that's what it seems like.

I'm attempting to parse an RSS feed using the Google Feed API (https://developers.google.com/feed/) and it's having issues reading the output - so I just want to see if anyone else out there is using RSS in Craft so I can see their output vs mine. When I view mine, it doesn't look like a traditional xml output.


texts:
That is written so inefficently:

{% set indexNavi = craft.entries.section('pageContent').level(1).all() %}
{% set bookingLink = craft.entries.section('booking').all() %}

  {% for item in indexNavi %}

      {{ item.title }}

  {% endfor %}
  {% for item in bookingLink %}

      {{ item.title }}

  {% endfor %}

Is there a better way?

I wanted to creat a single variable:

{% set merger = craft.entries.section(['pageContent','booking']).level(1).all() %}

But this only outputs the pageContent. I guess because booking is a single section and therefore has no level?


texts: How to output a placeholder image if an Assets field is empty

texts:
I'm trying to output an Asset image if the Main Image field is populated, and if it's not populated, I'd like to output a placeholder image. But I'm having problems getting the conditional to work - it outputs the image in the Assets field, but when the field is empty, it's not outputting the placeholder image. Any ideas on what I'm doing wrong here? Thanks.

{% if entry.mainImage %}
  {% for asset in entry.mainImage %}

  {% endfor %}
{% else %}

{% endif %}


texts: Can't install Craft 3 when deploying to AWS EC2 instance - Template not found: install Template not found: install

texts:
I'm deploying my Craft 3 application to an ec2 instance using elastic beanstalk. When I navigate to "/admin/install", I get the following error:

When I ssh into my ec2 instance to check the 404 logs, the stack trace I get is:

  2018-03-02 11:47:03
  [192.195.80.235][-][-][error][yii\web\HttpException:404]
  yii\web\NotFoundHttpException: Template not found: robots.txt in
  /var/app/current/vendor/craftcms/cms/src/controllers/TemplatesController.php:69
  Stack trace: 0 [internal function]:
  craft\controllers\TemplatesController->actionRender('robots.txt',
  Array)

  1 /var/app/current/vendor/yiisoft/yii2/base/InlineAction.php(57):
  call_user_func_array(Array, Array)

  2 /var/app/current/vendor/yiisoft/yii2/base/Controller.php(157):
  yii\base\InlineAction->runWithParams(Array)

  3 /var/app/current/vendor/craftcms/cms/src/web/Controller.php(74):
  yii\base\Controller->runAction('render', Array) 4
  /var/app/current/vendor/yiisoft/yii2/base/Module.php(528):
  craft\web\Controller->runAction('render', Array)

  5 /var/app/current/vendor/craftcms/cms/src/web/Application.php(237):
  yii\base\Module->runAction('templates/rende...', Array)

  6 /var/app/current/vendor/yiisoft/yii2/web/Application.php(103):
  craft\web\Application->runAction('templates/rende...', Array)

  7 /var/app/current/vendor/craftcms/cms/src/web/Application.php(226):
  yii\web\Application->handleRequest(Object(craft\web\Request))

  8 /var/app/current/vendor/yiisoft/yii2/base/Application.php(386):
  craft\web\Application->handleRequest(Object(craft\web\Request))

  9 /var/app/current/web/index.php(21): yii\base\Application->run()

  10 {main}

  2018-03-02 11:47:03 [192.195.80.235][-][-][info][application] $_GET =
  [
      'p' => 'robots.txt' ]

Why is this happening and how can I fix it?


texts: Can I set an environment var for SMTP mail servers?

texts: Pretty straight forward here, I'd like to use MailTrap for devMode and then use an SMTP service (Mandrill or like) for production. I looked through the General Config Settings docs but didn't see anything that lent itself to being SMTP related. Is this possible?


texts: Use a plugin from another plugin in Craft 3

texts:
I would like to use another plugin from my own plugin. What is the best way to do this. Right now I am doing something like this, but there should be a better way than to explicitly call the service:

Craft::$app->getModule('mobile-detect')->mobileDetectService

What I am really looking for is the service container where I do not have to know anything just the plugin what should have been loaded...?


texts: How could I load content from one Craft install into a template of another

texts:
We are working on a help guide solution for Craft and our hope is to have all the guide content live in a single master Craft setup and then our client's sites could read and display this content in their admins through a custom plugin.

We have the rough outlines of a proof of concept for it, the missing piece is sharing the content.  We are thinking of using RSS or JSON to do this but wanted to see if there was any other ways we should consider?


texts: Navigation position in Control Panel Craft CMS 2.5

texts:
The new position of the Control Panel navigation on the left side in Craft CMS 2.5 needs so much space and looks kind of wrong to me.

Is there any way to position it on the top like in pre 2.5 versions?


texts:
I have two channels set up, the first creates entries called "databytes" the second is a channel for relating certain databytes to each other called "databyteSeries". In my template I want to output all databytes but if they are related just show the first in the series. I have the following code which is displaying the first in the databyteSeries no problem (sectionId 8):

{% paginate craft.entries.section(['databytes','databyteSeries']).limit(6) as entries %}

{% for entry in entries %}

  {% if entry.sectionId == 8 %}

  {% for series in entry.relatedDatabytes %}
    {% if loop.first %}
      {# TEMPLATE CODE FOR ENTRY HERE #}
    {% endif %}
  {% endfor %}

  {% else %}

    {# THIS NEEDS TO DISPLAY ALL DATABYTES THAT ARE NOT RELATED #}

  {% endif %}

{% endfor %}

{# PAGINATION CODE HERE #}

{% endpaginate %}

It's the second part where I now only want to display the databytes that have NOT been related where I am struggling. I guess it needs some kind of reverse relationship where I have put the {# THIS NEEDS TO DISPLAY ALL DATABYTES THAT ARE NOT RELATED #} but I am not sure.

Any help would be appreciated.


texts: How to return data to an ajax succes callback

texts:
I want to call an action via an ajax call with the following code:

$.ajax({
    url: Craft.getActionUrl(_this.options.updateRestockAction),
    method: 'POST',
    headers: headers,
    data: data,
    success: function(data) {
        console.log(data);
    },
    error: function(jqXHR, textStatus) {
        console.log('error');
    },
    complete: function(jqXHR, textStatus) {
        console.log('complete');
    }
});

My action is being called successfully. However, I can't find out how to return data to the success callback. Any idea how to do this? I'm using Craft 3.

Thanks


texts: Viewing Assets (PDFs) associated with an entry directly from that entry screen

texts: I have a channel with an Assets field, designed to hold PDF files. It works fine to select one or more files, and/or upload files and select them. However, I'm wondering if there is a way to view a PDF once selected, from the add/edit entry screen.


texts:
A client's site is currently showing this message:

  Craft does not support backtracking to this version. Please upload
  Craft 2773 or later.

I understand how to fix it, but I don't understand how it's happened.

In Craft’s request log I can only see one update:

2016/02/22 15:37:15 [info] [application] [Forced] Updating from 2.5.2761 to 2.5.2763.

But in the craft_info table the version and build are 2.6 and 2773, updated_at 2016-03-09 22:07:49.

Also in the log are several requests hitting 404s - /wordpress/, /administrator/index.php, /wp/, etc.

Then at 2016/03/10 04:07:42 (6 hours after craft_info was updated) in the log I'm seeing a load of these errors:

******************************************************************************************************
2016/03/16 09:11:25 [error] [exception.Craft\HttpException.503] exception 'Craft\HttpException' in /chroot/home/lincshub/lincshub.com/craft/app/etc/web/WebApp.php:229
Stack trace:
#0 /chroot/home/domain/domain.com/craft/app/framework/base/CApplication.php(184): Craft\WebApp->processRequest()
#1 /chroot/home/domain/domain.com/craft/app/index.php(62): CApplication->run()
#2 /chroot/home/domain/domain.com/html/index.php(19): require_once('/chroot/home/li...')
#3 {main}
REQUEST_URI=/
---

The last deployment (local to production) was made on 5 Feb 2016 12:44.

Could anyone shed some light on what's going on here please?


texts: How to use a Numeric Field with a Default Value

texts:
I have a case where I need to use a numeric field which also has a default value.

For example: numericField needs to have a minimum value of 100 and a max value of 1000, but when the user adds a new entry, the field value should default to 256 in the entry form.

Unfortunately, I cannot trust the user to enter the correct default value, even if it is clearly indicated in the field notes.

Right now, when the user adds a new entry, numericField will always be set to 100 the minimum value.

Is there another integer field type which would work as I have described?


texts:
I have a plugin that sets the user group based on whether a hidden checkbox has been ticked on the sign up form.

The plugin works exactly as I want it to while I'm logged in, but as soon as I log out the form reverts to default behaviour.

I can't find anything in Google about plugins misbehaving when someone logs out. Does anyone know what's going on and how I can overcome it?

Plugin code below;

public function init() {

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

      $user = $event->params['user']

      if ($event->params['isNewUser']) {

        $groupPreference = $user->getContent()->groupPreference;

        if (in_array("trade", $groupPreference)) {

           craft()->userGroups->assignUserToGroups($user->id, 3);

        }

      }

    });

}


texts: Does Craft have any default keys for flash messages?

texts: Does Craft have any default keys for flash messages like logging in or updating a profile?


texts: An unknown error has occurred in asset reindex

texts:
I am getting the error: An unknown error occurred for each file in a folder when I try Update Asset Indexes.  The folder is a local folder that is outside of webroot.  The files just contain json data. I have looked through Craft log files and apache log files and cannot find anything. Any ideas?

I have tried the following from other questions with the same error message and none of these made an difference.

Deleted entire craft/storage/runtime/ folder

An unknown error occurred - no log entry

Made sure no record in table assetindex has null for dateModified column

"An unknown error occurred" in assets screen

Reset folder ownership

permissions userphotos "an unknown error occurred"


texts: Exchange Content between Local and Production

texts:
Often I want to test in my local environment with content other people created on the production site. So it would be great to copy e.g. an entry from production.

I've found:

Smith https://plugins.craftcms.com/smith for copy, pasting, and cloning of matrix blocks, but unfortunately only within one Craft installation.

Is there a smart way to quickly exchange content from production with a local dev environment and vise versa?


texts: Accessing global field values in site loop

texts:
I have a drop down select that I am populating with sites.
I've added a lightswitch field (handle 'showInDropDown') to the global set 'siteInfo' with the hope of getting the lightswitch value per site in the loop below.
{% for siteId in currentSite.group.sites %}
    {% set setForSiteId = craft.app.getGlobals().getSetByHandle('siteInfo', SiteId =5) %}
    {{ setForSiteId.showInDropdown }}
{% endfor %}

The lightswitch field is set to translate per site.
setForSiteId is always coming back null:
Impossible to access an attribute ("showInDropdown") on a null variable.

I am not sure if I am missing something. Is there another way to access global variables/values per site?


texts: Get the Sub-Category Link from Category field in a Structure (output with Nav tag)

texts:
I am creating a Structure for the main navigation that has two possible choices for the Link: Entries field or a Categories field. The answer I received here showed me how to setup the basics but if the Category page I want to link to is a Sub Category, it will only link to the Parent.
{% set menu = craft.entries.section('navDropDownMenu').all() %}

    {% nav link in menu %}

        {% if link.entriesURL|length %}
            {% if craft.app.request.absoluteUrl ==  link.entriesFieldURL[0].url %}
                {{ link.title }}
            {% else %}
                {{ link.title }}
            {% endif %}
        {% else %}
            {% if craft.app.request.absoluteUrl ==  link.categoryFieldURL[0].url %}
                {{ link.title }}
            {% else %}
                {{ link.title }}
            {% endif %}
        {% endif %}
            {% ifchildren %}

                    {% children %}

            {% endifchildren %}

    {% endnav %}

So what I'm trying to figure out is, if I have a category setup like this:
-Shoes
    -Tennis

in the context of using the Nav Tag (as above), how do I get the link to 'Tennis' and not 'Shoes'?
I know you can output a nav of Categories, but I wanted to use a Structure if possible because the navigation has a mixture of categories and links to internal pages, and they are mixed together in the navigation as far as sorting goes.


texts: 404 shows "Internal Server Error" only on staging environment

texts:
Might be a duplicate, but couldn't find this exact question here.

I have a pretty basic 404.twig template that should be catching things, as described here: https://docs.craftcms.com/v3/routing.html

It works as described on my local environment but I'm getting the generic Craft "Internal Server Error" page on my staging site.

devMode is set to false on both environments, and there is no error prefix specified as in this post: Craft not loading custom 404 template for errors

I checked the web-404s log and confirmed that Yii is throwing a NotFoundHttpException when I test pages. I'm not sure what else I should check. Any ideas?


texts: Setting Variable to Specific Category for Loop

texts:
How do you set a variable to a specific category so you can do an if or for loop? I have entries(staffList) associated to categories (Management,Staff,Other,PartTime)and I am trying to set a variable to do a loop off of and pull the entry fields but am having a difficult time setting the variable to pull just a specific category.

Below is what I am using to set:

{% set staff = craft.entries.section('staffList').relatedTo('Management') %}

Any ideas where I am going wrong?


texts:
I'm stucked with a 404 error on all my localized sub-directories.
It works fine for the homepage ( es. domain.com/es, domain.com/it ). Also urls in the main directory are behaving correctly. Example:
domain.com/products is fine domain.com/es/products is not.

I'm running Craft Pro on Nginx. Here is my general.php:

'siteUrl' => array(
        'en' => 'http://129.0.1.67/',
        'en_us' => 'http://129.0.1.67/us/',
        'de' => 'http://129.0.1.67/de/',
        'fr' => 'http://129.0.1.67/fr/',
        'it' => 'http://129.0.1.67/it/',
        'es' => 'http://129.0.1.67/es/',
        'tr' => 'http://129.0.1.67/tr/',
        'ru' => 'http://129.0.1.67/ru/',
        'zh' => 'http://129.0.1.67/zh/'
)

Here is my index.php file for subfloders

/**
 * Path to your craft/ folder
 */
$craftPath = '../../craft';

/**
 * Define Craft locales
 */
define('CRAFT_LOCALE', 'es');

/**
 * Define Craft Templates Path
 */
 $templatePath = '../../craft/templates';
define('CRAFT_TEMPLATES_PATH', $templatePath);

I'm assuming that my problem is with my NGINX configuration but I'm not confident with it.

    root /var/www/app;

    location / {
            try_files $uri $uri/ @rewrites;
    }

    location @rewrites {
            rewrite ^(.*) /index.php?p=$1 last;
    }

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php7.0-fpm.sock;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
    }

Here is a Craft log in the browser console:

[12:46:33.764][error][exception.Craft\HttpException.404]
Craft\HttpException in /var/www/craft/app/controllers/TemplatesController.php:72
Stack trace:
#0 [internal function]: Craft\TemplatesController->actionRender('es/oil-news/pro...', Array)
#1 /var/www/craft/app/framework/web/actions/CAction.php(109): ReflectionMethod->invokeArgs(Object(Craft\TemplatesController), Array)
#2 /var/www/craft/app/framework/web/actions/CInlineAction.php(47): CAction->runWithParamsInternal(Object(Craft\TemplatesController), Object(ReflectionMethod), Array)
#3 /var/www/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#4 /var/www/craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#5 /var/www/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#6 /var/www/craft/app/framework/web/CWebApplication.php(282): CController->run('render')
#7 /var/www/craft/app/framework/web/CWebApplication.php(141): CWebApplication->runController('templates/rende...')
#8 /var/www/craft/app/etc/web/WebApp.php(290): CWebApplication->processRequest()
#9 /var/www/craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
#10 /var/www/craft/app/index.php(62): CApplication->run()
#11 /var/www/app/index.php(67): require_once('/var/www/craft/...')
#12 {main}
REQUEST_URI=/es/oil-news/prova


texts: Stop specific Twig template from rendering anything

texts:
If i want specific template to stop from rendering anything, I use if:
{% if something %}
HTML markup...
{% endif %}

This however requires wrapping whole Template in if which is not ideal for readbility.
Is there maybe some kind of Twig function which when used stops rendering template in which it is used? Like this:
{% if something %}
    {% do stopRendering() %}
{% endif %}

HTML markup (will show up if we didnt stopped rendering)...


texts: How does a plugin output JS that can be used within a cache tag?

texts:
Google Maps for Craft outputs data into script tags to add markers to map with Javascript. Everything works great until a user goes to cache the output of an entries loop. It works upon first page load, but all subsequent page loads do not contain any of the JS at the bottom of the page as it should.

Here is a simple example to duplicate this issue. I am not sure what to do about it. In my mind, there should be a way to output JS that can be cached and output to the page without the query running.

{% set options = {
    id: 'map',
    width: '400px',
    height: '300px',
    clustering: true
} %}

{{ craft.googleMaps.map(options) }}

{% cache %}

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

        {{ craft.googleMaps.data('map', entry.map) }}

        test<br>

    {% endfor %}

{% endcache %}

Within my add-on all the methods that use includeJs behave the same way. But this is just a simple example of what I am doing. I just instantiate an object with some data and include it in the JS.

 craft()->templates->includeJs('new GoogleMaps.MapData('.$id.','.$data->toJson().','.$this->jsonEncode($options).');');

For additional information you can see it here in this support thread on the Github repo.

https://github.com/objectivehtml/Google-Maps-for-Craft/issues/12


texts: Advice on entry form file uploads and S3

texts: Just planning out an entry form that includes a file upload field – an assets field hooked up to an S3 bucket. I see some documentation on entry form assets here, but need some advice on getting this working with S3 if anyone's done this before? Any help very much appreciated.


texts:
What's given:

Channel: Nutrition
Entries Fieldtype: restaurant
Category Fieldtype : menu

Category: Menu

Channel: Menus that also use relations using restaurant field.

Each item in the nutrition channel has restaurant and menu category selected.

On a restaurant's menu page I'm trying to list menu items from the nutrition channel grouped by categories.

Currently I use the following snippet

            {% for category in craft.categories.group('menu').all() %}

{{ category.title }}

                    {% for entry in craft.entries.section('nutrition').relatedTo(category).orderBy('title').all() %}

{{ entry.title }}

                    {% endfor %}

            {% endfor %}

Which works fine. However if I add more nutrition items and assign them to another restaurant they'll be listed as well.

I assume we need to define restaurant first

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

but what are my next steps?


texts: User make assets subfolder in the frontend

texts:
I have a standard user profile form. But now I would like that the user can upload images in new subfolder and make own subfolder.
Is there any solution or a plugin for this?


texts: How do I check if a lightswitch field is false?

texts:
I have a Resources page and an archived Resources page made up of entries. I want to show all current resources on the main page (this list should not include the archived ones) and on the archived page I only want to show only archived resources. I am using a lightswitch field to toggle whether a resource is archived or not.

The archived-only page works as expected, it shows only the archived resources, using this:

{% set resources = craft.entries.relatedTo({ targetElement: category }).order('title').archivedResource('1') %}

The main page, which should show all resource entries except archived ones actually shows all resources (archived and unarchived). I’m using this code:

{% set resources = craft.entries.relatedTo({ targetElement: category }).order('title').archivedResource('0') %}

It appears that the .archivedResource(‘0’) bit is not having any affect. Should I be using some other method to check whether a switch field is toggled or not?


texts: Controller action works but still gives 404

texts:
I'm writing my first plugin and I'm slowly getting there, but I hit on a problem:

I have a controller class in which I have a function that sets a cookie.
I call on this function from within a template with actionUrl().

The weird thing is, the cookie is being set (so the controller action is found and executed) but I still get a 404 page on the action path.

Anybody has an idea what could be wrong?


texts: How do I upload images programmatically?

texts:
I'm working on a plugin that creates auto crops of a selected image, but I am unsure of the proper steps to create and upload an image programatically. I am hoping that Local asset sources and Remote asset sources can be treated the same way. If not, then I would like to create that abstraction.

My understanding of this at the moment is that I need to both insert the file and save an asset file record. So I am first getting a local copy of the original asset that I will create crops from via <assetSource>->getLocalCopy(), and using that local path with  craft()->assets->insertFileByLocalPath().

This works well if I use a Local asset source to store my cropped images. However, when storing my crops on Rackspace, I run into an issue where a naming conflict is not resolved.

I am calling insertFileByLocalPath() with AssetConflictResolution::Replace. I've noticed that fileId is not set in BaseAssetSourceType->insertFileByPath() until the response is successful, which won't happen while there is a naming conflict. Instead the response returns back to craft()->assets->insertFileByLocalPath(), which then tries to access fileId via $response->getDataItem('fileId') which has not been set. I then get an error stating:

Fatal error: Call to a member function getFolder() on null in AssetsService on line 1334.

The failure occurs in AssetService _mergeUploadedFiles() after trying to getFileById() where the id is null, and then calling getFolder() on null.

I am not sure if this is the best place to put this, if this a bug within Craft, or if I am going about creating and uploading Assets in the wrong way.

Are my steps to upload images correct thus far? Can all asset sources be treated in the same way? Any guidance or critique would be greatly appreciated.


texts:
I'm getting this error when trying to call my plugin on a template:

  Fatal error: Call to undefined method Craft\SiteUtilitiesService::init() in /path/to/my/site/craft/app/framework/base/CModule.php on line 394

The template tag:

{{ craft.siteUtilities.videoEmbed( block.video, '219181' ) }}

Content of variables/SiteUtilitiesVariable.php:

class SiteUtilitiesVariable
{
    public function videoEmbed($url, $color)
    {
        return craft()->siteUtilities->videoEmbed($url, $color);
    }
}

Content of services/SiteUtilitiesService.php:

class SiteUtilitiesService
{
    public function videoEmbed($url, $color)
    {
        // some code to get the video ID from the $url variable

        return "<some html embed code with the $color variable>";
    }
}

What's the init method the error is referencing?


texts: Image Transform Internal Server Error (500 code) after Craft CMS update

texts:
I just updated an "older" Craft site (version 2.4.2702) to the newest update (version 2.6.2958).

But now all my image thumbnails in the back-end are missing and if I upload any new assets, the thumbnail is not generated and I get a Internal Server Error 500 on the front-end as the URL it points to is still the cpresources/transforms/283?x=qFc4lFWR5 kind of URL.

The image thumbnail itself is also not generated anymore in the folder it is supposed to go in. I didn't change any folder permissions (only updated the new app folder ofcourse with the correct permissions). I'm able to upload assets so the permissions should be fine I guess.

I've had issues like this before, but those were resolved, so I don't know what is causing this issue again. Is there anything I forgot about this update that I needed to change? I needed to do a manual update.

The logs I get are these:

2017-01-17 10:13:26

Level   info
Category    application
Message [Forced] Finished task 14 (GeneratePendingTransforms).
2017-01-17 10:13:26

Level   info
Category    application
Message [Forced] Starting task GeneratePendingTransforms that has a total of 0 steps.

UPDATE

I do get a PhP error:

[18-Jan-2017 14:04:07 UTC] PHP Fatal error: Call to undefined method Imagine\Imagick\Imagick::getImageAlphaChannel() in MY-BASE-PATH-HERE/craft/app/vendor/pixelandtonic/imagine/lib/Imagine/Imagick/Imagick.php on line 191

But through the PhPInfo in the Craft CP I can see that Imagick extension 2.2.2 is installed with ImageMagick 6.7.2-7, so according to this page the method should exist: http://php.net/manual/en/imagick.getimagealphachannel.php.

UPDATE 2

As I dumbly clicked "rebuild all asset indexes" on the live site (instead of on the local development site in the browser tab next to it aaargh) I quickly added 'imageDriver' => 'gd', to the config as a workaround.


texts: How to access CurrentUser variable in JS file

texts:
I'm using control panel js plugin to add some javascript in users page inside control panel, to hide some data based on current logged in user role, but I'm unable to access the {{currentUser}} variable inside it.
Can anybody tell how to access this variable in js.


texts: Is it possible to use the ElementType Modal UI for a custom Field Type Plugin?

texts:
So I'm writing a plugin to try and create a relationship between two entry sections that is a two way street (Many to Many).

I would love to co-opt the UI and functionality of the ElementType modal for a predefined section ID and then do my own saving logic.

In other words, I would just like to use the front end form functionality and handle the backend logic myself. Is this possible?

Thanks!


texts: Multiple relatedTo conditions using a combination of "and" and "or"

texts:
We're trying to make a filter that allows you to pick multiple items from 1 category, and multiple items from another category and return back all appropriate elements.
We're in PHP land not twig so the starting point we have is...

$results = Entry::find()
    ->type('recipe')
    ->relatedTo($conditions)
    ->all();

The pseudo query would be...
SELECT * FROM `entries`
WHERE
 (`food_type` = "cake" or `category` = "burger")
AND
(`weather` = "summer" or `tag` is "hot")

I've got the IDs and the hydrated models/elements of each category but can't figure out how to nest the conditions using the relatedTo method on the query..
Thanks


texts: Does defineSearchableAttributes() work with getter methods on the model?

texts:
If I define searchable fields via IElementType::defineSearchableAttributes(), the provided fields have to be model attributes. Can they also be getter-methods on the model class, which may return values from other related elements?

e.g. on Plugin_XYElementType.php:

public function defineSearchableAttributes()
{
    return ['relatedTitle','otherField'],
}

in Plugin_XYModel.php:

public function getRelatedTitle()
{
    return craft()->plugin_service->getTitleFromRelatedThing($this->relatedThingId);
}

Will this fields be correctly indexed and searchable in a ElementIndexView, where I use this related fields in a table column? Or does this only work for Attributes, that were defined via defineAttributes() ?

Thanks!


texts:
Is there a way to delete the users that were created in the customers section?
I made a site and generated multiple accounts for testing purposes, but now I have to deliver it and I don't want those users to show up.
Craft users are successfully deleted, but customers are not.


texts: Camera Orientation and image transforms?

texts:
I have a CraftCMS site and a client has uploaded some images to their portfolio that were taken with their iPhone. Generally I don't worry about the EXIF data/camera orientation but it looks like the transforms are ignoring it.

Looking in Chrome - you can see the issue on this page: http://seachant.co/work/levis-x-vsco

Wondering if anyone else has dealt with this or if there is a quick fix for this in Craft (without having the client save out their photos again)?


texts: How to limit sources for Entries field set up via migration

texts:
I'm seeting up all of my project's fields using migrations.
This works really well, but I haven't been able to figure out how to limit the sources (sections) for an entry selection field.

I've based my work on this migrations example, which contains the following code:

new \craft\fields\Entries([
    "name" => "Questions",
    "handle" => "questions",
    "instructions" => "Choose one or more questions",
    "sources" => ["section:" . $questionsSection->id],
    "limit" => 10,
    "required" => false,
    "selectionLabel" => "Select Questions",
]),

However, I don't get how I can add multiple sections as allowed sources… can anybody clarify how to do this?


texts: Frontend Form for editing entries HTTP Exception

texts:
I took the example form of the craft CMS Entry Form Documentation page and tried to use it on a test site.
However i always get a HttpException after submitting the Frontend Form.

Here's the Stack Trace.

And a Screenshot of the Error page

Here's the code

<form method="post" accept-charset="UTF-8">
  {{ csrfInput() }}
  {{ actionInput('entries/save-entry') }}
  {{ redirectInput('viewentry/{slug}') }}
  {{ hiddenInput('sectionId', entry.sectionId) }}
  {{ hiddenInput('enabled', '1') }}
  {{ hiddenInput('entryId', entry.id) }}

  <label for="title">Title</label>
  <input id="title" type="text" name="title"
      {%- if entry is defined %} value="{{ entry.title }}"{% endif -%}>

  {% if entry is defined %}
      {{ _self.errorList(entry.getErrors('title')) }}
  {% endif %}

  <input type="submit" value="Publish">
</form>

It's a multi-site with 3 languages. So maybe its related to the languages.
But i couldn't find any informations for a frontend form in multi-sites.


texts: Autogenerated PDF Thumbnail using PDFThumb in a Matrix Field

texts:
I would like to autogenerate a thumbnail of PDF's, and from this question I found the plugin PDFThumb. The problem I'm running into is I'm relatively new to Craft, and I can't seem to figure out how to use the provided code when it is with a Matrix field.
As I said I'm new to this, and I usually end up tying myself in knots when trying to backtrack the variable references, and I think that's the problem here.
The reference code from the plugin repo:
{% for myAsset in item.assetRef %}

{% endfor %}

And my code:
{% set pdfBlocks = entry.infoPagePDF.all() %}
{% if pdfBlocks|length %}
        {% for block in pdfBlocks %}
            {% if block.type == "pdf" %}
                {% if block.pdfFile %}
                    {% set rel = block.pdfFile.one() %}
                    {% if rel %}
                        {{ rel.title }}
                    {# Autogenerated Thumb #}
                        {% for myAsset in item.assetRef %}

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

The link generates fine, it's the image that doesn't.
I've tried a bunch of different variations, but the problem (I think) revolves around the fact I'm not sure what I'm supposed to be referencing in the FOR(myAsset and item.assetRef), so for clarity I reset my attempts to the provided code example.


texts: What is the correct way to format a module controller action URL?

texts:
Consider the following Craft 3 example module structure:
modules/
    businesslogic/
        controllers/ExampleController.php
        BusinessLogic.php

...and consider the following action in ExampleController.php:
public function actionExampleRoute()
{
    die('in example-route action');
}

Assuming everything is set up and configured correctly, is this the correct URL for triggering the action in ExampleController.php?
http://my-craft-site/business-logic/example/example-route

If so, this is not working for me; it instead results in a 404/Template not found error. I'm not sure if I misunderstand how to determine the correct URL or if I set up something incorrectly.
I am working with the example provided here and I believe I have followed the instructions correctly. The instructions include a simple test of the module, and the test succeeds--I'm just not able to get the controller action to work as expected.


texts: 'cacheDuration' => false, sets cache file expiration date to 1 year

texts:
So I noticed that by setting the 'cacheDuration' => false it seems to set, by default, the expiration date to 1 year from when the cache is saved.

I found this in /app/services/TemplateCacheService.php starting from line 263:

if($duration <= 0)
{
  $duration = 31536000; // 1 year
}

I know a longer duration could be achieved by setting the expiration to something like 4Y. But I wanted to raise this and ask if it was an oversight or what the reason was for setting it to a year and overriding the specific value of not setting an expiration at all...?

Thanks.


texts: Trouble with transliteration in slug caused by hardcoded charmap in craft.js

texts:
I've been struggling with automatic slug generation in Czech language: there are letters such as "š" or "č" and Craft has a charactere map hardcoded in craft/app/resources/js/craft.js, resp. craft/app/resources/js/compressed/craft.js, which tells craft to convert "š" to "sh" and "č" to "zh" for instance.

In Czech language that is not necessary; it's rather bad behavior which I need to change. Letter "š" should become "s" etc.

Is there any systematic way how to configure this character map?

I technically have no problems with rewriting the table, although that solution might either cause errors with automatic updates or my changes could get rolled back with every update - neither being good.

PS: This issue is NOT related to the same thing as here: How to transform German umlauts when creating slugs? - the described behavior is in place even with "limitAutoSlugsToAscii == 1"

UPDATE:

In case this question was not resolved yet or had no solution, here is a minified charmap which works as a hotfix to Craft issues with Czech slugs: http://pastebin.com/pc6etBFu

It works as a drop-in replacement for the same map in craft/app/resources/js/compressed/craft.js. My current version of craft is Craft Pro 2.3.2643


texts:
I'm having some trouble on a fresh install of Craft. I've uploaded all the files to my server and moved index.php (etc) out of the public folder and into the root directory.

I've also changed index.php's $craftPath to this:

$craftPath = './craft';

But I'm still getting a 404 error on the homepage. I've set permissions on the folders, but still nothing.

My file structure looks like this:

Any suggestions..?


texts: How can I place links at the bottom of the site?

texts: is it possible to place my privacy notice and cookies policy in the footer menu?  Is there one and how do I do it?


texts: Check if there is a discount and, is yes, how much

texts:
I would like to do two things in my Craft commerce templates:

In my product template:

Check if there are any discounts available to a specific product.

I have a way to output discounts but need to be able to check if there are any at all because the pricing table would look entirely different for either one of the two cases.

In my shopping cart template:

I would like to check (1) if there are any discounts applied to a line item in the shopping cart and, if there are, (2) I would like to display the discount amount for that line item.

This way, I can avoid showing a zero discount like this:
"Your discount: $0.00"

Thank you for your help.


texts: How give parent in navigation-structure the active tag

texts:
So I have a two-level Navigation in a structure. What I want is to give the parent of my entry (if a parent exists) the active tag.

right now I'm doing that:

{% for nav_item in navigation %}

    {{nav_item.title}}

  {% if nav_item.hasDescendants() %}

      {% for child in nav_item.getChildren() %}

            {{child.title}}

      {% endfor %}

  {% endif %}

{% endfor %}

sadly most children don't share the first segment


texts: Customize elementSelect Field's Modal Table Layout

texts:
I am using the "Select Entry" field (_includes/forms/elementSelect.html) field in a custom plugin to select one of my custom element types.

In my ElementType, I defined defineTableAttributes() and getTableAttributeHtml() to customize the table cells on a index view of the Element.

Now when I am using this Element in a modal view, it displays the same cells as on the index view, but I would like to hide certain fields (like buttons).

Is there a way to customize the returned fields, without building the whole modal myself, like mentioned here?

I saw, that a attribute context gets passed, which is either modal or index, but I don't know how I could access it.

Thanks!


texts: Locked out of my Account, how to get back in?

texts:
This really stressing me out!
When trying to log back in to Craft CMS today after som time my password wouldn´t work. I have not changed it and when trying to reset the password I´m only getting: "There was a problem sending the password reset email."
Is there anyway to find out through eg. my FTP and looking at the backend what the "user/password" is set to and what my reset email is set to?
I have not changed any of this, but since I´m locked out now something must have happened..


texts: Any cloud providers hosting and securing Craft as a service

texts: Are there any PaaS providers out there delivering Craft as a platform continuously updated and secured?


texts: Anyway to extend Craft Entry query search in Craft 3

texts:
I've had to manually do an SQL call to the get correct results but I was hoping there would be a tidier way of achieving this in Craft 3?

$query = ( new Query() )
->select('craft_content.title, craft_entries.id, ( 3959 * acos( cos( radians(' . $latitude . ') ) * cos( radians( field_clubLatitude ) ) *
            cos( radians( field_clubLongitude ) - radians(' . $longitude . ') ) + sin( radians(' . $latitude . ') ) *
            sin( radians( field_clubLatitude ) ) ) ) AS distance')
->from( 'craft_elements' )
->where('field_clubLongitude != "" and field_clubLatitude != ""')
->join( 'LEFT JOIN', 'craft_entries', 'craft_elements.id = craft_entries.id' )
->join( 'LEFT JOIN', 'craft_content', 'craft_elements.id = craft_content.elementId' )
->andHaving('distance < 100')
->orderBy('distance')
->limit(3);


texts: How do I add Alt Image Tags to my photos?

texts: I am trying to figure out how to add alt image tags to my photos. I was under the impression that the "file name" served as the alt image tag in Craft CMS, but no such alt tags are populating...and furthermore...I really have no idea where I can add them. Can I do this from the assets field?


texts: Assign user to group available even though not allowed? (Craft v3)

texts:
Working my way through the CMS to learn in more detail I'm currently at the users / permissions parts of the CMS. Here I just bumped into the following thing I don't understand:

I have a Users Group called 'Content Creators' having these permissions:

One user, being inside this 'Content Creators' group is logged in in the CMS. But for some reason still is allowed to assign and un-assign other users to the 'Content Creators' group. Even though this is not allowed as 'Assign users to "Content Creators"' isn't checked and therefore I would expect this to be prohibited in the group he's in.

I don't get why this user is allowed to assign other users to the Content Creators group even though he is not allowed to do this.

The 'Assign users to "Content Creators"' is disabled in the user-specific permissions of the logged in user too, so it's not overwritten in the personal user settings.

Could anybody here please explain me why he is still allowed to do this?


texts:
I'm pretty new to Twig and I know the level here is far above my question, but thank you in advance...

I'm designing a site with sponsor logos on the homepage, each sponsor is an entry in a channel of sponsors. I have a lightswitch field on the entry page called 'showOnHome'.  I've tried "if" statements and conditionals in the loop, but have only got to where it shows the first entry and breaks the loop.

The following works to get all of the entries,

    {% for entry in craft.entries.section('sponsors') %}
        {% for image in entry.sponsorlogo %}

<img src="{{ image.getUrl() }}" alt="{{ image.title }}"

        {% endfor %}
    {% endfor %}

How do I only get entries where showOnHome == '1'?

Thank you in advance for helping the rookie.


texts: Generate transforms only working on default install (multi-site)

texts:
I have a multi-site setup running within Craft 3. Everything seems to be working nicely, except for image transforms. For example:
The following transform on the default site works correctly:
https://www.default-site.com/index.php?p=actions/assets/generate-transform&transformId=10406

The second-site transform gives an internal server error 500
https://www.second-site.com/index.php?p=actions/assets/generate-transform&transformId=10406

My 'second-site' index.php has the following constants:
define('CRAFT_SITE', 'second-site');
define('CRAFT_BASE_PATH', '/home1/client-dir');
define('CRAFT_STORAGE_PATH', CRAFT_BASE_PATH.'/storage');
define('CRAFT_VENDOR_PATH', CRAFT_BASE_PATH.'/vendor');
define('CRAFT_TEMPLATES_PATH', CRAFT_BASE_PATH.'/templates');

I should note that I'm using Amazon S3 to serve my assets (using the S3 plugin). Also, the assets field is set to relate assets from the default site.
UPDATE: In my log file, I'm seeing the following error:
2020-10-01 20:25:27 [-][-][-][error][Error] Error: Call to a member function getVolume() on null in /home1/client-dir/vendor/craftcms/cms/src/services/AssetTransforms.php:648
Stack trace:
#0 /home1/client-dir/vendor/craftcms/cms/src/services/AssetTransforms.php(603): craft\services\AssetTransforms->_generateTransform(Object(craft\models\AssetTransformIndex))
#1 /home1/client-dir/vendor/craftcms/cms/src/controllers/AssetsController.php(1179): craft\services\AssetTransforms->ensureTransformUrlByIndexModel(Object(craft\models\AssetTransformIndex))
#2 [internal function]: craft\controllers\AssetsController->actionGenerateTransform(11357)
#3 /home1/client-dir/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#4 /home1/client-dir/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#5 /home1/client-dir/vendor/craftcms/cms/src/web/Controller.php(178): yii\base\Controller->runAction('generate-transf...', Array)
#6 /home1/client-dir/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('generate-transf...', Array)
#7 /home1/client-dir/vendor/craftcms/cms/src/web/Application.php(291): yii\base\Module->runAction('assets/generate...', Array)
#8 /home1/client-dir/vendor/craftcms/cms/src/web/Application.php(559): craft\web\Application->runAction('assets/generate...', Array)
#9 /home1/client-dir/vendor/craftcms/cms/src/web/Application.php(270): craft\web\Application->_processActionRequest(Object(craft\web\Request))
#10 /home1/client-dir/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#11 /home1/client-dir/public_html/second-site/index.php(28): yii\base\Application->run()
#12 {main}
2020-10-01 20:25:26 [-][-][-][info][application] $_GET = [
    'p' => 'actions/assets/generate-transform'
    'transformId' => '11357'
]

Craft Version: 3.4.24  Amazon S3 Plugin: 1.2.8
Has anyone else experienced this? Any ideas?


texts: Creating an entry with a hidden title from a frontend form is failing

texts:
I have the Title Format set to {id} and that works fine if I create an entry manually from the CP. But I'm trying to create the entry from a frontend form, and it's erroring on me whether I try to send a title along or not. I know that it's the aspect of the hidden title that is causing the error, because if I allow the section to have a normal (non-hidden) title and add a title field to my form, it succeeds in creating an entry.
        <form method="post" accept-charset="UTF-8">
          {{ csrfInput() }}
          {{ actionInput('entries/save-entry') }}
          {{ redirectInput('/dashboard') }}
          {{ hiddenInput('sectionId', 4) }}
          {{ hiddenInput('enabled', '1') }}
          <input type="submit" value="Next">
        </form>


texts: Flat pricing for different currencies with sales

texts:
I am trying to implement flat pricing for Craft (ie. different fixed prices for products, based on the currency).  I have it working thanks to this post (Craft Commerce: Hard code different product prices based on currency?), but where I am having problems is with applying sales.

The site I am working on has different prices for different currencies.  These are fixed prices that are not based on Craft’s built-in exchange rates for different currencies. For example, a product in Currency A has a price of $100, which is stored in the Commerce’s default price field. However, the price for that product in Currency B has a price of $1000 - and that is stored in a custom text field for that product.

When a person orders a product in Currency B, I intervene on the LineItems::EVENT_POPULATE_LINE_ITEM event and manually set the price to Currency B’s price (from the custom text field on that product).  This works except for when there are sales for that product.

If there is a sale which applies a 10% discount to the product, then Currency A’s price would be $90 (reduced by $10). However, when someone ordering with Currency B buys that product (which is $1000), that price gets reduced by only $10 (instead of $100).  So it appears Commerce is calculating the discount based on Currency A’s price of $100 and applying that to whatever is the line item’s price.

I’ve written a method to calculate Currency B’s final sale price based on the discounts applied to Currency A.

However, it seems the sale’s discount is applied again after the populate line item event so even if I use my method to apply and calculate the correct Currency B sale price, Craft still applies the $10 sales discount again.

Is there a way for me to tell Craft not to apply the sale discount and let me do it manually if a product is being ordered in Currency B?


texts: How to display all fields for an entry within an entry field type?

texts:
I've got a portfolio site I'm building, and on each project's page I'm wanting to show a list of people who worked that project. I created a channel section called "work" with an entry field type called "team". I then created another channel called teamMembers with a plain-text field for their name, another plaintext field for a link to their website, an assets field for their profile picture, and a categories field which would indicate their role in the project. When I'm adding a project as an entry in "work" i have an entries field that allows me to select team members from the teamMembers channel.

For the life of me I can't figure out how to display a list of team members (with each team member's name, link and photo) who worked on a project.

Here's my progress so far: http://dziey3.com/work/polaris

Team

            {% set team = entry.team %}
            {% for asset in entry.teamMembersPhoto.find() %}

            {% endfor %}
            {% for field in team %}

{{ field.title }}

            {% endfor %}

Thanks in advance


texts: Interne Serverfout after one click update

texts:
Hello and good evening,

After the one click update the message 'Interne Serverfout' appears on the screen. One can no longer connect to either the fron or backend of the installation ?

What is the correct procedure to roll back to a working website here ?

-Ruud


texts:
Craft CMS Pricing FAQ

https://craftcms.com/pricing

The FAQ mentions discounts when cost is an issue, presumably non-profit sites.

But… is there a discount for bulk purchasing? Example. 10, 50, 100 licenses?

I can't see an 'official' tier for multiple purchase, is it best to ask?


texts: I can see that craft.request.firstSegment and craft.request.lastSegment works but craft.request.secondSegment does not. Is there a way (as in ExpressionEngine) to get the value of any URL segment?


texts: Saving/assigning User Group via a plugin

texts:
Anyone had experience of assigning a user group when saving or registering a user via a plugin?

Tried various combinations of $user->group = 1, $user->group = [1], $user->setGroups([$group]) and $user->setGroups($group) (where $group is the group I want to assign the user to) but whilst the user is being saved fine the user group is not assigned.

Any thoughts appreciated!

Cheers,

Cole


texts: Retrieve Matrix Field from Related Category in Element API

texts:
I have an API endpoint set up for a category group. This currently provides some details of all entries that have been assigned that category (i.e. related entries). That works well for some high level details, but I now need to add support for a Matrix field that those related entries contain. Here's the current setup:

'series.json' => function() {
            return [
                'elementType' => Category::class,
                'criteria' => ['group' => 'series'],
                'paginate' => false,
                'transformer' => function(Category $entry) {
                    $entries = Entry::find()
                        ->relatedTo($entry)
                        ->select(['slug','title','field_rating AS rating','field_pageCopy AS desc','postDate AS date'])
                        ->asArray()
                        ->all();

                    $typeArray = array_map('strval', $entry->mediaType->all());

                    return [
                        'id' => $entry->id,
                        'slug' => $entry->slug,
                        'title' => $entry->title,
                        'type' => strtolower($typeArray[0]),
                        'desc' => $entry->blurb,
                        'entries' => $entries
                    ];
                }
            ];
        }

However, if I try to add the Matrix field to the select() argument it doesn't work. If I remove select() I can see why: it isn't a listed field. If I remove asArray() then I can see all the relevant fields, but I can't limit the ones available, which is undesirable as it exposes a lot of excess information.

I feel like their might be a better way to format my transformer to begin with, but I'm at a bit of a loss when it comes to the docs.


texts: How to set index page as parent of a structure

texts:
I don't know if it's possible, but what I would like is to have a structure with 3 levels linked to a single entry that would act as the index. The problem is the examples I've seen are only with 1 level structures, so what they do is they set the single index URI as services/ and then the structure URI as services/{slug}. This, for a level 3 structure, gives me services/level3slug.
I want to display the parent URI on the level 3 entries, but if I do services/{parent.uri}/{slug}, I end up having a URI that is services/level1slug/services/level2slug/services/level3slug. When I would just have services/level1slug/level2slug/level3slug.

Is there a way of setting the single page as parent of the structure so I can just do {parent.uri}/{slug}?


texts: Setting a new / override shippingAddress via axios

texts:
I am trying to change/set a customers shippingAddress via axios

It does work e.g. for setting the shippingMethod or the quantity for a product. However if i want to set a new shippingAddress the axios post fails with a 500 status

This is my axios post request:

updateShipping() {
        const options = {
            method: 'POST',
            headers: {
                'content-type': 'application/x-www-form-urlencoded',
                'X-CSRF-Token': window.Craft.csrfToken,
            },
            data: qs.stringify({
                shippingMethodHandle: 'standardShipping', //works
                shippingSameAsBilling: false, // wont work
                shippingAddressId: 'new', // wont work, also tried an existing
                shippingAddress: {
                   firstName: 'test',
                   ...
                },
            }),
            url: '/actions/commerce/cart/update-cart',
        };
        axios(options)
            .then(response => {...})
            .catch(error => {...});
    },


texts: How do I sort and display by a matrix date field?

texts:
I have an entries in a section called 'garden', with a matrix field called 'sowing' - this matrix has a block called 'locationDate' and two fields 'sowingDate' and 'sowingLocation'.

I want to loop through and show the last 5 things sown in the garden, so based on other examples and using low blocks, I have this code:

{% set allSown = craft.lowblocks.blocks.fieldId(12).type("locationDate").order("sowingDate").limit(5) %}
{% set entryIds = [] %}

{% for sown in allSown %}
    {% set entry = sown.title %}
    {% set entryIds = entryIds | merge([entry.id]) %}
{% endfor %}

{% set entries = craft.entries.section("garden").id(entryIds).fixedOrder(true).status("live,pending") %}

{% for sown in entries %}
    {{ sown.title }}<br />
{% endfor %}

So my question is, why can't I view the entries, and what do I need to do to display the date of the matrix field? It seems like it should working, but I am missing something for sure.

** note I need to have a matix date there as there are often multiple sowing locations and dates per entry.


texts: How do you create an alternating layout in a template? i.e. an image on right then an image on left

texts:
I'm a new user so I really don't know how to do this.

I want to create a template that displays the results of a "news" type entry in alternating rows - image on left/text on right - image on right/text on left.

Could someone help in explaining where to put the code and what the code should be?


texts:
I'm trying to output the video files from within a block but get a Calling unknown method: craft\elements\db\AssetQuery::url() error when using the following:
{{ block.video.videoFileWebm.url }}

Assets in this volume have public URLs so I'm not sure why this isn't working.
FULL CODE
{% if block.video %}

                <video {% if block.video.videoAutoplay %}autoplay{% endif %} {% if block.video.videoLoop %}loop{% endif %}

                    {% if block.video.videoThumbnail %}
                    {% set optimizedImages = block.video.videoThumbnail.one().imageVariants16by9 %}
                    poster="{{ optimizedImages.srcset() }}"
                    {% endif %} muted>

                    {% if block.video.videoFileWebm %}
                        <source src="{{ block.video.videoFileWebm.url }}" type="video/webm">
                    {% endif %}
                    {% if block.video.videoFileOgg %}
                        <source src="{{ block.video.videoFileOgg.url }}" type="video/ogg">
                    {% endif %}
                    {% if block.video.videoFileMp4 %}
                        <source src="{{ block.video.videoFileMp4.url }}" type="video/mp4">
                    {% endif %}

This browser does not support the video element.

                </video>

            {% endif %}


texts:
Wondering how to write a conditional that was dependent on the length of a plain text field within a matrix field. I  have something like:

{% for block in entry.pricing %}
    <li>{% if block.destination|length > 25 %}TEST{% endif %}{{ block.smallCost }}</li>
{% endfor %}

Where I’m trying to add TEST if the length of the string of block.destination is more than 25.


texts:
One of my Craft websites is taking a long time (30+ seconds) to load. The /admin area also loads slowly. I have other installs of Craft on the same server that don't experience this problem.

Are there any debugging tools built into Craft to see which part of the site is taking the long time to load?

Some server information:

DigitalOcean instance in SF with 2GB ram
Nginx 1.6.0 (set up through Forge).
PHP 5.5.12-2

I have tried a couple things:

Disabling gzip (I recently enabled it)
Restarting the server
Changing the mysql connection address from localhost to 127.0.0.1 (also tried server IP)
Enabling memcached as the cache type
Clearing cache/rebuild assets/reindex search

The error logs don't show anything unusual.


texts: Exposing current Commerce2 Cart via the Element API

texts:
I want to be able to retrieve the current users Cart via a JSON API endpoint, so I can loop through the products in the cart in JS on the front end.

I've got the Element API plugin installed, but I am not understanding how to grab the current cart from inside the endpoint via PHP. Any help much appreciated.

<?php
use craft\helpers\UrlHelper;
use craft\commerce\elements\Product;
use craft\commerce\elements\Order;

function requireLogin() {
    $currentUser = Craft::$app->user->getIdentity();

    if(!$currentUser) {
        throw new \yii\web\ForbiddenHttpException("You are not logged in");
    }
}

function requireCart() {
    // TWIG would be: {% set cart = craft.commerce.getCarts().getCart() %}
    $currentCart = Craft::WHAT?;
    $cartId      = $currentCart->id;

    if(!$currentCart) {
        throw new \yii\web\ForbiddenHttpException("You don't have a cart yet");
    }
}

return [
    'endpoints' => [
        'cart.json' => function() {
            requireLogin();
            requireCart();

            \Craft::$app->response->headers->set('Access-Control-Allow-Origin', '*');

            return [
                'elementType' => Order::class,
                'criteria'    => ['id' => $cartId],
                'transformer' => function(Order $order) {
                    $items = [];

                    foreach($order->lineItems as $lineItem) {
                        $items[] = [array(
                            'itemTitle' => $lineItem->title
                        )];
                    }

                    return [
                        'items' => $items
                    ];
                }
            ];
        }
    ]
]
?>


texts: Is there a way to localise error messages in Craft Commerce 2?

texts:
I'm using Craft Commerce v2 on a Craft 3 Pro website.

The checkout process of the shop includes a number of forms such as the ones that visitor can use to add or edit shopping and billing addresses. All the templates are based on the demo templates for Craft Commerce and I haven't created any of those input fields using Settings > Fields.

When an error occurs in one of those forms, an error message is displayed as expected under each input field. However, the error messages are not fully localized. For example, if a field is required and the form is submitted without a value for that field, then the error message appears localised except for the title of the required field.

In this error message: The field "First Name" must not be empty.

the name of the field, First Name, is not localized.

e.g. Το «First Name» δεν μπορεί να είναι κενό.

How can I localize the «First Name» part?


texts:
Why do I have to activate the PHP functions: "proc_open" and "proc_close" to backup the database?
I got the error logs:

[error][yii\base\Exception] yii\base\Exception: Could not create backup: proc_open() has been disabled for security reasons in /home/velolade/craft3veloladen_daten/vendor/craftcms/cms/src/controllers/UtilitiesController.php:383
[error][yii\base\Exception] yii\base\Exception: Could not create backup: proc_close() has been disabled for security reasons in /home/velolade/craft3veloladen_daten/vendor/craftcms/cms/src/controllers/UtilitiesController.php:383

After activating these functions in my hoster's PHP settings, it worked.
Is this a security problem for my website?
Thank you very much!


texts: Craft, CSS Frameworks, Bower & Grunt setup suggestions

texts:
I would like to use a CSS Framework like Zurb Foundation with Craft. I also want to manage my bower dependencies and I want to use Grunt to concat and minify my sass/js as well as compress my images. All this good stuff is happening on my local computer running Mamp Pro. I'll then move it to a Staging server once everything is set up.

I have these folders/files in my directory.

.bowerrc
bower.json
-craft
-dev
 -bower_components
 -scss
  .htaccess
  index.php
  robots.txt
-node_modules
-public
Gruntfile.js
package.json

The idea of my workflow is to work in the "dev" folder (html, scss, js) and when it's time to push to Staging server I use grunt to copy/minify/compress into the "public" folder. That way I can send only the "craft" and "public" folders.

If I'm working in the "dev" folder my templates would need to link to the files in the bower_components folders as well as my unminified code. When I publish to the public folder everything gets the minified/concatenated version.

My question concerns templates.
I know that templates are in the "craft" folder. How would I get craft to choose between 2 base _layouts (one built for dev, one built for speed) based on which folder my index.php file is located? Is there a better workflow solution?


texts: Saving matrix field of a duplicate of an entry not working

texts:
I'm creating a cron job to automatically import new entries (vacancies).
I have an entry that I use as a template with some standard data fields and matrix fields. If it's an entry that has not been imported before I create a new entry as a duplicate of the template entry.
$entry = Craft::$app->getElements()->duplicateElement($entryTemplate);

The template already has the matrix blocks but only placeholder data that I want to overwrite like this:
// existing matrix fields (already created or from template)
$matrixBlocks = $entry->myMatrixBlock;

/** @var MatrixBlock $matrixBlock */
foreach($matrixBlocks as $matrixBlock) {
    $matrixBlock->setFieldValues(['contactText' => 'random text']);

    $success = Craft::$app->elements->saveElement($matrixBlock);
}

The strange thing is that the ownerId of the matrixBlock isn't the value of the $entry->id nor is it the value of the template id. It generated a new ownerId.
It works correctly when I import it a second time because the owner id is now correct.


texts: Hiding my plugin table columns for mobile

texts:
My custom plugin uses a table to display each of my results, works as intended. However, on the mobile device the table does not layout properly as the table has 6 columns.

I know this is a rather simple task that can be handled with media queries, but is there a way to use the native CSS/tools that craft provides?


texts: How to exclude some fields from the searchindex using the RegisterElementSearchableAttributesEvent event?

texts:
Context

I had big issues on a Craft 2 multilingual site with dozens of thousands of entries that were using Matrix fields. The site had become extremely slow (almost unusable), especially when recording new data.

This was certainly caused by the searchindex table which handled very massive records (that weren't particularly necessary for the search features of this project).

I am currently working on a Craft 3 site using PostgreSQL and fear the same kind of issues.

Solution

But since Craft 3, and following this post, there is now a RegisterElementSearchableAttributesEvent event that a plugin can listen to modify what gets saved to the search index table when an element is saved.

Problem

I tried to use this event in my CustomModule.php file using this simple test, in order to exclude every fields of the search index:

Event::on(
    Element::class,
    Element::EVENT_REGISTER_SEARCHABLE_ATTRIBUTES,
    function (RegisterElementSearchableAttributesEvent $event) {
        $event->attributes = [];
    }
);

But unfortunately, this change nothing: on save, all the same fields are still saved in the searchindex table.

Question

For a given Section, how can I exclude certains fields (specifically Matrix fields) from the search index on save (both from a CP or a front end entry save)?

Disclaimer: I'm a new to Module development


texts: CraftCMS with Cloudfront Full Page Delivery

texts:
I have a fully static website. All images and videos are currently delivered via aws cloudfront.

Now I am thinking of delivering the HTML via cloudfront as well. My concern is that craftCMS routing will always point to the CDN domain.

How do you preview your content without invalidating the cache? I want my clients to immediately see the changes they made without waiting for 30 minutes (cdn cache expiration).

Any ideas?

edit #1:

I am wondering if relative urls for linking between pages has any pit falls.


texts:
I am trying to put my categories and their children into a Bootstrap navbar. If category has Children it should become a dropdown link.

Here is the code:

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

   {% nav entry in categories %}

{{ entry.title }}
     {% ifchildren %}

       {{ entry.title }}

       {% children %}

{% endifchildren %}

    {% endnav %}

It kind of work except that the top categories appear twice:

once with the dropdown and the children (which I want)
and once without the dropdown.

How could I nest those children without repeating them?


texts: I can't get the first image to show on the homepage

texts:
I'm sure this is a simple question, but I'm a newbie in this, so I'd greatly appreciate all the help I can get! :)

The site is carstensphotos.lumenage.com for now. It's a one page site, so I used the index as the template for the Gallery Section ('gallery'), where the photographer will be able to upload his pics. I'm trying to get the first image of the first entry to show with no success.

Code:

  {% for galleryEntries in craft.entries.section ('gallery') %}

{{ galleryEntries.title }}

  {% endfor %}

   {% for image in entry.galleryPhotos.first() %}

    {% endfor %}

Thank you very much!


texts: Craft SMTP emails + Localhost [Mamp pro] (+postmarkapp)

texts:
Ok I'm running Mamp pro 3.0.5 for my localhost setup and php 5.3.28 and for the life of me, I can't get my localhost setup to send out emails.

My host name is smtp.postmarkapp.com
My username and password are my API key as specified by postmarkapp. I've tried port on both 25 and 2525, Use SMTP authentication is set to yes and SMTP Secure Transport Type is set to none.

When I run a test email through the admin panel I see SMTP connect() failed.

Note: emails send out correct on our dev/production servers without issue.

Anyone have ideas here?


texts: Placing an extra empty linebreak in the Redactor Field

texts:
I've been trying to add extra line breaks to a text field, But this seems impossible?

Most logical thing to do for the user would be to give it an extra linebreak

Those get deleted, sometimes directly, sometimes after opening and then saving again

So far I've tried:

disable cleanup html in the field - still deletes

In the json file settings:

tidyHtml: false - no
cleanSpaces: false - no
removeEmptyTags: false - no
linebreaks: true - this converts ALL breaks to line breaks. Not handy.


texts: Programatically creating a user not appearing in Users index table

texts:
I'm trying to programatically create a user (once the user submits a form through Sprout Forms). The user doesn't seem to appear in the Users section of the CP.

I've ensured the user is being added correctly - I can even see a row in the craft_users database table. Going directly to admin/users/349 (the ID of the newly added user) shows all the user details.

It's been suggested that I need to index the new element data - but not sure how to do this.

$content = $entry->getContent();

$user = new UserModel();
$user->username         = $content['email'];
$user->email            = $content['email'];
$user->unverifiedEmail  = $content['email'];
$user->firstName        = $content['firstName'];
$user->lastName         = $content['lastName'];
$user->newPassword      = $content['password'];
$user->pending          = true;

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

if ($success) {
    craft()->search->indexElementAttributes($user);

    // Assign them to the default user group
    craft()->userGroups->assignUserToDefaultGroup($user);

    // Send the activation email
    craft()->users->sendActivationEmail($user);

    // Update the Element Index
    craft()->search->indexElementAttributes($user);
}


texts: Adding php.ini file to root crashes site

texts:
My client's site is on name.com and in order to change the upload limit, I think i need to place a php.ini file in the web root. But Craft crashes when I add it. The site is fine when I remove it. Anyone know why?

They're uploading video and Craft is giving me the 8MB upload limit problem.

Changing the limit in the Craft config file isn't solving it.


texts:
I'm trying to create a switch statement for a single entry event template that has various entry fields associated with it (description, contact, location, etc.) from an Events Channel I have. Rather than using a bunch of IF's to display only those fields that have been populated, I'm trying to use a switch statement instead, but I can't get this to work when I based the switch on the 'entry.type." I'm trying to something like this, but it's not working. Any help would be appreciated!

{% switch entry.type %}
{% case 'contact' %}
    {{ entry.contact }}
{% case 'location' %}
    {{ entry.location }}
{% endswitch %}


texts: GraphQL two image transforms for same field

texts:
To get image transform in GraphQL we use this

image {
   url @transform ([width: 300, immediately: true])
}

But how do I get two different image transforms (for responsive image) for this asset field?


texts: How can I use two different templates for a single entry?

texts:
I'm building a coursework site and have a Course section, who's entries will be courses containing work that the client will assign to users. I built in both the work itself (different "lessons" sections), and fields for the info page that will be displayed to all users of the site.

How can I use two different templates with the same entry? I need to be able to link to the course.url for the info page, as well as the course.url for the work page within the different templates that use info from the courses.

Currently I have all of the course entries urls going to the info page template. Do I need to create a separate section for course work?


texts: Sprout Forms notification test giving me an internal server error

texts:
We have set up this particular Craft CMS site with smtp details and when testing from the Settings > Email page it works fine.
We've installed Sprout Forms and created some forms - all seems pretty good, but when we test a notification email from within the Sprout Forms admin area we just get an 'internal server' error. No specifics at all. just 'Internal Server error'.
Anybody been through this before?