texts: Craft 2.6 Asset Upload 500 Error (EC2 and Amazon S3)

texts:
Our site is hosted on AWS with assets uploading to an S3. Everything has worked great until the last update. Locally, I can upload assets without issue, but on the stage we're receiving an error /index.php?p=admin/actions/assets/uploadFile 500 (Internal Server Error) preventing us from uploading. The files upload to the directory, but the upload bar hangs.

Within the assets directory when pressing "refresh" on the bucket name, we receive the error /index.php?p=admin/actions/assetSources/getS3Buckets 500 (Internal Server Error)

Craft Version: Craft CMS 2.6.2950

This is the data from the logs.

2016/11/14 12:05:47 [error] [exception.Error] Error: Call to undefined function simplexml_load_string() in /var/www/stage.website.com/craft/app/lib/S3.php:2221
Stack trace:
#0 /var/www/stage.website.com/craft/app/lib/S3.php(420): S3Request->getResponse()
#1 /var/www/stage.website.com/craft/app/assetsourcetypes/S3AssetSourceType.php(438): S3::getBucket('website-craft', 'banners/IR_shar...')
#2 /var/www/stage.website.com/craft/app/assetsourcetypes/BaseAssetSourceType.php(237): Craft\S3AssetSourceType->getNameReplacementInFolder(Object(Craft\AssetFolderModel), 'IR_shareholder_...')
#3 /var/www/stage.website.com/craft/app/assetsourcetypes/BaseAssetSourceType.php(172): Craft\BaseAssetSourceType->insertFileByPath('/var/www/stage....', Object(Craft\AssetFolderModel), 'IR_shareholder_...')
#4 /var/www/stage.website.com/craft/app/services/AssetsService.php(709): Craft\BaseAssetSourceType->uploadFile(Object(Craft\AssetFolderModel))
#5 /var/www/stage.website.com/craft/app/controllers/AssetsController.php(52): Craft\AssetsService->uploadFile('1', NULL, 0, NULL)
#6 /var/www/stage.website.com/craft/app/framework/web/actions/CInlineAction.php(49): Craft\AssetsController->actionUploadFile()
#7 /var/www/stage.website.com/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#8 /var/www/stage.website.com/craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#9 /var/www/stage.website.com/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#10 /var/www/stage.website.com/craft/app/framework/web/CWebApplication.php(282): CController->run('uploadFile')
#11 /var/www/stage.mediatek.com/craft/app/etc/web/WebApp.php(818): CWebApplication->runController('assets/uploadFi...')
#12 /var/www/stage.website.com/craft/app/etc/web/WebApp.php(288): Craft\WebApp->_processActionRequest()
#13 /var/www/stage.website.com/craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
#14 /var/www/stage.website.com/craft/app/index.php(62): CApplication->run()
#15 /var/www/stage.website.com/public/index.php(19): require_once('/var/www/stage....')
#16 {main}
REQUEST_URI=/index.php?p=admin/actions/assets/uploadFile
HTTP_REFERER=http://stage.website.com/admin/assets
---

--

2016-11-14 20:25:28

Level   error
Category    exception.Error
Message Error: Call to undefined function simplexml_load_string() in /var/www/stage.website.com/craft/app/lib/S3.php:2221

We haven't made any system changes, so I'm unsure what the next step is. Any help would be appreciated.


texts: Using { slug } to create subfolders won't work

texts:
I'm running craft locally using MAMP and I'm trying to move assets into a subfolder when unploaded into an image field in my gallery section.

I'm trying to set the path to subfolder so it uses the slug. When I put {slug} into the field settings nothing happens when I upload the images and save the entry, it just pulls them all into the top level folder.

Im not sure if its something in the local file permissions or something but I can bring the images in fine and transforms work okay ie. they create folders and pop the images in fine.

Any help would be appreciated


texts: Option for removing 'transfer content to' when deleting a user?

texts: Is there an easy way of disabling the 'transfer content to' option when deleting a user from the admin portal? In my use case, I want users content to always be completely deleted when they are removed from the site.


texts:
I have a custom plugin where I get a freeform submission by token. I woud like to change a value in this submission and resave the submission. When I try this the old form data gets overwritten.
$submission = Freeform::getInstance()->submissions->getSubmissionByToken($submissionToken);

$submission->setFormFieldValues(['customField' => $customFieldValue]);

// method 1, doesn't accept type submission, should be form
Freeform::getInstance()->submissions->storeSubmission($submission);
// method 2, old data get's overwritten, current submissiontoken changes
Craft::$app->elements->saveElement($submission);


texts: Order entries by content of their fields

texts:
Can I order entries by the content of a field every entry has?

{% for entry in craft.entries.section('entries').order(  *first time field of a matrix block within the entry*  ).all() %}


texts: Craft CMS Graphql orderBy random - pagination?

texts:
How does pagination work with orderBy: 'RAND()' queries?
I've setup a page that loads assets on scroll. If I'm ordering by random, how does offset:2 work? Is each query a new random selection from all assets, in which case repeats are possible?
Should I be passing in asset IDs somehow to exclude already returned assets?


texts: How to override the Craft forgot password email

texts: Struggling to find any documentation on how to override Craft's HTML for the forgotten password email.


texts:
I'm suddenly unable to load my site's assets page. All of my asset sources are local, and loading the main assets page or any source folder or subfolder results in "An unknown error occurred." being displayed. No images are displayed. The assets section of the CP had previously been working fine.

I can still see my assets when uploading an asset within an entry editing screen, though.

The relevant log info (I hope) is below. Seems to be an issue with Imager, which I think was updated recently:

2018-12-10 17:04:05 [-][1][-][error][yii\base\UnknownPropertyException] yii\base\UnknownPropertyException: Getting unknown property: aelvan\imager\models\ConfigModel::imgixEnablePurgeElementAction in /path/to/site/vendor/yiisoft/yii2/base/Component.php:154

Stack trace:

0 /path/to/site/vendor/aelvan/imager/src/Imager.php(154): yii\base\Component->__get('imgixEnablePurg...')

1 [internal function]: aelvan\imager\Imager->aelvan\imager\{closure}(Object(craft\events\RegisterElementActionsEvent))

2 /path/to/site/vendor/yiisoft/yii2/base/Event.php(310): call_user_func(Object(Closure), Object(craft\events\RegisterElementActionsEvent))

3 /path/to/site/vendor/craftcms/cms/src/base/Element.php(320): yii\base\Event::trigger('craft\\elements\\...', 'registerActions', Object(craft\events\RegisterElementActionsEvent))

4 /path/to/site/vendor/craftcms/cms/src/controllers/ElementIndexesController.php(409): craft\base\Element::actions('folder:3')

5 /path/to/site/vendor/craftcms/cms/src/controllers/ElementIndexesController.php(90): craft\controllers\ElementIndexesController->_availableActions()

6 /path/to/site/vendor/yiisoft/yii2/base/Controller.php(155): craft\controllers\ElementIndexesController->beforeAction(Object(yii\base\InlineAction))

7 /path/to/site/vendor/craftcms/cms/src/web/Controller.php(104): yii\base\Controller->runAction('get-elements', Array)

8 /path/to/site/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('get-elements', Array)

9 /path/to/site/vendor/craftcms/cms/src/web/Application.php(282): yii\base\Module->runAction('element-indexes...', Array)

10 /path/to/site/vendor/craftcms/cms/src/web/Application.php(542): craft\web\Application->runAction('element-indexes...', Array)

11 /path/to/site/vendor/craftcms/cms/src/web/Application.php(266): craft\web\Application->_processActionRequest(Object(craft\web\Request))

12 /path/to/site/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))

13 /path/to/site/web/index.php(21): yii\base\Application->run()

14 {main}


texts:
I'm working with Craft Commerce with a set of individual items in a product type and in another, I have packaged sets of the same. The sets (cardSets) have a relation field to select the required individual cards. The code is in the product entry template for the individual card and my intention is to highlight that the single card can be purchased in a set.

I'm using the following code to do a simple reverse relationship but I can't get this to work and I'm not sure if I've got the syntax correct. I'm not seeing any return or error. How do I know if I'm getting an object back?

{% set relatedProduct = craft.commerce.products({
    type: 'cardSets',
    relatedTo: {
        targetElement: product,
        field: 'productsInSet'
        }
}) %}

{{ relatedProduct.title }}


texts:
I'm new to Craft and I'm trying to achieve the following with a Craft Plugin

A user visits my site and can input a zip code to receive the corresponding contact person's name, phonenumber and image. I want to develop a plugin which allows the admin to create the contact person entries in the backend and which handles the ajax request by getting the right contact person form the database.

So for example, the user sends the zip code 54343, an ajax request with that data is sent, the plugin queries the database, converts the result into a json-string and sends the ajax response back.

I'm afraid I have no idea how to start.

How do I create the table and import the data? (There is a CSV document)
Where do I send the ajax request to?
What structures of a Craft plugin do I need?

I'd really appreciate your help.


texts:
We have a matrix field for weekly winners names in a company promotion. We've entered 199 so far, the 200th is not saving, it blanks out the fields and logs a validation error - cannot save because name is blank.

If we delete item 199 then we can add a new item, it then fails on item 200 again

Is this a known limit in craft matrix fields??


texts: Get the type of action and the elements(s) that an action is being performed on when listening to elements.onPerformAction?

texts:
I have a plugin that needs to do something when an entry is deleted. I've recently discovered that the entries.deleteEntry event is not fired when deleting bulk entries (the list view with checkboxes) in the Control Panel (CP). Instead, an elements.onPerformAction event is fired (you can also listen for onBeforePerformAction).

Now that I know that these are the events that are fired when deleting an entry from the list view in the CP, and that I'm working with an Element event instead of a Entry event, I'm struggling to access the type of information I need.

I would like to know...

what type of action is being performed on the element? (Save, Delete, etc.)
how do I identify the entry that the action is being performed on?


texts: Why are my SEOmatic Entry Metas not overriding Sitewide SEO?

texts:
SEOmatic is working as normal locally, but since I put the site up on production the Meta Entry fieldtype isn't overwriting the Site Metas.

I have my

{% hook 'seomaticRender' %}

set up in my head as normal. I've created my Meta fieldset and added it to each entry type. I've set up SEOmatic before and never seen this issue, so I assume I missed something while bringing the site onto the hosting.


texts: Importing members from EE without password reset

texts:
We've rewritten an EE site on Craft and now need to import the members.

My understanding is that since passwords are hashed & not encrypted there is no way to transfer the passwords from EE to Craft without having to force members to reset their passwords.

Is that correct ?


texts: Multiple Craft install configuration in subdomains

texts:
I was playing around that quiet long time, because I didn't want to post the question right away I encounter on some difficulties. But here I go.

The goal

is to have separate craft installs for each subdomain.

The problem

When I hit enter to start installation, I get this The requested URL /admin was not found on this server. Have tried with *index.php?p=admin *, but with no effect.

I've set up virtual host subdomain.craft.dev
Checked, if the host loads anything. It does.
Uploaded public files to subdomain.craft.dev and edited

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

P.S Could I simply use $craftPath = '../subdomain.craft';? I've tried it at first without positive results.
Created folder subdomain.craft above the webroot. In it, uploaded craft folder and set the permission for required directories recursively.
Edited db.php to the needs of Craft's installation.
Run the install by visiting the host address subdomain.craft.dev:8888/admin


texts: Can a JS string variable be used in Twig?

texts:
I've came to the situation where I need to use JS variable string and use it in Twig's variable.

The plan is built on the Guest entries and Ajax form submission. On successful Ajax form submission I'm calling for entry's keys (especially id key) and using these keys to set a cookie names. Those cookie names should be used on next page to get into the entry that just got submitted. Can it be achieved?


texts: Show entry content for other available locales

texts:
We need to part translate a site, and by which i mean only certain sections are available in other locales, and only certain Entries in those pages. In order to display these in the front end we simply want to show :

"This entry is also available in French"

at the base of the entry, and link to a special layout (no nav).

Has anyone achieved this - can the locales be called for each entry ?

Thanks
Dan


texts: How to merge SEOmatic object in Craft 3?

texts:
I'm using SEOmatic plugin in craft cms 3 and I need to set the seoTitle in my template but can't figure out how to do it...

I know that in Craft 2, it was possible to merge the seomatic variable. I tried something like this :

{% set seomatic = seomatic|merge({
    meta: {
        seoTitle: 'my title'
    }
}) %}

But it doesn't work because the merge filter only works with arrays or "Traversable", and I got object... I'm kind of stuck with this issue.

Has anyone ever managed to make a merge of seoTitle?


texts: Cached entries and postDate / expirationDate

texts: How does the {% cache %} tag handle a situation where an entry reaches its post date or expires?


texts: Importing set of flat fields into multi-row matrix using Feed Me

texts:
I'm using 'Feed Me' in Craft 3 to import data. The data has 9 fields (like full_name_child_1, and gender_child_1...) and has 10 sets of them (all the way to full_name_child_10, etc).

I originally mirrored that setup in craft and imported everything fine... but I'd rather have that as one Matrix field with 9 fields (and 0 to 10 row) rather than 90 separate fields with a bunch of nulls.

BUT... Feed Me doesn't seem to support that. In the mapping stage, it only allows you to map to one matrix row...

Has anyone dealt with this before, or can you suggest a workaround? Maybe a way in Craft to populate a matrix with repeated sets of existing field data? Thanks!


texts: Module's control panel sub-navigation is not working properly

texts:
I have a problem with setting up a CP navigation for my module.
In module's init() I declared the following:
Event::on(
    Cp::class,
    Cp::EVENT_REGISTER_CP_NAV_ITEMS,
    function (RegisterCpNavItemsEvent $event) {
        $event->navItems[] = [
            'url' => 'asset-checker-module/broken-links',
            'label' => 'Checker',
            'subnav' => [
                'broken-links' => [
                    'url' => 'asset-checker-module/broken-links',
                    'label' => 'Fehlerhafte Links'
                ],
                'unused-assets' => [
                    'url' => 'asset-checker-module/unused-assets',
                    'label' => 'Nicht verwendete Dateien'
                ]
            ]
        ];
    }
);

So I see my main navigation item, when I click on it, the subnavigation gets expanded, the first element is active. But when I click on the second item, parent item gets collapsed.
I tried to fix it by setting selectedSubnavItem in my template, it did not help.
Any ideas?

Running Craft 3.2.7.


texts: Creating locale-specific entries from plugin

texts:
Can you create an Entry with content only for a specific Locale? For instance, I have U.S. English (en_us) and German (de) locales setup for a section. I want to create entries, but only populate one locale. Is this possible?

$entry = new EntryModel();
$entry->getContent()->title = 'Testing Locale';
$entry->sectionId = '14';
$entry->typeId = '16';
$entry->locale = 'de';
$entry->localeEnabled = true;

$entry->setContentFromPost(array('plainTextField' => 'Test'));

craft()->entries->saveEntry($entry);

The resulting code above creates the entry fine, but content is present for both locales. Is this expected behaviour?


texts:
Just getting starting with templating so apologies if this is obvious. Couldn't find a solution through search.

I have set up two sections. These contain different sets of information.

I have one category group that lists UK counties like so..

Country (Parent)
 - County (Child)
 - County (Child)
 - County (Child)

Both sections have this category group as a category field.

Now I want to create a Category page, but that only lists the entries for the section you are currently viewing.

Lets say for example you are viewing a list of entries, or single entry in section 1.
On an index page I'm displaying the category like so..

{% for category in entry.county.level(2) %}{{ category.title }}{% endfor %}

and on a single page like so...

{% set category = entry.county.last() %}
{{ category.title }}

Now I want to link to the category page plate that will show a list of entries within that category.

I have my category group set up like so...

Now I'm not quite sure how to set this up so that it will only show the relevant sections entries.

Does that make sense?

Please ask if it's not clear and I can hopefully clarify!

Thanks.


texts: Feed Me: How to format JSON for a table field?

texts:
I need to import some data into a table field.

What's the best way to format the data in my original JSON feed?

I've tried this:

[
    "first value",
    "second value",
]

and this:

[
    {"col1": "first value"},
    {"col2": "second value"},
]

But neither of those JSON formats seems to be importing the data properly.

How should I format my data in JSON, so that it may be imported into a table field?

MORE INFORMATION

I've read these docs, but apparently I'm still doing something wrong.

My current JSON looks like this...

"altTitles": [
    {
        "title": "Morke"
    }
]

Where altTitles is my table field, and title is the only column.

I believe I've properly mapped the field...

Yet for whatever reason, the table fields are not populating...


texts: How to create a new Tag group and save it?

texts:
I'm new to the Craft CMS framework and have a question about tags. How can I create a new tag group?
You can create a tag list by hand via the admin panel > settings > Tag Groups > New Tag Group.
This is a way I can't use for plug-in development. So far as I know, I have to use the following code:
    $tagGroup = new TagGroup();
    $tagGroup->name = 'GroupName';
    $tagGroup->handle = 'GroupHandle';


texts: Is there any barrier to using AuthorizeNet CIM gateway in Commerce 1? The vendor/omnipay/authorizenet folder has a CIMGateway class but there doesn't appear to be a corresponding AuthorizeNet_CIM_GatewayAdapter. I'm wondering why it's not supported by default, and how difficult it would be to implement it for a client.


texts:
Very simple request!
All I want to do is to be able to get the full URL of the page & output that in the HTML (for a 'share this page' link).
Can anyone help please?
Many thanks!


texts: How can I relate PDFs and Files using an Element Select field in my custom plugin?

texts: I would like to create an elementSelect form field in my plugin, and can't find an example or description. Can someone help?


texts: Is it possible to limit the title field in an entry?  As with other fields I can adjust so that it only takes a certain amount of characters.


texts:
Is Craft's Search case-insensitive?

(And is there a way to toggle case-sensitivity on/off?)


texts: Craft Commerce: Checkout without email / address

texts:
Is it possible for Users to checkout without an email or address?
I want to give users the option to switch to a payment provider in the cart and fetch the address later via the provider.
Unfortunately I get an error message that no email is associated with the cart \ order.
Is there a way to checkout without an email?
Or Is it possible to edit an Order before passing it to an payment gateway to include an fake email?


texts: How do I query two relationship fields where one relationship MUST be empty?

texts:
I have two relationship fields. I am trying to query all entries where the first field is related to a particular element and the second field is related to nothing. Here is how I thought it would work but it doesn't.

$criteria->relatedTo = ['and',
[
    'targetElement' => anElementId,
    'field'         => 'relationshipOne'
],
[
    'targetElement' => null, // also tried ":empty:"
    'field'         => 'relationshipTwo'
]];


texts: `entry` variable pre-populated on a frontend form

texts:
I set up a single page "Add Post" in the CP.

In following the example here https://craftcms.com/docs/templating/entry-form my form title input field is pre-populated with "Add Post" This is obviously not the desired result. When I include an entry id for modifying the post it grabs the title from the post as it should.

How do I create a new post without having a form pre-populated with "Add Post" in the title input field?

{% macro errorList(errors) %}
    {% if errors %}

            {% for error in errors %}

{{ error }}

            {% endfor %}

    {% endif %}
{% endmacro %}

{% from _self import errorList %}

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


texts: How to loop through Craft CMS query in Angular

texts:
Given the following query sample, how can I loop through the entries past the first array in Angular?

Here is the query sample:

query sample ($section: [String], $type: [String], $slug: [String]) {
entries (section: $section, type: $type, slug: $slug) {
... on sections_sample_Entry {
  pageTitle
  description
  keywords
  canonical
  topBanner
  imageHero {
    ... on imageHero_ImageHeroData_BlockType {
      backgroundImage {
        title
        url
        ... on images_Asset {
         altText
       }
      }
      seal {
        title
        url
        ... on images_Asset {
         altText
       }
      }
      heroTitle
      supertitle
      subtitle
      heading
      bullets
      ctaButton
      }
    }
   }
  }
}

In the Angular template, I'm able to get and display the content within entries before the imageHero, anything after imageHero I have not been able to figured how to loop:

{{ entry.pageTitle }}

{{ entry.description }}

{{ entry.keywords }}

   {{ entry.canonical }}

   {{ entry.topBanner }}

How can I get entries.imageHero.heroTitle for instance?

The data return looks like the following when I console.log this query:


texts: 4 Different HTML from single Craft 3 CMS on 4 different domains?

texts:
Can we serve 4 different HTML from single Craft 3 CMS on 4 different domains?

working on a client project which has their 4 different domains for their different brands of the same business.

Is it possible, if yes how can we achieve it?

Thanks in Advance ..!!


texts: When is Craft 3 ready for commercial use

texts:
We are  trying out some features of the new Craft update and are wondering how ready for use the current version is and if any of you guys are already using it outside a testing environment.

And if not, is there a clear signal of the development team on when to switch to the newer version?

Thanks in advance.


texts: Root domain config overriding subdomain config

texts:
My question is similar to Subdomain database configuration picking up root domain config, but I don't have any custom database variables.

I have a staging site and a (forthcoming) production site on the same remote shared hosting server. The staging site is at a staging subdomain and the production site will be at the root.

The staging site seems to be using the config variables from the root domain in general.php and db.php. I had to take the production site out of db.php to get the staging site to work at all, and anywhere I'm using environment variables (like my asset paths), they're coming from the production config instead.

This is my general.php:

return array(
  '*' => array(
    'omitScriptNameInUrls' => true,
    'generateTransformsBeforePageLoad' => true,
    'loginPath' => 'admin',
  ),
  'localhost' => array(
    'server' => 'localhost',
    'devMode' => true,
    'environmentVariables' => array(
      'basePath' => 'C:\wamp\www\craftcms',
      'baseUrl'  => 'localhost/craftcms/',
    )
  ),
  'staging.safs.msu.edu' => array(
        'server' => '35.8.12.67',
    'devMode' => true,
    'environmentVariables' => array(
      'basePath' => 'staging',
      'baseUrl'  => 'http://staging.safs.msu.edu',
    ),
  ),
  'safs.msu.edu' => array(
    'server' => '35.8.12.67',
    'devMode' => false,
    'environmentVariables' => array(
      'basePath' => '',
      'baseUrl'  => 'http://safs.msu.edu',
    ),
  ),
);

How do I get my config files to recognize the staging subdomain's settings?


texts: We have a tight budget for a new Craft 3 site. How can the paid plugins be filtered from the store, so we can review only the free ones?


texts:
I've been trying to build a category filter. I managed to make my buttons respond with categories but the returned entries on the page stay the same. So when I click one of the links "/?category=koop" gets added to the URL, but my entries don't respond upon that URL. I do have added the categories in the CP and assigned them to my entries.

Here is the code of my filters:

{% if craft.request.getParam('offerCategory') is not null %}

    {% set offerCategory = craft.categories.slug(craft.request.getParam('offerCategory')) %}
    {% set offers = craft.entries.section('offers').relatedTo(offerCategory).find() %}

{% else %}

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

{% endif %}

And my button list

{% for offerCategory in craft.categories.group('offerTypes').find() %}

        {{ offerCategory.title }}

{% endfor %}

I'm quite new to Craft. One of the resources I'm using to build this is: http://craftcookbook.net/recipes/197.

If anyone knows what I'm overseeing, thanks in advance.


texts: How to handle Belongs To User relationship

texts:
In a custom plugin is it possible to have a element type with a belongs to relationship to a user, as you can only define half of the relationship (without somehow modifying the userRecord).

What would be the best practices to get something like this working?


texts: Conditional fields based on structure level

texts:
I have a site that will heavily rely on the structure entry type to allow the client to publish content.

The "1st" level of the structure will always act as a table of contents for its children. The child pages will always contain the actual content (supplied via a matrix field).

- Page A (TOC)
    - Page B (Content)
    - Page C (Content)
        - Page D (Content)
- Page E (TOC)
    - Page F (Content)
    - Page G (Content)
- Page H (TOC)
    - Page I (Content)
- ...

This means that the fields visible in the control panel for level 1 entries need to be different to the fields for level 2 + entries.

Is it possible to have conditional fields based on the structure's level?


texts: How do I reset a user’s password or email them when I create an account?

texts:
Is it possible to reset a users password from the Control Panel, I remember seeing an option for that before but not seeing it anymore?

Same goes for notifing users when you create their account, is there a way to trigger an email to them automatically?

If not maybe a plugin is in order?


texts: Is FeedMe v2 supporting FTP with basic authentication

texts:
I'm currently redoing a import mechanism for a site we've inherited.  I'm trying to use Feedme version 2 for this as opposed to the custom import script that was written (and is not working too well).

The import needs to be transferred via FTP with basic authentication.  I saw that version 1.4.7 included this FTP support and I'm wondering if that includes FTP with basic authentication and if that function is actually at all available in Feedme2


texts:
I created a custom page for account activation failure and I'm telling Craft to route to my custom page by setting the general config setting activateAccountFailurePath. This works as expected.

What I'd like to do is prevent users from being able to directly navigate to the custom account activation failure page. I'd prefer this page only be displayed when Craft routes the user to it. Any suggestions?

Thanks


texts:
I have a super table field (scoreRanges) that has two columns: mx range slider (range) & rich text (summary). Some entries can have multiple rows:

I'm trying search a row in that field that has a range between a certain value. MX range slider saves data ranges to the database text field like 9;20 which is a range from 9 to 20.

Does anyone have an idea of how to search for a row between a certain range? So far I have tried this which returns no results.

{% for range in profile.scoreRanges.range('and', '>=' ~ result.points, '<=' ~ result.points) %}
...
{% endfor %}

On the template side, I have variables like {{ range.range.from }} & {{ range.range.to }} to use.

Update

Currently not ideal. Using a conditional to filter the correct row, but will work now ¯\_(ツ)_/¯

{% for range in profile.scoreRanges %}
    {% if result.points >= range.range.from and result.points <= range.range.to %}

Range: {{ range.range.from }} - {{ range.range.to }}
 Your Score: {{ result.points }}

        {{ range.summary }}
    {% endif %}
{% endfor %}


texts:
Having a weird issue here.

I have a structure field inside my section on my panel which is divided up by headings.

The issue I'm having is that when I try to collapse a heading via the panel, it doesn't have any effect. It doesn't collapse and sometimes it makes a duplicate of itself.

Its a hard issue to explain over text so I've created a small video to show the issue in action.

https://www.youtube.com/watch?v=vv8vToRCUUw&feature=youtu.be

Any help would be appreciated.

Thank you


texts: How to make combination of two field values unique?

texts: I make use of the front-end entry form for an event registration process. The event is the main entry, and every event registration an entry of a related registration section. The challenge is to see whether a user has already been registered for an event. Today, I do that with a database query before the entry form loads. But for some reason, this works not always (for example when users reload the page). How could I make the combination of two fields ("user id" and "registration status") unique? (Normally, I would do that on a database level with a unique index over the two fields.)


texts:
Hello I am building a system in craft cms using the getharvest api. I have 'translated' the php api to support twig. The problem is the getharvest api is really slow (10+ seconds loading time)

I have solved this problem by using the {% cache %} tag
But now my problem is whenever content changes inside the {% cache %} you don't see the updated content but you see the same content as before.

Is there a way I can tell craft to update the cache whenever content changes inside the cache tag?

This is the code I use:

        {% cache globally using key craft.request.getParam('id') %}
            {% set range = craft.harvestapi.setRange %}
            {% set results = craft.harvestapi.getProjectEntries(id, range) %}

            Budget: {{ result.get("data").budget }}

            Uurprijs: {{ result.get("data").get("hourly-rate") }}

                    Werkzaamheden
                    Omschrijving
                    Uren

                {% for project in results.get("data") %}
                    {% set taskId = project.get("task-id") %}

                        {{ craft.harvestapi.getTask(taskId).get("data").get("name") }}
                        {{ project.notes }}
                        {{ project.hours }}

                {% endfor %}

        {% endcache %}

Thanks in advance!


texts:
I have strange issue and cannot find out the solution for that.
I have this field (matrix with some text values): https://imgur.com/a/KaFXubJ

Also I have this entry: https://imgur.com/a/cPMrGul

And this is how it rendered (it shows not value of fields but id of matrix block table): https://imgur.com/a/SR3HgQZ

Here is how it looks like in template: https://pastebin.com/viVbPLqj

I've tried multiple combinations but nothing was solution. Also other fields are works well (fields which not related to "companyInformation" matrix).

So what may I do wrong?


texts:
I'm using plugin Ad Wizard, supported custom fields.

Trying include additional asset field for html5 animated banners.

Here is dump array:

["groupId"]=>
  string(1) "1"
  ["assetId"]=>
  string(3) "144"
  ["url"]=>
  string(14) "http://localhost"
  ["startDate"]=>
  NULL
  ["endDate"]=>
  NULL
  ["maxViews"]=>
  string(1) "0"
  ["totalViews"]=>
  string(1) "2"
  ["totalClicks"]=>
  string(1) "0"
  ["filepath"]=>
  string(0) ""
  ["width"]=>
  int(0)
  ["height"]=>
  int(0)
  ["html"]=>
  string(0) ""
  ["revisionCreatorId":protected]=>
  NULL
  ["revisionNotes":protected]=>
  NULL
  ["_fieldsByHandle":"craft\base\Element":private]=>
  NULL
  ["_fieldParamNamePrefix":"craft\base\Element":private]=>
  NULL
  ["_normalizedFieldValues":"craft\base\Element":private]=>
  NULL
  ["_nextElement":"craft\base\Element":private]=>
  bool(false)
  ["_prevElement":"craft\base\Element":private]=>
  bool(false)
  ["_parent":"craft\base\Element":private]=>
  NULL
  ["_prevSibling":"craft\base\Element":private]=>
  NULL
  ["_nextSibling":"craft\base\Element":private]=>
  NULL
  ["_eagerLoadedElements":"craft\base\Element":private]=>
  NULL
  ["_currentRevision":"craft\base\Element":private]=>
  NULL
  ["_errors":"yii\base\Model":private]=>
  NULL
  ["_validators":"yii\base\Model":private]=>
  NULL
  ["_scenario":"yii\base\Model":private]=>
  string(7) "default"
  ["_events":"yii\base\Component":private]=>
  array(0) {
  }
  ["_eventWildcards":"yii\base\Component":private]=>
  array(0) {
  }
  ["_behaviors":"yii\base\Component":private]=>
  array(1) {
    ["customFields"]=>
    object(craft\behaviors\ContentBehavior)#545 (18) {
      ["bannerHtml"]=>
      NULL
      ["_customFieldValues":"craft\behaviors\ContentBehavior":private]=>
      array(0) {
      }
      ["owner"]=>
      *RECURSION*
    }
  }
  ["id"]=>
  string(3) "282"
  ["tempId"]=>
  NULL
  ["draftId"]=>
  NULL
  ["revisionId"]=>
  NULL
  ["uid"]=>
  string(36) "150f6150-28a2-4237-a2fc-bcd62751fc17"
  ["fieldLayoutId"]=>
  string(1) "7"
  ["structureId"]=>
  NULL
  ["contentId"]=>
  string(3) "382"
  ["enabled"]=>
  string(1) "1"
  ["archived"]=>
  string(1) "0"
  ["siteId"]=>
  string(1) "1"
  ["enabledForSite"]=>
  string(1) "1"
  ["title"]=>
  string(8) "Banner 1"
  ["slug"]=>
  NULL
  ["uri"]=>
  NULL
  ["dateCreated"]=>
  object(DateTime)#542 (3) {
    ["date"]=>
    string(26) "2019-10-08 16:36:46.000000"
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(9) ""
  }
  ["dateUpdated"]=>
  object(DateTime)#544 (3) {
    ["date"]=>
    string(26) "2019-10-09 12:22:32.000000"
    ["timezone_type"]=>
    int(3)
    ["timezone"]=>
    string(9) ""
  }
  ["dateDeleted"]=>
  NULL
  ["root"]=>
  NULL
  ["lft"]=>
  NULL
  ["rgt"]=>
  NULL
  ["level"]=>
  NULL
  ["searchScore"]=>
  NULL
  ["trashed"]=>
  bool(false)
  ["awaitingFieldValues"]=>
  bool(false)
  ["propagating"]=>
  bool(false)
  ["propagateAll"]=>
  bool(false)
  ["newSiteIds"]=>
  array(0) {
  }
  ["resaving"]=>
  bool(false)
  ["duplicateOf"]=>
  NULL
  ["previewing"]=>
  bool(false)
  ["hardDelete"]=>
  bool(false)
}

bannerHtml value all time empty, trying with text field, its working fine, problem only in asset field.

UPD:

This solution works fine:

{% for ad in craft.adWizard.ads.group('TopBannerLeft').orderBy('RAND()').all() %}
    {% set asset = craft.assets().id(ad.assetId).one() %}
    {% if asset.extension == 'html' %}
        <iframe src="{{ asset.getUrl() }}" frameborder="0" vspace="0" hspace="0" width="390" height="80" marginwidth="0" marginheight="0" scrolling="no"></iframe>
    {% else %}
        {{ ad.displayAd() }}
    {% endif %}
{% endfor %}


texts: Is there a way to get the session id from craft.session in a twig template without needing to create a new filter?


texts:
I'm building out a new site and have moved all the existing client asset upload directories into one parent directory.

old site:

/hero/

/books/

/slider/

new site:

/uploads/hero/

/uploads/books/

/uploads/slider/

When adding a redirect in retour how can I set up a regex to catch all images/files in the various directories and point them at the new structure.


texts:
I see the docs here about getting the lat/long of an address from a zip code, city, etc. I am having issues getting the map to render from this info. My code:
{% if craft.smartMap.visitor.ip != '' %}
    {% set locations = craft.smartMap.visitor.coords %}
{% else %}
    {% set locations = craft.smartMap.lookupCoords(90210) %}
{% endif %}

{{ craft.smartMap.map(locations, options) }}

I get:

Undefined index: fieldId

How do I convert the lat/long result into one of the correct location types?


texts: Add entry with the select-entry-modal-field

texts:
So I have a 'Single' that uses entries from different 'Structures'. I can choose one or more entries with the fieldtype. But often I want to select an entry that is not created yet .. so I have to go back create that entry and then select it ..

It would be so much easier if I could just say "create a new entry" right there

What I mean

Is there a plugin for that or anything ?


texts:
I want to search for Entries of the same channel/section based on their type. Let's say, we are a travel company with two types of tours: "guided group" and "private". For group tours, we want trips associated with a particular provider. For private tours, we want trips less than a certain price (this field is N/A for group journeys).

In the controller:

$criteriaFilters = [
    'section'=>'journeys',
    'relatedTo'=> [<ids of the provider>],// Should be for group only
    'price'=>'<10', // Should be for private tour only
];
$criteria = craft()->elements->getCriteria(
    ElementType::Entry,
    $criteriaFilters
);

I need to retrieve them all in an ElementCriteriaModel object, via one SQL query. I don't want to get all private and guided tours separately and then combine them because that doesn't work well with pagination.

What do you think is best to achieve this? (in PHP, not Twig)


texts: Dynamically specify the 'To' email/recipient using Contact Form plugin

texts:
I'm trying to leverage the Contact Form plugin so I can dynamically specify the To email/recipient (via a text input, not as a hidden field).

I've tried via my own plugin to tap into the beforeSend event and also via config (eg https://gist.github.com/cole007/e65f028cc58140ed3b0f6910fc9615d6).

However, the sent message always defaults to send to the recipient specified in the plugin settings. Any thoughts on how to resolve, or if this is indeed possible?


texts: What is the best way to test if a file exists without knowing which file extension a Craft install is using for templates?

texts:
Craft allows users to use whatever template extension they prefer: .html or .twig or something custom.

We can check if a file exists like so:

IOHelper::fileExists($filePath)

Is there any way to know which extension we want to be testing for?  By default Craft supports both html and twig in the supported extensions config setting.

Right now, I have the following which feels a bit clunky:

foreach (craft()->config->get('defaultTemplateExtensions') as $extension)
{
    if (IOHelper::fileExists($template . "." . $extension))
    {
        ...
    }
}


texts: Search return wrong result with special character like @#! in Craft 3

texts: I have implemented search in Craft 3, but it returns wrong result when I enter some special characters like @#!. Is there a way to prevent it?


texts: How to change the message on the homepage

texts:
More newbie stuff.

Here's my index.html

and here's what Chrome is doing

So, where is it coming from because I obviously don't want that message on the homepage?


texts: How to pass an entry's Matrix fields as JSON?

texts:
Have a JSON object that I'm trying to pass to my Javascript through a script tag in my markup like so:

<script type="text/json" id="json-data">
{
  "terms": "{{ entry.termsAgreement }}",
  "sectionHeader": {{ entry.formSection }}
}

However, I'm getting an error that says:

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

formSection is a Matrix field. How can I pass this along to have access to it in Javascript? I tried

JSON.stringify({{ entry.formSection }})

but no luck.

Thanks.


texts: Can't login after restoring production DB locally

texts:
I'm attempting to restore a postgres DB backup on to my local dev environment but I encounter an error when trying to login as the admin user (the salient parts being):

SQLSTATE[23502]: Not null violation: 7 ERROR:  null value in column "id" violates not-null constraint

and

The SQL being executed was: INSERT INTO "sessions"

So it seems as though it correctly authenticates my username and password and then tries to create a new entry in the sessions table but fails to do so because the session service is returning a null value.

Is this interpretation correct?

I'm using redis for my session storage, so I tried clearing the keys from there but it doesn't fix the issue.

I'm really blocked on this one and would appreciate any thoughts!

kind regards,

piaras hoban


texts: I'm getting unexpected output within media queries

texts:
It outputs the same image, which shouldn't and I am suspicious, that it causing it curly brackets followed after media queries and after twig code.

{% set news = craft.entries.section('news').limit(3) %}
{% for news in news %}

            {{ news.promotionNewsText|ucfirst }}

{% endfor %}


texts:
Our university is made up of many small sites.  I'd like to use craft for this.  Love the auto update feature.  I want each site to share template styles (ie. staff directories, document listings, etc.) but I want to be able to update this global library of templates as time goes on so all sites have access to the latest options.  Also being able to make a change to a global navigation and footer and have all sites updated at the same time would be key.

Does anyone have any suggestions on how to achieve this?


texts: Entry form with field translated accross multiple sites

texts:
I've got 2 sites, each with a locale (dutch - nl & french - fr). I've set up a frontend entry form that works nicely for all not translated fields, I am however struggling to get it to accept submissions for the translated field in both languages at once.

So what should the name of my HTML input tag be so I can use a translated field in a front-end entry form ?

EDIT:

As this might not have been clear before, the goal is to be able to send content for both languages in a single form submit. As I understand this will involve some PHP code, which is certainly no problem, but I'm a bit stuck as to what to add where so any pointers are much appreciated.

EXAMPLE

I've got a field with the handle description

I've tried the following input names but without result
 - fields[description][nl]
 - fields[nl][description]


texts: Multisite system messages: change domain in {{ link }}, other than primary domain

texts:
How can I change the domain in the generated {{ link }} in a system email, other than the primary domain?

I have a multi domain setup in craft3, and it works fine everywhere, except ... for the system messages.

For instance, when a user registers using a front-end entry form on a domain other than my primary domain, they receive the correct email, generated by the following template (Admin -> Email Settings -> System Messages):

Hey {{user.friendlyName}},

Thanks for creating an account with {{siteName}}! To activate your account, click the following link:

{{link}}

If you were not expecting this email, just ignore it.

The {{ siteName }} is rendered correctly in the email, but the {{ link }} still points to the primary domain, something like this: https://myprimaryandhtusthewrongdomain/actions/users/set-password?code=nicecode

I use the mailgun adapter to send the mails btw


texts: Remove trailing comma from an output loop?

texts:
I want to create a comma separated list of categories to which an entry belongs, but without the trailing slash on the last element... can't work out how to remove it!

{% for category in entry.mediaType %}
    <b>{{ category.title }}</b>,
{% endfor %}


texts: Is there an issue with debug mode in 2.4?

texts:
We've recently updated and now find that in debug mode we sometimes don't get the expected stack trace on error.

With a 500.twig file in place it displays that, otherwise we get the default Internal Server Error summary view.

Is this something that broke in the recent update?


texts:
I'm working on a plugin to save user profile data. I have a matrix field called addressMatrix, I've made address a matrix because users can save multiple addresses. Every address entry will have the following fields:

streetAddress
city
stateProvince
postalCode
country

NOTE: I did associate the field with users.

All I want to do is to be able to save a new address or update an existing address for each user. I have no idea where to begin.

I've looked at 1 or 2 Stack Exchange posts on the matter but it does not look like anyone else has raised this question. Sorry in advance... I have no code to post as I don't even have a solid starting point.

Thank you for any help you can provide.

UPDATE

Here's the code I have thus far:

// Load the user
$userModel = craft()->users->getUserById($profileDataModel->userId);

// Load the matrix field
$addressMatrix = craft()->fields->getFieldByHandle("addressMatrix");

$block = new MatrixBlockModel();
$block->fieldId    = $addressMatrix->id; // Matrix field's ID
$block->ownerId    = $userModel->id; // ID of entry the block should be added to
$block->typeId     = 7; // ID of block type

$block->getContent()->setAttributes(array(
    'streetAddress' => '1523 Kansas Ave'
));

$success = craft()->matrix->saveBlock($block);

The above does work, but what I'm current stumped on is how to get the type ID programmatically. I should be able to get a block ID by the block handle. Looking through the class reference I don't see it.


texts: Checking if a hidden field exists in freeform

texts:
My client publishes event sign up forms using Freeform 1, under Craft 2.9.

They would these forms to automatically shut down when a certain submission count is reached. The submission count will differ depending on the event/form.

I had planned to let authors add a hidden field to the Freeform composer which specified a maximum number of submissions. Then on the template, check that the hidden field has a value, and use the submission limiting logic.

The problem is I don't know how to check if a hidden field exists hidden fields don't seem to be accessible through the form>pages>rows>fields objects, and render automatically as part fo the form.renderTag function.

Is there a way to check a hidden field exists when rendering a form?


texts:
I have a service called useTR.php. It has a public method exampleService().

In the variables folder I have added the following code in my KGVariable.php (KG is my plugin name)

public function sayHello() {
    return craft()->useTR->exampleService();
}

In my templates folder I have an html that gets loaded after a form submission and that html has the following code.

Thank you {{ craft.KG.sayHello() }} will contact you soon

When this HTML is loaded, I get the following error:

  Twig Runtime Error – Twig_Error_Runtime
  Calling unknown method: craft\web\twig\variables\CraftVariable::keyword()

What am I doing wrong? Kindly help (I am a beginner at Craft). Thanks.


texts: Server-side address validation in Craft Commerce 3

texts: Was wondering how to do this in Commerce 3 as there were a few different older methods discussed here.


texts: Freeform form throws error on submitting hidden field with JSON

texts:
I've been running into a strange error with the Freeform plugin. I have made a form that has a hidden input field which gets occupied with JSON. This JSON data then is decoded in the e-mail notification for correct displaying.
A little more info for clarification:
The user can select multiple products from different product groups on the page. The selected products are put into a JSON object with javascript and the hidden input field is filled/updated on choosing a product.
When selecting 2 or 3 products, the form is submitted successfully and the e-mail notification is sent with the correct data. When selecting more than 3 products (from 1 product group or more, doesn't matter) the form does not submit and the error message is displayed.
I have logged the form.errors object in my code as followed:
{{ dump(form.errors) }}
Which returns the following if the error occurs:
/home/vagrant/sites/citymesh/citymesh_insky-website/vendor/twig/twig/src/Extension/DebugExtension.php:61: array (size=0) empty
Example of the json that is put into the hidden input field:
  "group-1": {
    "name": "Group 1",
    "products": [
      {
        "name": "Start",
        "id": "11087",
        "price": "10",
        "amount": 50
      },
      {
        "name": "Plus",
        "id": "11090",
        "price": "20",
        "amount": 10
      }
    ]
  },
  "group-2": {
    "name": "Group 2",
    "products": [
      {
        "name": "Start",
        "id": "11122",
        "price": "8",
        "amount": 5
      },
      {
        "name": "Plus",
        "id": "11125",
        "price": "12",
        "amount": 10
      }
    ]
  }
}

The Freeform log and phperrors log are empty after this error occurs, so I'm out of ideas what the issue could be. Does anyone have a lead to where the problem might be?


texts: Do tuples exist in twig? If so, how can I create one?

texts: Is there a tuple data structure in Twig? If there is, how do you create one?


texts: Can the Craft CMS admin be blocked from accessing the Internet?

texts:
In our production environment, we have set up a three-tier architecture. Craft CMS is deployed on a server sitting in the private zone. We want to have it serving client browser's request through a proxy server which sits in the DMZ. We want to make sure the app server does not have internet access for security.

However, it seems to us that craft CMS admin page is trying to access the internet. We would like to know why it is doing that and whether this can be disabled.


texts: Is there any vcl file to use with Craft? I saw here an amazing answer about Varnish and Craft and there is a 3.x configuration file but i need a newer one for Varnish 4 and i don’t know Varnish Configuration Language to port it myself


texts: Paginate search results after combining sections in Craft 3

texts:
I have installed the Calendar plugin and I'd like to search across event entries from this plugin and from channel/section entries across the base Craft 3 site.

However, I am getting the usual Limit-Array error when trying to paginate the results.

Is there a method for paginating multiple search results in Craft 3? I haven't come across a way to do this in any current questions or Craft 3 Docs.


texts: Archive Not Returning Correct Date Variable

texts:
I'm using the technique for creating an archive that's in the Craft docs: https://craftcms.com/support/entry-archive

I'm archiving by day, so my code looks like this:

{% set agendaEntries = craft.entries.section('agenda').status('live,pending,expired').limit(null) %}

{% for day, entriesInDay in agendaEntries | group('postDate.day') %}

{{ day | date('Y-m-d') }}

    {% for entry in entriesInDay %}

          {# entry data #}

    {% endfor %}

{% endfor %}

The looping and grouping (heh) works great, but the {{ day }} variable doesn't correctly output the date, instead I get the day-before-Epoch date (1969-12-31).

I don't really understand how the for loop even knows what the day variable is, so I don't know how to troubleshoot.


texts:
I should begin to say that I have no idea really how exactly ajax works. Although I've used it a couple of times with pre-made WordPress plugins. I saw some examples of ajax entry-loading here on Stack Exchange, I tried to make ajax requests in Craft but just ended up with server errors.

My main goal that I want to accomplish is just to have a news-feed that begin to show 5 entries, a button on the bottom that appends five more.

Is it best to use jQuery for the Ajax-request?
How can I load the "next" five entries in a news-feed, so the call doesn't load the latest five entries over and over?
I've seen that you need to build a specific template for ajax-calls. Is there any good examples of those?

If someone got some advice for me how to accomplish this it would make me so happy!
It'd be really nice to learn how it works, so if you got tips of tutorials, working examples, good reads — please share :)


texts: What effect does nesting cache tags have?

texts:
What effect, if any, does nesting cache tags have? It seems like it would be redundant, but are there any inherent drawbacks?

Recently, I can across an instance where I was using the {% cache %} tag in an include to cache a large matrix field. This was very successful at reducing querries and speeding things up on several pages that used that same include.

But one template that included this file used more entries tags so it seemed to make sense to wrap all of them in a cache tag as well. Here's an example.

_includes/article-body.html

{% cache %}
  {% for block in entry.bigMatrixField %}
    ...
  {% endfor %}
{% endcache %}

blog/_entry.html

{% cache %}
  {% for entry in craft.entries.section('blog') %}
    ...(some expensive queries)...
  {% endfor %}

  {% include "_includes/article-body" %}

  {% for category in craft.categories.group('blogCategories') %}
    ...(some more expensive queries)...
  {% endfor %}
{% endcache %}


texts: Why would Craft Commerce only be using the dummy gateway?

texts: This maybe an obvious one but I thought I should document it here. After purchasing Craft Commerce and enabling your payment gateway of choice after disabling the dummy gateway, payments are still being processed using the dummy gateway only.


texts:
Does anyone have any clue why my login page is missing styling. Seems like encoding trouble, but this has been perfectly fine before. I also checked the CSS, which has alot of scrambled content... check out the screenshots.

Front end:

Weird CSS file:


texts: Can I add an enabled-by-default lightswitch field to existing entries?

texts:
I've created a lightswitch field that defaults to "On", and it works fine for new entries, but for all existing entries it is set to "Off". I'm keen to avoid having to manually go through all existing entries switching it to "On" - is there a way of making existing entries respect the default value of this new field (rather than treating the absence of a value for it from when they were created as "Off")?

(Or alternatively: is there an easy way to set a field to "On" for all existing entries?)


texts:
Please someone tell me where I'm going wrong with this. I have a Matrix field called Page Builder (pageBuilder) and have different matrix blocks for outputting information in different ways.

This code in the entry template works fine for every field except for the one called Placement (placement) which is a position select field. I can't for the life of me get it to output anything at all :-(

Please tell me where I'm going wrong on this one as I'm sure it's going to be something stupid with my code syntax somewhere but just can't tell where for the life of me!!

{% for block in entry.pageBuilder %}

{% switch block.type %}

    {% case "textBlock" %}

        {{ block.text }}

    {% case "callToAction" %}

        &lt;h3&gt;{{ block.blockColour }}&lt;/h3&gt; {{ block.text }}

    {% case "sectionBlock" %}

        {{ block.text}}

    {% case "threeColumn" %}

        {{ block.column1 }}
        {{ block.column2 }}
        {{ block.column3 }}

    {% case "smallColumnLargeColumn" %}

        {# CAN'T GET THIS NEXT BIT WORKING #}
        {% switch block.placement %}
                {% case "left" %}

Code to output if left

                {% case "right" %}

Code to output if right

        {% endswitch %}
        {# ----------------------------------- #}

        {{ block.column1 }}
        {{ block.column2 }}

{% endswitch %}
{% endfor %}


texts: How can I create and validate against a url token?

texts:
I am (attempting) to and for the most part succeeding in sending an email from a plugin.

My plugin has a textarea in the settings that allows the user to customize the message. The message looks like this by default:

{{ forms.textareaField({
    label:        "Guest Email Message"|t,
    id:           'guestEmailMessage',
    name:         'guestEmailMessage',
    instructions: "The email message."|t,
    value:        (settings.emailMessage ? settings.emailMessage : "
Use the link below to complete your request.

Regards,
{siteName}
"|t({ siteName: craft.app.siteName })),
    errors:       settings.getErrors('emailMessage')
}) }}

I would like to create something like this:

"
Use the link below to complete your request.

"

My first problem is, I haven't figured out how to properly escape the anchor parameter. I've tried single quote and a backslash \ (that one).

My second problem is how to generate a random token. I'd like to generate a random string or something. I thought something like getUrlWithToken(), but I'm at the twig level and I'm not sure how that translates.

It would be cool if when I visit the link I am sending I have a way to validate that in my template. Maybe it's a case of if the CSRF token matches? I'm not sure where to start.

Thank you for any suggestions!


texts: Best SEO plugin for Craft CMS - SEOmatic vs SEO plugin

texts:
SEOmatic vs SEO plugin (https://github.com/ethercreative/seo) - which one is better? Ignoring the fact that one is paid and one is free.

I'm creating a blog site and I need to also implement SEO related functionalities.


texts:
I'm trying to route the homepage / to a specific template. In my routes.php file, i've tried these two without result:

return array(
    '/' => 'specific/_entry',
    '' => 'specific/_entry',
);


texts:
Site design I am working on the first word of ever page title is bold. The code looks like this;

Discover Riaflex Today

I am struggling to find a simple solution to do this in Craft.

If I setup a simple rich text field then it wraps "p" tags around it. I have tried to used Markdown but this is the same and also end up with ** in the <'title'> output.

Anyone done something similar or can offer a fairly simple approach. I had a quick  attempt at editing radactor but dropped it as it didn't seem to work and remove 'p' tags.

Thanks.


texts: Apply discount on login during commerce checkout process

texts:
I assign users to specific user groups and then I created discounts that are applied to orders based on the user groups that the users are in.

I have a scenario where users add items to their cart while they are not logged in. Then when they are ready to do the checkout I show a login or registration page. The user then logs in and is then redirected to the view-cart page.

When they get to the view cart page there are no discounts applied. Discounts are only applied when an item is added or removed from the cart.

How can I reevaluate and recalculate any applicable discounts based on the user groups the user is in when the user logs in?


texts: Syntax for eager loading assets from multiple matrix block types

texts:
When eager loading assets from within a matrix block like so:

{% set blocks = entry.relatedCategory
                     .with([categoryBlocks.blockType.blockAssetField])
                     .all() %}

What is the correct way of specifying that there are multiple block types to load that asset field from within?

Do you list each one manually:

{% set blocks = entry.relatedCategory
                     .with([
                            categoryBlocks.blockType.blockAssetField
                            categoryBlocks.blockTypeAlt.blockAssetField
                          ])
                     .all() %}

or is there a regex style version available, something like:

{% set blocks = entry.relatedCategory
                     .with([
                            categoryBlocks.{blockType|blockTypeAlt}.blockAssetField
                           ])
                     .all() %}

I have found that wildcarding works:

{% set blocks = entry.relatedCategory
                     .with([categoryBlocks.*.blockAssetField])
                     .all() %}

but this is only usable if all the block types contain the field.

I have read the docs, and looked over previous "eager-loading" tagged questions but not found anything on this.

Any clarification would be much appreciated


texts:
I am looking for a way to send an email based on the products ordered.

I was thinking this needed to be done using custom order statuses. Although, this would require the ability to change the default order status based on product. And with multiple product types ordered, would require the ability to set multiple statuses to an order.

So, at this stage the ideal solution would be a custom email that is sent conditionally based on products ordered.

I have so far been unable to find a solution for this. Any chance this is possible?


texts:
I'm trying to index some asset volumes that I'm creating in a migration. These are local volumes which may already contain files.

I'm hoping to avoid the step where I have to manually update the asset indices after creating volumes.

The following code does not seem to perform the index, am I missing a step? I've studied the controller used by Utilities but I can't see where I'm going wrong.

    $volumeId = Craft::$app->volumes->getVolumeByHandle('myVolume')->id;

    $indexer = Craft::$app->getAssetIndexer();

    $sessionId = $indexer->getIndexingSessionid();

    $indexer->processIndexForVolume($sessionId,$volumeId);

Any help is much appreciated


texts: Can't remove index.php without getting a 404, .htaccess redirect not working, why?

texts: So this is not my first craft build, and basically, it's identical to my last setup on the craft front, I can't see anything wrong, but I can't remove index.php without causing a 404. I've tried the .htaccess fix, not luck. The last site I did simply had "deny from all" in .htaccess, but it didn't need index.php, so I don't see why I would need to change that for it to work? Is there anywhere else I can look for a settings change that might allow for cleaning up the urls?


texts: Craft Commerce: Custom address model validations

texts: How/Where/Can I add more address model validations than just "firstName" and "lastName"...?


texts: Q: Call to member function on null - Freeform (Solspace)

texts:
I am running Freeform 1.9.0 and I have a small plugin that is supposed to save user submission id's to a custom user field. The plugin returns error when it runs after a new user submits a form though.

Here is the error

  Call to a member function getContent() on null

Here is the code

craft()->on(
        "freeform_submissions.onAfterSave",
        function (Event $event) {
            $submission = $event->params["model"];
            $isNew    = $event->params["isNew"];

            $submissionId = $submission->id;

            $user = craft()->userSession->getUser();

            $user->getContent()->submissionID = $submission->getId();
            $success = craft()->users->saveUser($user);

            if (!craft()->users->saveUser($user))
            {
                $errors = $user->getErrors();
            }
        }
    );


texts:
Is there a way to automatically create a 301 redirect on a structure entry if it gets reordered into a new group. For example the original entry lives under /section-1/entry-title and it gets moved to /section-2/entry-title. So if the original url is indexed it gets redirected to the new location without the client needing to do anything.

Thanks for the help


texts:
I am having difficulty moving the user's cart over to being an order. I understand that a cart is essentially an order with isCompleted set to false and no date set but I can't seem to access anything when setting orders = craft.commerce.orders, etc. I can see the cart on the backend along with the guest's email but cannot get orders. I can easily get the current cart and all my products have a price of $0 if that is relevant.

Thanks!


texts: update existing cart via ajax creates new cart

texts:
Running craft cms 2 as a backend with react as the front end I am able to create a cart via an ajax post request to actions/commerce/cart/updateCart.

However, I'm not sure how to then update that cart. Every request to updateCart creates a new cart.

What do I need to pass to updateCart for it to update instead of create a new cart?


texts: Select entry from any locale with Entries Field

texts:
I'd like to be able to create an Entries field that can select from entries from all locales.

Currently it looks like there's the option to choose a single locale or specify the same locale as the source entry.

Is there any way around this?


texts: How can I filter Craft Commerce products by the current price

texts:
Building on from this question How can I filter Craft Commerce products by price

I have a price filter in the store

Using this code works fine for the normal price

{% set queryParams = {
        relatedTo: category,
        defaultPrice: [
            'and',
            '>= ' ~ 0,
            '<= ' ~ 90,
        ]
    }
%}

but defaultPrice does not consider sale prices.

So if a product is normally $99 but it is reduced to $89, it won't be returned

I would have expected defaultPrice to store the current price being charged. So the sale price if it was on sale.

Is it possible to filter by price and include sale prices?

I've spent hours now on something I thought would be simple. It seems the only way to get this information is to get the products and loop through them. Checking for sale prices.

Do I have to create a plugin to make a usable price filter?


texts:
I have a multi site setup for supporting multiple languages in Craft 3.

'/' => German
'/en/' => English

In my general.php I have 'errorTemplatePrefix' => 'error/',

When I enter '/notexisting', my error/error.twig gets called. But when I enter '/en/notexisting', then the default Craft error message gets displayed "Page Not Found, Template not found: notexisting"

How do I get my error.twig called also for other sites?


texts: Validating date fields in a plugin's settings

texts:
I have a plugin that has some settings, some of which are dates. I want to make these fields required, and ensure they are valid dates.

Because of this bug the date attributes are set as AttributeType::Mixed.

I'm using a structure like this and this to set up the attributes on my settings, but I can't get the date fields to be required, never mind use a custom date-validation method.

<?php
namespace Craft;

class My_SettingsModel extends BaseModel
{
    protected function defineAttributes()
    {
        return array(
            'myText' => array(AttributeType::String, 'column' => ColumnType::Text),
            // There are multiple date fields, but for the example:
            'myDate' => array(AttributeType::Mixed),
        );
    }

    public function rules()
    {
        $rules = parent::rules();

        $rules[] = array('myText', 'required');
        $rules[] = array('myDate', 'required');
        $rules[] = array('myDate', 'validDateString');

        return $rules;
    }

     public function validDateString($attribute, $params)
     {
         if ( /*  $this->$attribute is not a valid date  */ )
         {
             $this->addError($attribute, 'Please enter a valid date');
         }
     }
 }

myText is required OK - the form re-displays with an error message if you try to leave it empty.

I have two problems:

myDate is not required - if I leave the date field empty, the form is always successfully submitted, and when I go back to it the field has the date that was previously there.
Ignoring that, although validDateString() gets called, and doing var_dump($this->$attribute) looks something like array(1) { ["date"]=> string(0) "18/01/2016" }, I get "Illegal string offset 'date'" if I try to access $this->$attribute['date']. I'm baffled.


texts: Including customer details in Stripe emails

texts:
I have one of those questions that I have no idea how to phrase…

Basically Stripe is sending an email notification to my client's ‘accounts department’ on successful payment, but it only includes their email address and the value of their order.

What they’ve requested is that it also includes the customer name in the email that goes to the accounts department.

From looking at the details of a Stripe Event I can see that none of the address details are in there, so either we’ve messed up with out integration, or commerce doesn’t send this info?

Is anyone able to shed some light on that?


texts: How do you Paginate if Looping through element queries directly is deprecated?

texts:
I want to create a basic product listing page based on categories. I created a template that dynamically shows all items based on the category that is passed to it based on the help I received here. That solution works great, but I'm getting the Deprecation warning others have received: Looping through element queries directly has been deprecated. Use the all() function to fetch the query results before looping over them.
Here is my solution that works, but throws the deprecation:
{% set query = craft.entries()
    .section('mySection')
    .relatedTo(category)
    .limit(10)
%}

{% paginate query as pageInfo, pageEntries %}

{% for entry in pageEntries %}

{{entry.title}}

{% endfor %}

{% if pageInfo.prevUrl %}Previous Page{% endif %}
{% if pageInfo.nextUrl %}Next Page{% endif %}

I've looked through all the questions and answers here, and gone back to the documentation on pagination, which still uses limit(), but I can't figure out how I can paginate if I'm not able to use limit() and instead have to use all()?
I'm new to Craft so it's entirely possible I'm missing something simple.


texts: ADLDAP plugin in Craft 2.6 - New User Required In Craft Table?

texts:
I'm pretty new to Craft, and we have been trying to implement a front end LDAP authentication to our website at my organization.  I found the ADLDAP plugin and have been testing it with the website.

Here's the link to the AdldapController.php file that seems to have most of the logic for the plugin:
https://github.com/thepitagroup/adldap_craftcms/blob/master/adldap/controllers/AdldapController.php

I was looking at the code in the AdldapController.php file and was wondering if the check for a matching username in Craft is necessary?

To clarify, my organization only desires to authenticate by Active directory.  It looks like this script is also checking to see if the user exists in the local craft user table (line 62). (Am I correct in understanding that this script will put the username/password combo from active directory verbatim into the MySQL table for future use, or is a new craft-only password generated?) Can this block of code be omitted as an 'option?' Pros/cons?

Thanks for any leads or input.


texts: How to reprocess image transforms that already exist in the database

texts:
If I import a Craft DB into my local db, and it has references to image transforms that existed in another environment, it won't recreate them in the filesystem when a page is loaded that asks for one of those transforms. Is there a way to tell Craft to recreate these transforms, or is the only option to retrieve the transforms from the other environment and bring them over?

I tried running ./craft index-assets/all in the terminal but that didn't work. Not really sure what that command is meant for.


texts: Is there a way to output only the first paragraph of a Rich Text field?

texts: I have a rich text output section I want to limit to the first paragraph so I can link to a full version on another page. What's the best way to do this?


texts: specifying section id manually while saving section

texts:
Is is possible to set the "section id" manually by using

Craft::$app->sections->saveSection($section);?

Can we specify the id of a section in an $section array ?


texts: Issues migrating Craft site to a new host

texts:
We've tried moving an existing, live Craft site to a new host (where we currently just have http access via an IP). We simply copied all files (all 'craft' files, the index.php file and our related assets) across to the new host and updated permissions where necessary. We then moved across the DB and updated config settings to connect to it.

However, something is wrong. On the front end we get this message:

Our site is temporarily unavailable. Please try again later.

And when trying to access the CP, all we get is this message:

Oops!

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

No idea what this means. As well, the version that the message references (2670) is the version we have installed on the live site and are trying to migrate across. Any help would be much appreciated - and I can share the dev URL non-publicly if needed.


texts: What would cause an custom element listing to just return everything?

texts:
I'm creating a plugin with its own ElementType, i've been using the Events plugin by P&T for reference, so I thought everything was going fine.

Now when I go to my elements index, I seem to just get a listing for all elements, regardless of anything. What could cause this? I have my element type in my template like

{% set elementType = 'Custom_ElementType' %}

So if I change this to

{% set elementType = 'Entry' %}

I get a list of all entries with the correct sections and whatnot, which is what I expect, but when I change it to the former I get this:

I've obviously overlooked something but I can't figure it out, if anyone else has overcome something similar i'd be grateful for any pointers.

Update

Here is the code i'm using:

Plugin_FooElementType.php

<?php
namespace Craft;

class Plugin_FooElementType extends BaseElementType
{
  public function getName()
  {
    return Craft::t('Foo Element');
  }
  public function getSources($context = null)
  {
    $sources = array(
      '*' => array(
       'label' => Craft::t('All sources')
      )
    );
    return $sources;
  }

  public function populateElementModel($row)
  {
    return Plugin_FooModel::populateModel($row);
  }

  public function defineTableAttributes($source = null)
  {
    return array(
     'id' => Craft::t('ID'),
     'handle' => Craft::t('Handle'),
     'path' => Craft::t('Path'),
    );
  }
}

_index.html

{% extends "_layouts/elementindex" %}
{% set title = "Endpoints"|t %}

{% set elementType = 'Plugin_Foo' %}

{% set tabs = {
  events:    { label: "Events"|t, url: url('events') },
  requets: { label: "Requests"|t, url: url('plugin/foos') }
} %}

Plugin_FooModel.php

<?php
namespace Craft;

class Plugin_FooModel extends BaseElementModel
{
 protected $elementType = 'Plugin_Foo';

 protected function defineAttributes()
 {
    return array_merge(parent::defineAttributes(), array(
        'requestId' => AttributeType::Number,
        'handle' => AttributeType::Handle,
        'path' => AttributeType::String,
    ));
 }

 public function getCpEditUrl()
 {
    $relation = $this->getRelation();
    if ($relation)
    {
        return UrlHelper::getCpUrl('plugin/'.$relation->handle.'/'.$this->id);
    }
 }

 public function getRelation()
 {
    if ($this->relatedId)
    {
        return craft()->plugin->getRelationById($this->relatedId);
    }
 }
}


texts: Trouble saving custom fields onto custom element type

texts:
Im working on a plugin with a custom element type and i have most things working but i haven't been able to get custom fields to save with my elements using setContentFromPost.

I have the record and the model all setup and saving, and it creates rows in both the custom table (inquiries) as well as an entry in the craft_elements table and the craft_content tables but the craft_content table always has blanks for all the fields

I tracked things down to this one line

$inquiry->setContentFromPost('fields');

thats where its supposted to copy all the values from the post variables for fields into the element but i tested it with var dumps both before and after that line and the content isnt attached.

I did the same check in the example "Events" plugin from pixel and tonic and it is in fact that line that attaches the custom field values to that line.

I've also checked the post variable 'fields' and its set properly and its returning an array as expected with content

array(4) { ["jobTitle"]=> string(7) "partner" ["bio"]=> string(47) "
this is a guy

" ["twitter"]=> string(13) "@keithmancuso" ["instagram"]=> string(11) "keithmancuo" }

I even went so far to try and manually attach content to the model and THAT WORKS!  so when i do this:

    $fields = craft()->request->getPost('fields');
    $inquiry->getContent()->jobTitle = $fields['jobTitle'];

It works, job title is saved into the content table, huzza!

but why doesnt

    $inquiry->setContentFromPost('fields');

work for all the fields in the "fields" array.  Do i need to do my own loop around that array?


texts:
I'm using Matrix fields for blog posts. These are made up of text and image block types. I want to pull in only the first image block and a snippet of text from the first text block into the blogs index page for listing the entries.

Adding limit(1) to each block type didn't work.

{% for entry in craft.entries.section('blog').limit(3).find() %}

    {% for block in entry.blogBody %}

    {% switch block.type %}

      {% case "text" %}
      {{ block.text|hacksaw(chars='100', append='...') }}

      {% case "blogimage" %}
       {% for asset in block.image %}

      {% endfor %}

 {% endswitch %}

{% endfor %}

{% endfor %}

{% endblock %}


texts: EVENT_AFTER_SAVE_ELEMENT triggered twice after saving an entry

texts:
I had this weird issue, not sure if that happens to you guys or not.

I'm trying to catch the 'after entry is saved' event, using the following code in my custom module's init() function (The module's code is generated by pluginfactory.io):

Event::on(
    \craft\services\Elements::class,
    \craft\services\Elements::EVENT_AFTER_SAVE_ELEMENT,
    function (\craft\events\ElementEvent $event) {
        $element = $event->element;
        if($element instanceof \craft\elements\Entry) {
            // Craft::info('Entry saved: ' . $element->title, __METHOD__);
        }
    }
);

It seems to work by testing on saving an entry in the CP, but the weird thing is this event seems to be triggered twice according to the log:

2019-08-16 12:21:52 [-][1][-][info][modules\testmodule\{closure}] Entry saved: Document translation
2019-08-16 12:21:52 [-][1][-][info][modules\testmodule\{closure}] Entry saved: Document translation
2019-08-16 12:21:52 [-][1][-][info][application] $_GET = [
    'p' => 'admin/entries/pages/234-document-translation'
]

I also tried Andrew's answer in this post: https://craftcms.stackexchange.com/a/26815/7136, but same thing happened.

Event::on(
    \craft\elements\Entry::class,
    \craft\elements\Entry::EVENT_AFTER_SAVE,
    function (\craft\events\ModelEvent $event) {
        Craft::debug(
            '\craft\elements\Entry::EVENT_AFTER_SAVE',
            __METHOD__
        );
    }
);

I certainly don't want my custom code to be executed twice. Is this a bug or an expected behavior?

Craft version: 3.2.10


texts:
If a user has permission to publish on multiple sites, he by default publishes to all of them. If he wants to exclude some sites, he needs to go in each one and turn off the post for that site. This is ok if you have several sites, but on +100 sites it is a very time consuming task.

It occured to me that we could use one user account for publishing on one site and another for publishing on multiple sites, but again, if you don't want to publish on all 100+ sites, you still have to invest a lot of time to disable the post for unwanted sites.

I found this field type plugin, but i am not sure if it can accomplish what I want.
https://github.com/eastslopestudio/craft3-sites-field

I think something like a list with checkboxes would be ideal for this (like the one in user permissions for Sites) with the current Site being automaticaly initially checked. Or a multi select field maybe.

Is something like that doable?
If not with core Craft then maybe with a plugin?

Thanks in advance for any advice!


texts:
The multisort flag for arrays doesn't work the way I'm trying it. This is how I'm using it.

{% for conv in conversations|multisort(['postDate'],['SORT_DESC']) %}

This is the error I keep getting.

array_multisort(): Argument #2 is expected to be an array or a sort flag

Any ideas?


texts: Trying to show selected categories in a multi select form input

texts:
I have a users form, which they can select their occupations. They can choose multiple values from a multi-select input.

Occupations are categories that are related to users profile.

Here in this code, i can get the values and submit witout any problem,but i cannot show as selected when user returns to form. They should see thier previous selections.

{% set categories = craft.categories.group('occupation').all() %}
<input type="hidden" name="fields[occupation][]" value="">
<select multiple name="fields[occupation][]" class="selectpicker" >

{% for category in categories %}
  {% set selected = currentUser.occupation.all()  %}
  <option value="{{ category.id }}" {% if category.id == selected  %} selected{% endif %} > {{ category.title }} </option>
{% endfor %}

How can i access to selected arrays id value?


texts: List only those months that have entries

texts:
I setup my archive using the Craft demo.  I have a page for each year.

I use MixItUp,(think Isotope) to allow a user to filter entries by month. There are simple hard coded buttons for each month.

How can I loop through the entries and create a button for only those months that have entries?

Update.  I have a loop that pulls all the entries for a given year.  I then use MixItUp (think Isotope) to filter the entries by month.

There is a button for each month that triggers MixItUp.  I want to make the creation of these buttons dynamic.  That is, I want to create a loop that generates a button for only those months that contain entries and create a class with the month's name that corresponds with the month in the class names of the entry cards.

For any given year, the loop would create 1-12 buttons.

{% for month that has > 0 entries %}

<button type="button" class="btn btn-outline-secondary btn-lg"   data-mixitup-control data-filter=".February">Feb</button>

{% endfor %}

Thanks


texts: Difference between chained and batch element queries?

texts:
I apologize if this has been asked or addressed already, but I have a question concerning Element Queries. The docs show two possible ways:

Chained Methods

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

Batch-set Parameters

{% set query = craft.entries({
    section: 'news',
    limit: 10
}) %}

The examples shown above (from the docs) obviously accomplish the exact same thing--but what is the difference, if any?

It is my assumption that the batch-set way of querying elements allows for more options, is that true? And does either way have an effect on performance?


texts:
Looking to setup a public facing, launchpad page that lists out all of the user accounts with a 1 click login.

I realize the security implications of such a page but we need something like this to rapidly test multiple accounts different sections of the site.

What's the best way to create something like this?


texts:
I'd like to Restrict access to Element API endpoint by the current user's group.

Is this possible Using Craft 2?


texts:
how can i modify the login html?
I specifically want to add an image below the title.


texts: Searching for specific MatrixBlocks with either GraphQL or PHP

texts:
I'm building a search for my Craft site right now.
Finding entries is fine. I usually have the structure that one entry is one site in the frontend.
I sadly also have entries that are way longer. So one entry of that can have 9 sites. When I search for something that is in this entry like with PHP
$results = \craft\elements\Entry::find()->search('example')->all();

or
$results = \craft\elements\MatrixBlock::find()->search('example')->all();

I get the full entry and get redirected to the first site of this entry.
Same thing happens with GraphQL and the query:
{
  entries(search: "Example"){
    id
    title
    __typename
  }
}

My problem:
I always get back the full entry, but not the exact MatrixBlock or the exact location of the word.
Is there any way to get the exact location (which entry and where in the entry) of the searched query? Either PHP or GraphQL is fine.
If there's no dynamic way to do that, is there a manual way to loop through the entry and find the exact MatrixBlock in PHP? If I'd do it in GraphQL I'd need to do too many requests and this wouldn't be handleable for the search to be dynamic.
Thanks in advance for any kind of help!


texts: Is it possible to update multiple cart items?

texts: To be more specific I would like to add an "update cart" button so that the visitor can adjust the quantity of multiple cart items without having to click on "update" for each cart item.


texts: Restricting access to fields based on user group

texts: I saw this thread Check user is in User Group / Custom User Permissions had an idea. Can I use USER group to limit who can see the Author dropdown on the entries form? Is this even permitted the craft license. I really need to remove that field from view of two user groups. Also would be nice to be able to limit which fields a user has access to when creating an entry.


texts: How to cache and serve different data to different users using Blitz?

texts:
What strategy should I take when I want to serve different data to different users with (Blitz) cache? Logged in users get one set of prices (that can vary depending on their price group memberships), users that are not logged in don't see prices at all.
I read and implemented a test of Dynamic Content as described in the Blitz Cache documentation, and the result looks promising. Lighthouse says between 97-99 on performance with a 0,6s Fist Contentful Paint, serving gzipped caches from Blitz Storage on the Hyperlane VPS (I will test Cloudflare too).
The question is rather about the potential user experience of having the prices ajaxed into the body of the html document. I've never seen any site do it this way before. Have a look at the result. Pay attention to how the prices appear and the related network events on the right:
https://vimeo.com/507996281/0d16df559d

(I realize that the defaultPrice is passed as a parameter to the productPrice template, and therefore the price is exposed - I've later replaced it with an encrypted string using the free plugin Cryptographer)


texts:
I am running Craft 2 CMS for one website. Its in Norwegian for our client.

Its about SKI School. Where Parents reserves sport dates for there children. In database there are parents profile with there children information, date of birth and names in craft_content.

I need to have on website dropdown, when parents login and go to sport dates, they can choose there children, instead of writing it, they choose also dates when there children participate, and price is multiple for chosen dates, on end they see total for payment, they can reserve, and pay later/or at once?

Is there solution for it. I have twig file for templates.


texts:
Running into a strange issue with the XML sitemap on our site that I'm hoping for help with. Here is example code for the blog section of our site in our sitemap:

{% set blogPosts = craft.entries.find({ section: 'blogPosts'}) %}

{% for entry in blogPosts %}
    <url>
        <loc>{{ filteredUrl(entry.url) }}</loc>
        <lastmod>{{ entry.dateUpdated.w3c() }}</lastmod>
        <changefreq>{{ changeFreq }}</changefreq>
        <priority>1</priority>
    </url>
{% endfor %}

For context, I believe that the sitemap template was built in roughly early December of last year as part of our site redesign. At the time we had yet to import a variety of older posts from our old website blog, but did so after the sitemap had been coded.

I'd like our sitemap to show those old posts created before the early December timeframe but, unless I change the "post date" to be after Dec 2014, the post will not appear. This is true even if I make a modification to the page, thus changing the dateUpdated field (which populates <lastmod>). If I change the post date of an old post to 2015, it will appear on the sitemap (with <lastmod> showing the current date), but if I change it back to 2014, it disappears.

There's no code that I can see in the template that sets a required post date timeframe for appearing on the sitemap.

What can I do to fix this issue?

Thanks!


texts:
Currently I am sorting the entries by an ID:

{% for gallery in craft.entries.section('Gallery').order('available desc').limit(none) %}

but I would like to show the latest entries on top, currently it shows available first but latest entries ones go to the bottom. How can I mix the above code with something like this?

.order('postDate desc') %}


texts: Google Maps plugin - Create map from front-end form

texts:
I'm using the Google Maps plugin for Craft and I'm trying to generate the map via a front-end entry form using address fields but I can't seem to get this to work. If I go into the admin and save the entry I can get it to generate using a Google Map field.

Does anyone have any ideas?


texts: How can I query for entries that have one of two Lightswitch fields enabled?

texts:
I have two Lightswitch fields – lightswitchA and lightswitchB – and I need to pull all entries in a certain section, that have one or both of these fields enabled.

Is it possible to execute such a query with a standard ElementCriteriaModel, or do I need to construct a custom query? If I need to construct a custom query, how would that look (in a template, not a plugin)?

I also need to paginate the results, using the {% paginate %} tag.


texts: Two different lightswitches to add class on body tag

texts:
I'm using a lightswitch field to add a class to my html document body-tag. The field is added to a section  with a handle named "events".

To make this happen, I do this in my _layout.html:

{% if entry.whiteLogoText %}
    <body class="white">
{% else %}
    <body>
{% endif %}

Now I also want to use such a lightswitch for entries of a different section (with a field handle named 'projects').

Should I make a new lightswitch field for this particular section, and if so, how should I print it?

I wanna make sure I don't get two <body>-tags.


texts: Why can't we log items regardless of dev mode?

texts:
Unfortunatley we need to develop an Import plug-in helper with dev mode OFF, for - according to Brad at P&T:

  devMode uses a lot more memory on a given PHP request and importing
  probably already requires significant memory, so my guess is that
  you're running into your php.ini file's memory_limit or
  max_execution_time limits or something similar.

The Import plug-in is definitely a resource pig. We can't get it to work at all in dev mode. But we need to develop a plug-in using its hooks to help with things it can't handle in our situation (tables, dates, switches) so we're in a tough spot.

According to this article:

  If you want a log item to appear regardless of whether devMode is
  enabled, you can pass true as the third argument to the log() method.

SproutActivePlugin::log('Log this with or without devMode enabled.', LogLevel::Info, true);

Is this accurate?

We've tried it. Doesn't seem to work as advertised. Nothing in the logs unless dev mode is turned on. And when it's turned on the Import plug-in hangs up. We're in a tough spot.

What else should we be looking for? What else can we try?

Craft CMS 2.6.2930 / Import 0.8.28 / PHP 5.6.10

EDIT:
We have increased memory_limit 10 fold (1280M)
We have increased max_execution_time 100 fold (30000)
We have increased max_input_time 100 fold (60000)


texts: How do you page through child entries in a structure?

texts:
I am trying to figure out how to page through only the children of the top level section entry being displayed, I have looked at this question but as I say I am after only the children not the siblings.

Is there a prevChild() and nextChild() or something similar I can't see them in the docs.

Response to Bryan

So I would do something like:

{% set prevDatabyteSeries = entry.getChildren().first().getPrevSibling() %}
{% set nextDatabyteSeries = entry.getChildren().first().getNextSibling() %}

{% if prevDatabyteSeries %}

{% endif %}

{% if nextDatabyteSeries %}

{% endif %}


texts: how to uninstall a plugin when there is no cp option

texts:
I want to uninstall a plugin.
I disabled it in CP but there is no option to uninstall this plugin.

So I go to composer and remove it from the required section and run composer update.
This deals with the files but not the database record.

So it's not clear to me the best way to uninstall a plugin in Craft 3. Thru the interface is fine when it works but when there is no option how do you get rid of it?


texts: Dropdown field value getting outputted multiple times

texts:
I have a dropdown field that has three options. In my template, I want to do one thing if option 1 is selected and do something else if option 2 is selected.

Here is what my code looks like:

{% for option in entry.transparentMenu.options %}
    {% if entry.transparentMenu.value == "menuLight" %}

white

    {% elseif entry.transparentMenu.value == "menuDark" %}

black

    {% endif %}
{% endfor %}

The code seems to work but the output is: black black black; I only want black to display once.

What am I doing wrong?


texts: Front End Dropdown Field from Super Table

texts:
I have a single static Super Table Field with some Dropdown Fields.
Is it possible to loop through the values instead of hardcoding each one?
My hardcoded version works without problems but i think a dynamic loop is better for the future.

Here is one example: ('static' is the value of the Super Table btw.)

    Visibility:
    <select name="fields[{{ fieldHandle }}][{{ block.id }}][fields][visibility]">
      <option value="privat"{% if entry.static.visibility.value == "privat" %} selected{% endif %}>Privat</option>
      <option value="public"{% if entry.static.visibility.value == "public" %} selected{% endif %}>Public</option>
    </select>

Would be great, if someone has a idea! Thanks


texts: Get first X paragraphs, then output the rest

texts:
The below is code that works to only show the first paragraph, then show the rest. Is it possible to instead, show the first five or six paragraphs, then show the rest?
{# Split paragraphs using a limit of 2 #}
{% set paragraphs = block.body|split('
', 2) %}

{# Get first paragraph and add the missing closing tag  #}
{% set firstParagraph = paragraphs|first ~ '
' %}

{{ firstParagraph|raw }}

{# The rest of the text is here, due to the limit in the split filter #}
{{ paragraphs|last|raw }}

Wordsmith works for this, but I'm unable to see a way to output the rest of the paragraphs.


texts:
Is it possible to create new tables in Craft when building custom modules or do you need to build a plugin for this?
Modules don't have the special "install" migration. So how does table creation work for modules? Is there a best practice for creating new tables for custom modules?


texts:
How would I enable search in a single section only?

I want my search results template to be used regardless of which search option is used. Ideally I'm looking to pass another value from my search form to the search results to do

{% paginate craft.entries.search(query).section(sectionPassedFromSearchForm).limit(5) as entries %}


texts: Set Entries field in Commerce order on completion

texts:
I'm trying to set an Entries field within a Commerce Order once the order completes.

I've tried using the onOrderComplete event like so;

craft()->on('commerce_orders.onOrderComplete',function($event){
    $order = $event->params['order'];

    $order->setContent(array( 'calculation' => 678 )); // magic number for testing
    craft()->commerce_orders->saveOrder($order);
});

and also;

 craft()->on('commerce_orders.onOrderComplete',function($event){
     $order = $event->params['order'];

     $order->calculation = 678; // magic number for testing
     craft()->commerce_orders->saveOrder($order);
 });

With no luck.

I have also tried setting the field value on the add to cart form with

<input type="hidden" name="fields[calculation][]" value="678">

Again with no luck (I am using MultiAdd so thought it might not be working because of that).

Can anyone point me in the right direction here?


texts: How to create an array of items and fetch them with .all()?

texts:
Is there a way to create an array of items, fetch them with .all() and loop through them?  For example:

{% set array = array|merge([block]) %}

{% for block in gallery.all() %}
{% endfor %}


texts:
I have seen a few questions the same as this, but none with answers that work. I am trying to use redactor to allow for dynamic blog posts to be written by my team. In my redactor set up file I have:

buttons: ['html', 'format', 'bold', 'italic', 'deleted', 'lists', 'image', 'file', 'link'],

AND

imageUpload: true

And yet, the button does not show up when I go into my editor.

Any ideas about what else it could be?