texts: pulling in an image from another section within a matrix loop

texts:
I am trying to loop through a matrix to output three blocks but also I want to pull in 3 images from 3 different sections. The images are asset fields in 3 other sections. should i loop through those sections using craft.entries or craft.assests? below is an example of what i have been trying out. thanks in advance for any help

{% for block in entry.homeMatrix %}
        {% if block.type == "homeMatrix" %}

                    {% for image in craft.assets.kind('image') %}
                    <picture class="box-image">

                            <source srcset="{{ entry.lTopBannerImg.first().url('gridImages480X340') }}" media="(min-width: 45em)">
                            <source srcset="{{ entry.lTopBannerImg.first().url('gridImageOdd559X315') }}" media="(min-width: 28.4375em)">
                            <source srcset="{{ entry.lTopBannerImg.first().url('gridImages560X520') }}">

                    </picture>
                    {% endfor %}

{{ block.url }}

Click to see more information

        {% endif %}
    {% endfor %}


texts: Plugin variables class versus twig functions/filters class

texts:
Is there a particular school of thought on which is best to use?

They both appear to offer the same thing - exposing data and functionality to templates.


texts:
I have a scenario in a plugin where I need to create / check data obtained by reading files. This currently happens on plugin init but isn't completed in time to make use of by other functions.

My plugin needs to parse a few SVG's and stylesheets and create data accordingly. I'am currently checking against a last modified date to avoid extraneous work.

The SVG's and stylesheets are from the website public directory and can be modified by the developer at any time and I would like to avoid any manual interaction within the CP when it comes to parsing these files.

What would be an acceptable way to ensure this data is generated before my plugin attempts to use it?


texts: Using the Guest Entries plugin, how can I allow people to edit/delete?

texts:
I have a form for people offering or requesting to share-a-lift to an event.
I'm using the Guest Entries plugin.

But I need them to be able to edit and delete those entries, as once a pair are matched up they need removing from the list of offers/requests to avoid multiple offers.

I have a page with the list of the lifts on offer or requested and have a link from each of the entries to the form page but with the entryId as segment 2.

How do I code the Delete button? (turns out you can't)

I appreciate that this is not the most secure way of doing things, but the client has been using a similar form/method on their old site and have not had any fraudulent or malicious issues in many years.
If anyone can suggest a more secure method without any logins or registration I'm open to ideas.

The final solution

As you can't delete or edit Guest Entries @carlcs came up with the idea of allowing a second entry (in another entry type) with a common field to the first.

In the template listing all the offers and requests you look for entries from both entry types with a matching field, and if a match is found don't show either. See the code in his answer for the details.


texts: Craft 3: Preventing Element from Saving in Plugin

texts:
I had a simple Password Confirmation validation function in Craft 2. In porting the function to Craft 3, I'm struggling to figure out how to handle the same thing. In Craft 2, all events were consistently handled by setting $event->performAction = false but in Craft 3, only a subset of events have a similar isValid option.

Here is my previous Craft 2 version, triggered on onBeforeSaveUser...

public function confirmPassword($event)
{
    // Only do anything if it is a front end submission
    // Only validates against passwordConfirm if field is present
    if (craft()->request->isSiteRequest()) {
        $password = Craft::$app->request->post('password');
        $passwordConfirm = Craft::$app->request->post('passwordConfirm');
        if (isset($passwordConfirm) && strcmp($password, $passwordConfirm) !== 0) {
            $event->user->addErrors(array('passwordConfirm' => Craft::t('Passwords do not match.')));
            $event->performAction = false;
        }
    }
}

In my attempt to port to Craft 3, right now, I'm listening for EVENT_BEFORE_SAVE_ELEMENT and then doing...

public function confirmPassword(ElementEvent $event)
{
    // Only do anything if it is a front end submission
    // Only validates against passwordConfirm if field is present

    if (Craft::$app->request->isSiteRequest) {

        $password = Craft::$app->request->getBodyParam('password');
        $passwordConfirm = Craft::$app->request->getBodyParam('passwordConfirm');

        if (isset($passwordConfirm) && strcmp($password, $passwordConfirm) !== 0) {

            $event->element->addErrors([
                'password' => 'Passwords do not match.'
            ]);

            // WHAT DO I DO HERE TO PREVENT USER ELEMENT FROM SAVING?

        }
    }
}

When I print out $event->element->errors, it correctly shows the errors. But the element is still saved. Am I missing a step here? Or is there a better way to handle this simple/custom validation?


texts: Archive page - only show posts from certain month

texts:
Using this handy thing (http://buildwithcraft.com/help/entry-archive) to create an archive page, but not quite doing what I need it to do.

Set up as a route to call /year/month, replacing year with current year if not provided and replacing month with most recent month that has posts in it if not provided.

This version will print out all posts from a single year:

{% set entriesInYear = craft.entries.section('pressReleases').limit(null).after(year).before(year+1) %}

{% for entry in entriesInYear %}

{{ entry.title }}

{% endfor %}

And this version will print out the entire year into groups based on month:

{% for month, entries in entriesInYear | group("postDate|date('F')") %}

{{ month }}

        {% for entry in entries %}

{{ entry.getLink() }}

        {% endfor %}

{% endfor %}

But what I need is to only get the posts from the month in the url and am not sure how to get there... basically an entriesInMonth variable as opposed to an entriesInYear.


texts:
Can anyone suggest on how to programatically save fields to a GlobalSet?
I’ve been following this: Programatically Adding Fields to a Layout

But, doesn’t seem to work with a global?

I am doing the following :

Create a new field group - works
Assign fields to field group - works
Create global set - works
Create field layout - works
Create field layout tab - works
Set fields to layout tab - nope

.

// get all the fields from company info fieldgroup
$Fields = $FieldGroup->getFields();
// Get field layout
$GlobalSetLayout = $GlobalSet->getFieldLayout();

// Create tab model
$GlobalSetLayoutTab = new FieldLayoutTabModel();
$layout = craft()->fields->getLayoutByType(ElementType::GlobalSet);
$GlobalSetLayoutTab->setLayout($layout);
$GlobalSetLayoutTab->setFields($Fields);

// Set the tab's fields
$GlobalSetLayoutTab->setFields($fields);

// setTabs() expects an array
$layoutTabs[] = $GlobalSetLayoutTab;

// Now, set the tabs back in the layout.
$layout->setTabs($layoutTabs);

Not sure if part of the issue is because Globals don’t exactly have a “tab”, but looking at others in the database it does seem to have one with the name “Content”


texts: I'm looking to rollback Feedme to a previous version. I can't find any docs or information on Stack Overflow on the best way to go about doing this?


texts:
I have a plugin the imports data from an external database. This is more of a onetime action. But what I've noticed is that when this process runs, I cannot do anything in the admin section anymore. (and its not CPU or apache blocking) All my other requests (on other tabs) are blocked until the long running process is done. Is this normal behaviour? If so,can that be changed with config settings?

Thanks in advance


texts: Add active class to nav created from globals

texts:
I have a simple nav set up using Globals in a table, but I'm struggling to get it to add an active class to only the active page.

The below code adds the nav links, but I need to know what to add to it to get the active class on only the current page.

Need a little help please?

{% if mainNav.navitems|length %}
    {% for row in mainNav.navitems %}

{{ row.name }}

    {% endfor %}
{% endif %}


texts: Update a user image on the front end using Vue.js and Ajax

texts:
Following on from this question I am now looking at adding, deleting and updating a user's image on the front end using Vue.js and vue-resource. I have the delete functionality working no problem but I am having an issue with how I add and upddate a users' image.

Here is my test form code:

<form method="post" action="" enctype="multipart/form-data" accept-charset="UTF-8" @submit.prevent="submitForm">
  {{ getCsrfInput() }}
  <input type="hidden" name="action" value="users/saveUser">
  <input type="hidden" name="redirect" value="/">
  <input type="hidden" name="userId" value="{{ currentUser.id }}">

      Member Image
      <input id="avatar" type="file" name="userPhoto">

  <button type="submit" class="button is-primary">Save Profile</button>
</form>

Looking at the Craft log when you submit the form without Ajax it works successfully and this is the log:

$_POST=array (
  'CRAFT_CSRF_TOKEN' => 'Vq_qS8xUX_Z0d09MHA_n3lFLCse3hLuc5Vx0sREE|b95a7c106acaa1e421d409d2eb708ac2beb18b96',
  'action' => 'users/saveUser',
  'redirect' => 'members/profile/gareth
',
  'userId' => '39',
)

$_FILES=array (
  'userPhoto' =>
  array (
    'name' => 'new-me.jpg',
    'type' => 'image/jpeg',
    'tmp_name' => '/Applications/MAMP/tmp/php/phpfDqUNQ',
    'error' => 0,
    'size' => 395885,
  ),
)

My main question is how do I submit to the $_FILES array using ajax? When I post my form using ajax I get the following Craft log:

$_POST=array (
  'userPhoto' =>
  array (
    'name' => 'me.jpg',
    'type' => 'image/jpeg',
    'tmp_name' => '/Applications/MAMP/tmp/php/phpLha7Uh',
    'error' => '0',
    'size' => '117463',
  ),
  'deleteUserPhoto' => '',
  'userId' => '39',
  'action' => 'users/saveUser',
  'CRAFT_CSRF_TOKEN' => 'Vq_qS8xUX_Z0d09MHA_n3lFLCse3hLuc5Vx0sREE|b95a7c106acaa1e421d409d2eb708ac2beb18b96',
)

Is the only way to handle file uploads on the front end to create your own controller and work things out through that or can I set something within my ajax post that will add to the $_FILES array?

Here is my Vue.js code for review:

Vue.http.options.emulateJSON = true;
Vue.http.options.emulateHTTP = true;

var app = new Vue({
  delimiters: ['@{', '}'],
  el: '#app',
  data: {
    user: {
      userPhoto: {
        'name': 'me.jpg',
        'type': 'image/jpeg',
        'tmp_name': '/Applications/MAMP/tmp/php/phpLha7Uh',
        'error': 0,
        'size': 117463
      },
      userId: '{{ currentUser.id }}',
      action: 'users/saveUser'
    },
  },
  methods: {
    submitForm: function() {

      var data = this.user;

      data[window.csrfTokenName] = window.csrfTokenValue; // Append CSRF Token

      this.$http.post('/', data)
        .then(function(response) {
          // success stuff here
        });
    }

  }
});


texts: Using multiple elementTypes in Element API

texts:
I am currently trying to create an autocomplete search with the element-api. I need results from two different elementTypes:

Product::class
Entry::class

How do I get results out of both elementTypes with only one endpoint?

Thats my working Product::class element-api.php config file:

return [
    'endpoints' => [
        'search.json' => function() {
        // settings
        $phrase = Craft::$app->request->getParam('query');

        $criteria = [
            'search' => 'title:'.$phrase,
        ];

            return [
                'elementType' => Product::class,
                'criteria' => $criteria,
                'paginate' => false,
                'transformer' => function(Product $product) {
                return [
                    'title' => $product->title,
                    'url' => $product->url,
                ];
            },
          ];

        },
    ]
];


texts: Redirect all but certain requests to index

texts:
I have a defined in routes.php a regex that redirects all queries but api to my index template:

return array(
   '<url:(?!api).*>' => ['template' => 'index']
);

I'm trying to exclude robots.txt as well as Google Analytics which is utm_source=analytics_test&utm_medium=referral I've tried the following but it's not quite right:

return array(
   '<url:^(?!api|robots|utm_source)(.*)$>' => ['template' => 'index']
);


texts: File robots.txt needed in Craft package?

texts:
I dont understand why we need the robots.txtfile in the Craft CMS package. I think it is confusing. (I had a problem with Google indexing one of my BETA hidden website because of that.)

Reason : When I initiate my domain name on the hosting it creates automatically a public folder inside the virtual host main folder.

So for example my hosting server make the domain name point to /lamp0/web/vhosts/public/. So I just have to upload craft and public folders below in /lamp0/web/vhosts/.
Then I just have to rename public in htdocs and no need of robots.txt file because craft folder is below domain name root.

# Don't allow web crawlers to index Craft
User-agent: *
Disallow: /craft/

=========================
UPDATE
OK I see now in the Craft install documentation (see below). I missed it sorry.
Perhaps would it be good to insert a README.txt file in the package next to robots.txt file to explain that again :)


texts: Craft CMS with Foundation 6 workflow / installation

texts:
I'm currently making a website with the Foundation 6 ZURB template, and want to connect to Craft CMS, but I'm pretty new at this stuff, and can't figure out wht the right installation and workflow would be.

So questions I'm dealing with:

Should I on my local machine install Craft, and change Foundation to build to that location?
Should I install them alongside each other (i.e. install Craft in the same folder as my Foundation)?
Should I make a fresh installation of Craft somewhere else, and install Foundation within the Craft structure somehow?

I found this on Github that looks interesting:
https://github.com/johanneslamers/craft-workflow

But I don't know how I would take it from there to get my existing Foundation code into the project. Could I just copy it over to this new installation?

Sorry if these are silly questions, but I want to get off on the right foot here. All help appreciated!


texts: Troubleshooting paginated content cached globally

texts: Looks like caching paginated content globally forces any following pages (p2,p3, etc) to just echo the same content as the first page. Using a regular cache tag works as desired, but I don't want to cache the same content across all locales, nor generate new cache any time the same template is accessed through one of the several locales. Has anyone run into this? Is this a problem or am I confusing the functionality of the cache globally tag?


texts:
I'm trying to use php-redis as the session store to my craftcms site.
What I've tried:

apt-get install php5-redis
Edited php.ini with the following:

session.save_handler = redis
session.save_path = "tcp://redis:6379?auth=password”

Still, I don't see any sessions saved in redis.

Can anyone help? Thanks!


texts: Base fieldtype validation working with model validation?

texts:
How can you ensure that the base fieldtype validation (required etc) and error messages are still applied when validating $value via the validate($value) function??

Validate method in fieldtype class:

public function validate($value)
{
    if(is_array($value) && $value['type'] != '')
    {
        $linkModel = $this->_valuetToModel($value);
        $validated = $linkModel->validate();
        return $validated ? true : $linkModel->getAllErrors();
    }
    return true;
}

Validate method of custom model that the fieldtype populates and returns to the template:

public function validate($attributes = null, $clearErrors = true)
{
    switch($this->type)
    {
        case('email'):
            if( !filter_var($this->value, FILTER_VALIDATE_EMAIL) )
            {
                $this->addError('value', Craft::t('Please enter a valid email address.'));
            }
            break;

        case('tel'):
            $regexp = '/^[0-9+\(\)#\.\s\/ext-]+$/';
            if(!filter_var($this->value, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => $regexp))))
            {
                $this->addError('value', Craft::t('Please enter a valid telephone.'));
            }
            break;

        case('custom'):
            if(!filter_var($this->value, FILTER_VALIDATE_URL))
            {
                $this->addError('value', Craft::t('Please enter a valid url.'));
            }
            break;

        case('entry'):
            if($this->value == '')
            {
                $this->addError('value', Craft::t('Please select an entry.'));
            }
            break;

        case('asset'):
            if($this->value == '')
            {
                $this->addError('value', Craft::t('Please select an asset.'));
            }
            break;

        case('category'):
            if($this->value == '')
            {
                $this->addError('value', Craft::t('Please select a category.'));
            }
            break;
        // default:
        //     Craft::dd(parent::validate($attributes, null));
        //     $this->addError('value', Craft::t('Please select a sdfasdfsd.'));
        //     break;
    }

    return !$this->hasErrors();
}


texts: Return all entry types or entry fields for one entry object

texts:
Is there a way to pull out all entry fields for an entry by their handle so they can be looped through?

For example rather than doing each field manually like {{ entry.title }}, {{ entry.description }} and {{ entry.date }}, just do a loop.

{% for field in entry %}
    {{ field.fieldHandle }}
{% endfor %}


texts: Change user's photo to base64-encoded image received via POST

texts:
I'm trying to change a userphoto of a certain user to a base64-encoded imagestring that is supplied in a POST request. I already succeeded in uploading an actual asset that way, however, userphotos seem to be handled in a completely different fashion apparently. While this is supposed to change in Craft3, is there a proper way to achieve what I'm trying in Craft 2.x?

This is what I've come up with so far, it obviously does not work though.

    $postdata = file_get_contents("php://input");
    $posts = json_decode($postdata);

    $user = craft()->users->getUserById($posts->userid);
    if ($user == null){
        return array( "status" => "no user found for id ".$posts->userid );
    }

    $imageData = base64_decode($posts->image);
    $source = imagecreatefromstring($imageData);

    craft()->users->saveUserPhoto($user->id."-".time().".jpg",$source, $user);

Not sure whats wrong really, or how I am supposed to properly achieve what I'm trying to do. I suspect the image file isn't handed over to saveUserPhoto() in the correct way due to the following error message,

  Argument 2 passed to Craft\UsersService::saveUserPhoto() must be an
  instance of Craft\BaseImage, resource given

, but I could be completely wrong with that.

Any ideas?


texts: Anyway to programmatically add default fields to a layout?

texts:
So I've been building my plugin to import product listings directly from Salesforce. So far I've been making progress. However, I've approached another roadblock and I was wondering how I would approach this issue. I want to write some code to add default fields into my product layout (e.g.- Body richtext, Image Asset field),

Someone showed me an example of this function that adds default content for a ProductType

/**
 * @throws \Craft\Exception
 * @throws \Exception
 */
private function defaultProductTypes()
{
    $productType = new Commerce_ProductTypeModel;
    $productType->name = 'Clothing';
    $productType->handle = 'clothing';
    $productType->hasDimensions = true;
    $productType->hasUrls = true;
    $productType->hasVariants = false;
    $productType->hasVariantTitleField = false;
    $productType->titleFormat = "{product.title}";
    $productType->template = 'shop/products/_product';

    $fieldLayout = FieldLayoutModel::populateModel(['type' => 'Commerce_Product']);
    \Craft\craft()->fields->saveLayout($fieldLayout);
    $productType->asa('productFieldLayout')->setFieldLayout($fieldLayout);

    $variantFieldLayout = FieldLayoutModel::populateModel(['type' => 'Commerce_Variant']);
    \Craft\craft()->fields->saveLayout($variantFieldLayout);
    $productType->asa('variantFieldLayout')->setFieldLayout($variantFieldLayout);

    \Craft\craft()->commerce_productTypes->saveProductType($productType);

    $productTypeLocales = \Craft\craft()->i18n->getSiteLocaleIds();

    foreach ($productTypeLocales as $locale) {
        \Craft\craft()->db->createCommand()->insert('commerce_producttypes_i18n', [
            'productTypeId' => $productType->id,
            'locale' => $locale,
            'urlFormat' => 'shop/products/{slug}'
        ]);
    }
}

I've tried to read through to see where I could include extra fields, but I'm a bit lost on where to start. Can anyone provide some insight or approach to this?


texts: Current assets don't display in Add an Asset modal for matrix field; using {owner.slug} in path

texts: For two channels that restricts uploads to subdirectory/{owner.slug}, when I want to add an image in an existing entry, the Add an Asset modal window doesn't list the existing images (this is a matrix field that supports multiple images). All other cases where the restricted directory isn't a dynamic asset folder work fine. I've updated Asset Indexes and Cleared Caches, but still no luck. Any idea what's up? Thanks.


texts: How can I best extend TagModel to add a `count` property?

texts:
I'm attempting to write a plugin to extend tags by adding a count property that'd be useful identifying popular tags, making a tag cloud, and anything else where a count would be useful.

The Goal

What I'd like is to neatly extend TagModel so that interacting with these new count tallies  would be straightforward and as similar as possible to working with tags. For example, pretend superTags is my count-appended set and I'm getting the top ten tags for a site across sections:

{% for tag in superTags.limit(10).order('count desc') %}
    {{ tag.name }} has been used {{ tag.count }} times.
{% endfor %}

...or getting the top 10 tags by a blog author:

{% for tag in superTags.channel('blog').relatedTo(author).limit(10).order('count desc') %}
    {{ tag.name }} was born in {{ tag.dateCreated | date('Y') }}.
{% endfor %}

The Problem

I humbly admit that I'm struggling to see the big picture. For example, this works fine (my plugin's called Taggregate):

{% set tags = craft.tags.find() %}
{% set superTags = craft.taggregate.appendCounts(tags) %}
{% set superTags = craft.taggregate.sortByCount(superTags) %}

{% for tag in superTags %}
    {{ tag.name }} has been used {{ tag.count }} times.<br>
{% endfor %}

I've got a TaggregateModel that extends TagModel only to merge in a count Number to defineAttributes(). My Service takes the tags array, then spits out a new one with TaggregateModel objects that include the count property. (Each count is just a tally from craft_relations with no regard for other parameters like section or author—later I intend to use an aggregate table as Brad suggested, even though that's irrelevant here.)

TaggregateService

...

public function appendCounts($tags)
{
    $superTags = array();

    new TaggregateModel($tags);

    for ($i=0; $i < count($tags); $i++)
    {
        $superTags[$i] = new TaggregateModel($tags[$i]);
        $superTags[$i]->count = $this->getTagCount($superTags[$i]->id);
    }

    return $superTags;
}

public function getTagCount($tagId)
{
    $q = craft()->db->createCommand('SELECT count(*) as count FROM craft_relations WHERE targetId = '.$tagId)->queryAll();

    // TODO: get stored aggregate if it exists, otherwise count and store

    return $q[0]['count'];
}

public function sortByCount($tags)
{
    usort($tags, function($a, $b)
        {
            return $a->count < $b->count;
        }
    );

    return $tags;
}

...

While this works, it's clearly bad design:

The Twig interface is specific to the plugin's weird version of non-native methods.
This superTag array isn't smart enough to do any of the cool things that TagModel can.

The Question

Is there a more sensible way to build this so I can hit my ideal usage outlined in "The Goal" above? I'm not looking for somebody to write this for me, just some big-picture guidance since I suspect I'm making this harder than it should be.

...or is my seemingly-simple objective actually complicated?


texts:
I'm working on a typical craft blog with articles. I know there is a plugin that was used to teach craft plugin development that tracks entry visit counts here:

https://straightupcraft.com/craft-plugins/entry-count

However, is there anyway to distinguish the visits made in the last 24 hours? The docs on this simple plugin doesn't talk about it. The logic would probably be take the view count now and subtract by the count from 24 hours ago. I'm guessing the view count might be a value in the mysql table that keeps getting updated. If each count is a row in the table then perhaps there are ways to just query the db for counts associated with an entry filtered by the time stamp. But I highly doubt thats how the plugin is implemented.

I also could use help tracking the posts with the highest upvotes using the upvote plugin:

https://straightupcraft.com/craft-plugins/upvote

I'm doing this to work out a trending logic. Trending posts are posts that have a combination of highest view count and upvotes in the last 24 hours.


texts:
Hi guys so I am having an issue with the "generating pending image transforms" being stuck.

I've seen the solution listed here https://craftcms.com/support/stuck-tasks telling me to go to the craft_tasks table and fix the error. But I cannot for the life of me figure out how to get to this table. Where is it? No one seems to explain this.


texts: Imagick installation passed with warnings

texts:
I have installed imagick on my amazon lightsail lamp instance like so:

apt-get install imagemagick
apt-get install php5-imagick

Unfortunately craft tells me that the ImageMagick extension has Passed with warnings. See this image:

What am I missing? How do I make sure imagick is working correctly?


texts: Verbb Comments plugin - Can't see comment replies

texts:
I recently installed Verbbs Comments plugin on my Craft site, which seems all well and good except that I can't toggle the comment replies. ('2 comments' when clicked does nothing)

Everything else works fine but that. I'm currently using the sample CSS and JS which was provided on their website.

I have also tried the AJAX version provided on this page:

https://verbb.io/craft-plugins/comments/docs/feature-tour/example-css-js

Not trying to override anything on this plugin, just want to get the sample up and running.

Also, no error in console.


texts: Tasks runs only after admin is logged in

texts:
I have a plugin which runs a task on order complete. The tasks runs successfully without any errors. But the problem is the task is only completed when admin is logged in. So if someone has completed the order, they have to wait until an admin logs in to dashboard. What could I be missing? The code I'm using is :

CustomPlugin.php

craft()->on('commerce_orders.onOrderComplete', [$this, 'initializeTask']);

public function initializeTask(Event $event){
    $order = $event->params['order'];
    foreach ($order->lineItems as $lineItem) {
        craft()->tasks->createTask('Custom', null, [
            'id' => $order->id,
        ]);
    }
}

CustomTask.php

class CustomTask extends BaseTask
{
    protected function defineSettings()
    {
        return [
            'id' => AttributeType::Number,
        ];
    }

    public function getDescription()
    {
        return 'Custom Task';
    }

    public function getTotalSteps()
    {
        return 1;
    }

    public function runStep($step)
    {
        $orderId = $this->getSettings()->orderId;
        .
        .
        .
        return true;
    }
}

Is there any type of priority or setting that needs to be set?


texts:
I'm trying to check to see if a particular category (In a loop) exists in a query submitted from a search form.

At the moment I'm doing this inside a 'childCategory' loop...

{% for childCategory in childCategories %}

    {% for category in query %}{% if childCategory.slug == category.slug %} checked{% endif %}{% endfor %}

{% endfor %}

EUGH right?

Is there a better way (Surely!) to check to see if the cateogry exists? I've tried the length and indexOf filters as well as an IN conditional. Nothing works.

The query is being set like this:

{% set query = craft.request.getParam('category') %}
{% set queryCategories = craft.categories.group('opportunities').slug(query) %}


texts: Custom Asset Source Types - not possible

texts:
I would love to extend Craft with a custom AssetSourceType. However it looks like components of type 'assetSource' are not extensible (enableForPlugins = false).

Is there a way to do this?
Or can I simply swap core services in the common.php without hacking the core?

My goal is to provide a 'S3CompatAssetSourceType' - the main difference to the S3AssetSourceType is the API endpoint.

Thanks.


texts:
I have a page that is supposed to render the content and then force a download of a file.

I have {% header "Location: " ~ entry.files[0].url %} in my template which brings up the browser's save dialogue window, but then the page doesn't render.

Is there a way I can delay the setting of the {% header %} tag until after the page has rendered? Or is there a better way of doing what I'm trying to achieve?


texts:
I've come across not a deal breaking problem - but an issue that will cost allot of time.
When I try to compress the craft folder (so I can upload it to a server) using windows:
Send to >> compressor >> I am given an error:

"File not found or no permission"

I did a bit of looking around and re-ran the compressor on win-zip - this allowed all but the files in VENDOR/BIN to be compressed so I would assume the problem is lying there.

So my question is -
Why is there a permission error here?
And are these files required (as in, do these files carry anything vital to craft)
Feel free to ask any follow up questions you might have if you need calcification, I will be happy to answer.
Side note - I am doing this to avoid using FTP - as FTP uploading/downloading a craft site is taking around an HOUR and its lost time I cannot justify.
Thanks in advance -
Wally


texts:
I have categories in my cms.

How do I gets a list of these value into my templates?

Thanks.


texts: Excluding a single Entry ID of an Entry Type from craft.entries

texts:
Any help here would be appreciated… I feel like this is really close.

I have 4 entry types, all of which are shown in a blog index:

Article
Video
Image
Blurb

The most recent entry of the Article type should always be shown as a "featured article" at the top of the page and never repeated again; all the other entry types should appear below this single featured entry in chronological order. The featured article should only appear on the first page of the index, and never appear on subsequent "pages" because this page also uses infinite scroll.

The problem is that the featured article shows up again on all pages past the first. When I remove pagination, but use the same nonFeaturedIds parameter to get my entries, everything works perfectly.

In other words, it seems that the "featured article," is not properly being excluded from Pagination by the entry paramaters I've set up.

Thank you!

{# Define a variable for all the post types #}
  {% set allIds = craft.entries.section('news').ids() %}
{# Define a variable for the featured article: the first occurance of the article entry type #}
  {% set featuredId = craft.entries.type('article').limit('1').ids() %}
{# Define all other entries and entry types as non featured #}
  {% set nonFeaturedIds = allIds|without(featuredId) %}

{# Get the featured entry #}
  {% for entry in craft.entries.id(featuredId) %}
    {% include '/partials/_featuredArticleTemplate' %}
  {% endfor %}

{# set paramaters on an elementCriteriaModel to get all non featured articles and paginate #}
  {% set entries = craft.entries.id(nonFeaturedIds) %}
  {% paginate entries.limit(10) as pageCount, nonfeatured %}

{# Take us to 404 if the page doesn't exist. Otherwise, Infinite scroll keeps repeating the last page of content. #}
  {% if craft.request.getPageNum() > pageCount.totalPages %}
    {% exit 404 %}
  {% endif %}

{# load up the templates for each entry type #}
  {% for entry in nonfeatured %}
    {# all the other articles #}
    {% switch entry.type %}
      {% case "article" %}
          {% include '/partials/_articleTemplate' %}
      {% case "video" %}
        {% include '/partials/_videoTemplate' %}
      {% case "image" %}
        {% include '/partials/_imageTemplate' %}
      {% case "blurb" %}
        {% include '/partials/_blurbTemplate' %}
      {% default %}
    {% endswitch %}
  {% endfor %}

{# infinite scroll loading area #}
  {% if pageCount.nextUrl %}
    {# pagination styles #}
  {% endif %}


texts: Apply custom filter on the entries in admin control panel using custom plugin in craft cms 3.5

texts:
I was referring to Filter entries in the CP based on custom permission and Filter entries in the CP based on custom permission
It seems onBuildElementsQuery was available only in 2.x.
Is there any alternative for craft 3.x?


texts: Unable to edit single or structures, channels working fine after update to Craft 3

texts:
Working in devMode, when trying to edit an existing single or structure entry, I get an InvalidArgument error

yii\base\InvalidArgumentException: Syntax error. in ...vendor/yiisoft/yii2/helpers/BaseJson.php:133

if (isset($availableErrors[$lastError])) {
    throw new InvalidArgumentException($availableErrors[$lastError], $lastError);
}

I notice in Chrome tools I get a bunch of Craft is not defined errors any ideas?


texts: Append a placeholder value to a text input field when form is submitted

texts:
I have a Matrix field in my Craft control panel which contains content which creates a front end form.  If the form field has a placeholder text entered in my Matrix field, I would like that text to be submitted along with the user's text input.

If the user entered "100" in the front end form text input field, and my placeholder text is "bpm", the result I would like submitted is: "100 bpm".

Here's my text input field form code:

<input type="{{ row.inputType }}" name="{{ block.fieldName }}" class="gui-input" placeholder="{{ row.label }}">

Here's a screenshot of my Matrix field:

Here's a screenshot of my front end form:

I tried adding a hidden input field below the text input field but the problem I ran into is that all placeholder text is submitted regardless of whether the user actually filled out a field.

<input type="hidden" name="{{ block.fieldName }}" value="{{ row.label }}">

So let's say that the user filled out the "fetal heart rate" text field but did not fill out the "estimated gestational age". Using the hidden text field both "bpm" and "weeks" is submitted even if the user didn't fill out the "estimated gestational age" field.

Summary of my question: Is there a way to conditionally append a value along user text input? Example, if the user entered "100" for "fetal heart rate" in the front end form text input field, and my placeholder text is "bpm", the result I would like submitted is: "100 bpm". If he skipped filling out any other text input fields then no additional values are submitted (like "weeks").


texts: SEOMatic: Get SEO Image from a Matrix Field

texts:
I'm using a matrix for hero images on my pages, and I'd like to use them as the SEO image in SEOMatic, but it's not available in the settings.

I tried setting the field to "Custom URL" and adding twig code:

{% set hero = entry.heroImages.one() %}{% set image = hero.image.one() %}{{ image.url }}

If I place this in my template, it displays the path to the first matrix image, but SEOMatic seems to ignore it.

Is there another way to configure things to use my matrix images?


texts: Attaching a file to a Matrix field and then saving the entry takes up to 2 minutes

texts:
I have an issue with attaching a file to a Matrix field and then saving the entry takes up to 2 minutes. If I open up another tab with the Craft CMS admin interface I can see that Craft is performing the task: "Delete Stale Template Caches"

This does not happen in DevMode.

I have read: https://craftcms.com/support/stuck-tasks but none of our templates are using the {% cache %} tag. Also there is nothing logged in: craft/storage/runtime/logs/phperrors.log I also tried clearing the caches to no avail.

I have also found:
Saving some entries and a matrix field settings takes a very long time
but this does not provide any real answers.

The server is running PHP 7.0.20 and running Nginx as a reverse proxy in front of Apache via ServerPilot.


texts: Is it possible to return a User Model Entry or userid from a successful registration form submission?

texts:
Is there a way to return a user model entry, userid, or some other identifier (and/or variables in general) from a successful registration form submission using the hidden redirect parameter?

In the docs for action/saveUser I see some mention of {id} in the redirect string, but I'm not exactly sure sure how this works (or if it's even related).

      if (isset($_POST['redirect']) && mb_strpos($_POST['redirect'], '{userId}') !== false)
      {
           craft()->deprecator->log('UsersController::saveUser():userId_redirect', 'The {userId} token within the ‘redirect’ param on users/saveUser requests has been deprecated. Use {id} instead.');
           $_POST['redirect'] = str_replace('{userId}', '{id}', $_POST['redirect']);
      }

The reason I ask is that I am creating a multipart form that relies on the values of the previous form submission to continue (starting with user account registration). I essentially want to redirect back to the form, fill out the next part, submit, redirect back to form, fill out next, etc. (controlling the workflow with javascript or twig). FYI, using impersonate() will not work for me in this case, because user must be admin, or in a custom 'manager' group.

As a side question, I also see craft()->userSession->setNotice(Craft::t('User saved.')); used throughout the saveUser controller. Is there a corresponding getNotices() similar to getErrors() or some way to retrieve these on the front-end?


texts: Minimum database privileges for Craft front-end?

texts:
I'm wondering if it's possible to reduce the database user privileges required by Craft, to run just the front-end of the site.

Currently, the requirements docs indicate that the MySQL user must have CREATE, ALTER, DROP privileges, etc. This makes sense when using the CP to update content, etc. (or if the site needs to accept user input form submission, member login, etc.)

However, I'd like to disable the CP on the site front-end and create a multi-environment config using a DB connection with a much less privileged MySQL user.

Does Craft require more than basic database 'read' permissions to simply serve up content?

Any reason I couldn't create two subdomains, one for serving content and one for managing content via the CP and provide different DB users (with separate privileges)?

Thanks!


texts: Possible FeedMePro Anomaly When Trying to Update Table

texts:
I am running into an anomaly when trying to use FeedMe to update existing fields.  My data source is a CSV file.  I have a unique ID.

I used FMP to create the entries.  Now, I want to update a table in each entry with annual sales data.

FMP is set to update existing elements.  My unique ID (Line ID) exists in both the entries to be updated and the source CSV file.

I have aligned the source CSV file fields to the target entry table fields.  The data preview looks good, with the value for each year correctly aligned.

I also reduced the # of fields being updated to just the table fields and unique ID.

FMP runs the feed with no errors.  But, the output value for each year in the table is no longer correctly aligned with the assigned year in FMP setup.  I thought at first it was a templating error on my part, but the values are misaligned in the CP entries.

Help.


texts: Best way to create an entry (bio) view for a User

texts:
I think Douglas has kind of answered this here, but just to ask as a separate question:

Given I have made use of Craft's User section to hold data about a company's team members, how do I now make an entry page for each member, which can link through from the list page? ('About us' single containing a loop over Users).

I originally had a channel for the team members, but switched to using Users because they will be authoring blog posts, and I figured the relation would be cleaner.

Thanks.


texts: Saving an entry with multiple parentheses throw a 403

texts:
Saving an entry with multiple parentheses (in a redactor field) throw a 403. I know it's from ModSecurity - but never experienced that behaviors with another CMS (WP, Kirby, etc.) or with Craft2. This issue appears on 2 (different) projects in development.

Is anyone got something similar?

Field details:

Clean up HTML : checked
Purify HTML : checked
HTML Purifier Config : Default
Column Type : 64KB

PS. If I remove the () from the text or replace them with brackets [], the entry saved correctly. We experienced that issue on multiple computers from different offices and didn't reproduce it on local environment (MAMP or XAMP) - so it's not machine/location oriented.

PPS. Deactivate ModSecurity is not a solution


texts: Cannot change cart email within Craft Commerce while logged-in

texts:
The provided addresses template for the Craft Commerce checkout only shows the email to logged-out users. We need logged-in admin staff to be able to put orders through on behalf of a customer, over the phone. So, I'm showing the email input to logged-in users as well.

When the admin person arrives at the addresses template, the email field is pre-populated with the admin person's address. They replace their email with the customer's email. They submit.

The cart email remains the admin person's email address.

Can anyone think of a workaround for this?


texts: Is it possible to use Update Asset Indexes on a target subfolder or subfolders?

texts:
I have a folder with 10GB of files that I need to sync with Craft. It has 12 subfolders, one for each year:

/1999
  /01
  /02
  /03
  /...

It's possible to run Update Asset Indexes on the top-level folder but this process takes several hours and can't be interrupted. If things get interrupted, for whatever reason, some of the sub-folders are successfully imported but the other subfolders aren't, and there is no simple way to pick things up where they left off without restarting the full process. Ouch.

Is it possible to sync a specific asset subfolder, or list of subfolders? How would I approach this programmatically?

It seems I may want to call the AssetIndexTool::performAction method but only pass in the subfolder IDs or something like that. I haven't interfaced with the Tool classes at all. Is this a reasonable direction to consider or am I not considering another potential direction?


texts:
I have the following code:

$fieldHandle = 'contentLead';

$entryTitle = $event->element;
$entryQuery = \craft\elements\Entry::find();

$entries = $entryQuery->title($entryTitle)->limit(1);

foreach ($entries->all() as $entry) {
    $entry->setFieldValue($fieldHandle, 'hello');

    Craft::$app->elements->saveElement($entry, false, true);
}


texts: Will craft attempt to reconnect to MySQL if the connection drops?

texts:
We have a customer using a cheap managed hosting provider, and their MySQL server very aggressively times out and drops the connection.

I wonder if this could be causing us troubles as outlined here: Massive template cache cleaning tasks always get stuck

Does Craft attempt to reconnect to MySQL if the connection drops halway through a request?


texts:
I have a channel section with a handle named 'events'.

In my field layout for this section I have a field named eventsDate, which is a Date/Time field.

I also have a plain text field called 'eventsHeadline'.

What would be a good way to output the 'eventsHeadline' entries ordered by 'eventsDate'?


texts: Retrieve entry data from an Entries field in a Matrix Block

texts:
I'm using a Matrix field for menu section blocks that each have a name, section and menu items. The menu items for that menu section are assigned using an Entries fieldtype that displays entries from food and beverage entries. Here's a screenshot of the field setup in case that helps explain it better:

What I'm trying to do is generate a menu endpoint that has the individual sections and within each section display the item data. The json response I'm looking for should be similar to this structure:

        "menu": {
          "id": 1,
          "sections": [
            {
              "id": 1,
              "name": "Heavy",
              "description": "All our heavy draft beers.",
              "items": [
                {
                  "id": 2,
                  "name": "Samuel Adams Utopias",
                },
                {
                  "id": 3,
                  "name": "Samuel Adams Utopias",
                },
              ]
            },
            {
              "id": 2,
              "name": "Light",
              "description": "All our light draft beers.",
              "items": [
                {
                  "id": 2,
                  "name": "Samuel Adams Utopias",
                },
                {
                  "id": 3,
                  "name": "Samuel Adams Utopias",
                },
              ]
            },
          ]
        }

I can accomplish the section structure just fine, but I can't get the data from the sectionItems field which is an Entries type. This is what I have minus the items call.

        'api/v1/locations/<entryId:\d+>/menu.json' => function($entryId) {
          return [
            'elementType' => 'Entry',
            'criteria' => [
              'id' => $entryId,
              'type' => 'location'
            ],
            'first' => true,
            'transformer' => function(EntryModel $entry) {
              foreach ($entry->menu as $block) {
                $menuBlocks[] = [
                  'id' => $block->id,
                  'menu_id' => $block->fieldId,
                  'name' => $block->sectionName,
                  'description' => $block->sectionDescription,
                  'items' => $block->sectionItems,
                ];
              }

              return [
                'title' => $entry->title,
                'menu' => [
                  'sections' => $menuBlocks
                ]
              ];
            },
          ];
        },

Any help would be greatly appreciated!


texts:
Does anyone know how I can show a specific entry to a user (frontend)? My user field is called "gebruiker".

{# Get current member e.g URL /members/1/ #}
{% set currentMember = craft.users.id(craft.request.segment(2)).first() %}

{# Get current members test entries #}
{% set currentMemberTest = craft.entries.section('test').relatedTo({
    targetElement: currentMember,
    field: 'gebruiker',
}) %}

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

{{ entry.title }}

{% endfor %}

Thanks


texts: Automatically add an insurrance for a product

texts:
What would be the best way to automatically add a product when another product is added to the cart?

For example, if I where to add a TV to the cart, I would like to automatically add a HDMI cable as well.


texts: How to access HTML input values from Twig and vice versa

texts:
I am new to Craft and Twig in general. I have encountered the following problems and struggling to find a solution for hours.

I want to access the value of "foo" input field inside the twig delimiters to set the "json" variable.
I want to change the "clicked" boolean, whenever the submit button is clicked.

The myFunc is a function that I am using from a custom plugin so it is not relative.
I have commented what I've last tried and does not work for me.

I am using Craft 3, if that helps.

{% block body %}
    {% set clicked = false %}

    <form name="search" action="{% set clicked = true %}">
        Foo
        <input name="foo" type="text"/>
        <input type="submit" value="Get Json"/>
        {#    <a href="{{ set clicked = true }}"#}
    </form>

    {% if clicked %}
        {% set json = jsonator_myFunc(search.foo.vars.value) %}
    {% endif %}

{% endblock %}

EDIT/SOLUTION:

A few more days into Craft CMS and chill and I realize how silly my question is.

Thank you for the replies. The solution which I was looking for is:

craft.request.getParam('foo')


texts:
I'm just wondering why don't you guys compile all the cpresources into 1 .js and 1 .css file?

Right now this folder is gigantic :D
cfr: https://i.imgur.com/Oksr5Kn.png


texts: Editing a custom user field onBeforeSave

texts:
When a user saves a front-end form, and has a custom field with a set value, I want to send an email - and set another field on the users profile to indicate a mail has been sent, so that if the form is saved again, another email will not be sent.

To do this I have a small plugin:

public function init() {
    craft()->on('users.onSaveUser', function(Event $event) {
        $user = $event->params['user'];
        $consentGiven = craft()->request->getPost('fields.consentGiven', 'no');
        $notificationAlreadySent = $user->notificationAlreadySent;

        if($consentGiven == 'yes' and $notificationAlreadySent != '1') {
            ... SEND EMAIL CODE ...

            // now set the notificationAlreadySent to '1' so we dont get in this conditional next time
                $userModel = new UserModel();

                // why we need to manually read these to write the same values I don't know
                $userModel->id        = $user->id;
                $userModel->username  = $user->username;
                $userModel->firstName = $user->firstName;
                $userModel->lastName  = $user->lastName;
                $userModel->email     = $user->email;

                // update the one field we actually wanted to update in the first place
                $userModel->getContent()->setAttributes(array(
                    'notificationAlreadySent' => '1'
                ));

                // Actually save it
                craft()->users->saveUser($userModel);
        }
    }
});

Problem: This ends up in a loop because it's watching the onSaveUser event, and inside that event it's calling saveUser. I figure I actually need the onBeforeSaveUser event, and I need to tweak the value of that field there so that it'll "just work" once it gets to the saveUser action.

That being the case I've tried this instead...

public function init() {
    craft()->on('users.onBeforeSaveUser', function(Event $event) {
        $user = $event->params['user'];
        $consentGiven = craft()->request->getPost('fields.consentGiven', 'no');
        $notificationAlreadySent = $user->notificationAlreadySent;

        if($consentGiven == 'yes' and $notificationAlreadySent != '1') {
            ... SEND EMAIL CODE ...

            // now set the notificationAlreadySent to '1' so we dont get in this conditional next time
                $user->fields['notificationAlreadySent'] = '1';
        }
    }
});

New problem: The syntax $user->fields['notificationAlreadySent'] = '1'; doesn't appear to be correct, and I can not work out how to reference that property...


texts:
I have a list of orders from Commerce 1 (Craft 2) in the frontend.

I want to invalidate the cache when a new order is placed but it doesn't work:

{% set latestOrder = craft.commerce.orders.first() %}

{% cache until latestOrder.dateOrdered  %}
   Last Updated: {{ orders.dateOrdered.first() | date('D d.m.Y - H:i') }}
   {# stuff #}
{% endcache %}

The Last Updated tag shows always the latest browser reload. What's the error here?


texts: I've got devMode enabled and can see the log happening in craft/storage/runtime/logs/craft.log for browser requests... but was wondering if there is a way to enable this level of logging (detailing every sql etc.) for console commands in plugins?


texts: Loop through entries taking far too long to finish

texts:
I am attempting to loop through my "journalEntries" in order to find duplicates. For some reason, it is taking a very long time to finish and return a response to me. Last time I tested it, it took 12 seconds to finish.

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'journalArticles';
$criteria->limit = 10;
$copies = array();

for($a = 0; $a < count($criteria); $a++) {
  for($b = $a + 1; $b < count($criteria); $b++) {
    if($criteria[$a]->title === $criteria[$b]->title) {
      array_push($copies, $criteria[$a]->title);
    }
  }
}

$this->returnJson($copies);

I think it is something I am doing incorrectly within the two for loops. As you can see, I limit the amount of articles to only 10, so something seriously funky must be going on. Any help?


texts: How to programmatically update a plugin's settings?

texts:
Is there a way to programatically update a plugin's settings? I'm experimenting with setSettings() but not really getting anywhere - I'm still quite new to plugin development so there's a good chance i'm completely off target hehe.

For some context: I'm trying to update the plugin settings when an event is fired and picked up by a listener as follows:

public function init()
{

    // add event listeners
    craft()->on('assets.onReplaceFile', function(Event $event) {

        //Load Asset
        $asset = $event->params['asset'];

        //Check if asset is the svg sprite
        if($asset->getUrl() == $this->getSettings()->spritePath){
            $url = craft()->getSiteUrl().$this->getSettings()->spritePath;
            $this->setSettings(array('spriteDefs'=>$this->getSpriteDefs($url)));
        }

    });
}

getSpriteDefs returns an array.

Thanks in advance!


texts: Error: Invalid negative value for  attribute

texts:
I'm trying to create a dashboard widget using the new Craft charting library.  I'm more or less copying the New Users widget however I'm running into an issue where my container does not seem to be behaving in the same way as the New User widget - it appears the container is getting a different width and no height.

Similar to NewUsersWidget.js I am using these three lines of code to set the container:

this.$widget = $('#widget'+widgetId);
this.$body = this.$widget.find('.body:first');
this.$chartContainer = $('

').appendTo(this.$body);

However, when I inspect this.$chartContainer in the NewUsersWidget.js it has a width and height whereas when I inspect this.$chartContainer in my own widget, the width is different and the height is not present. I don't see these values set explicitly in the New Users widget. It appears they may be set dynamically in craft.js, but I'm not sure. Both javascript objects extend Garnish.Base.

Understandably, someone helping troubleshoot this may need more context. I'm really not sure what more I should be sharing, so let me know if I can provide additional details to help narrow down what may be happening.

A more general question may be, how does width and height get set when creating a variable (this.$chartContainer) in an object that extends Garnish.Base? Why would two different widgets creating the same variable both end up with a different height and width?


texts: How can I return all user custom profile fields in an array?

texts: Hi I'm sure this is simple but it is eluding me. I want to pull out all the user profile fields with twig as an array that I can then check. When I dump the user or currentUser data it does not show any of the profile fields I have created in the returned object. I can however still access these fields with user.customfieldname. How can I return the array I am looking for?


texts: Is it safe to move Craft Commerce Templates out of Plugin

texts:
I installed Craft Commerce 2 and the templates are in vendor/craftcms/commerce/templates/shop. Is it safe to move these to my craft templates folder like this?

├── storage
...
│   └── runtime
├── templates
│   └── shop
├── vendor

Or are they where they are for a reason?

I don't really like the idea of drilling down into the vendor plugin directories to make changes, especially if they can be overwritten by composer during an update.

I don't want to introduce future problems.

David


texts: Advanced Search with tags and categories

texts:
Been scratching my head for the past day on how to implement search with multiple categories.

At the moment, I have product categories as a select dropdown which only allows to search in one category at a time. This is passing the value as a parameter. How do I go about searching with multiple categories (checkboxes) at once? Here's what I have so far.

Any ideas?

search.html

<form action="{{ url('food-suppliers/results') }}">
    <input type="search" name="query" placeholder="What are you looking for?" style="width: 100%;">

    <select name="supplier">
      <option value="">All Markets</option>
      {% set suppliers = craft.categories.group('suppliers') %}
      {% for supplier in suppliers %}
      <option value="{{ supplier.slug }}">{{ supplier.title }}</option>
      {% endfor %}
    </select>

    <select name="product">
      <option value="">All Products</option>
      {% set products = craft.categories.group('product') %}
      {% for product in products %}
      <option value="{{ product.slug }}">{{ product.title }}</option>
      {% endfor %}
    </select>

    <select name="delivery">
      <option value="">All Delivery</option>
      {% set deliveries = craft.categories.group('delivery') %}
      {% for delivery in deliveries %}
      <option value="{{ delivery.slug }}">{{ delivery.title }}</option>
      {% endfor %}
    </select>

      <input type="checkbox" name="homeGrown" value="true">Home Grown

      <input type="checkbox" name="preparedProduce" value="true">Prepared Produce

      <input type="checkbox" name="redTractor" value="true">Red Tractor

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

</form>

results.html

{% set query = craft.request.getParam('q') %}
{% set supplier = craft.request.getParam('supplier') %}
{% set product = craft.request.getParam('product') %}
{% set delivery = craft.request.getParam('delivery') %}

{% set homeGrownParam = craft.request.getParam('homeGrown') %}
{% set preparedProduceParam = craft.request.getParam('preparedProduce') %}
{% set redTractorParam = craft.request.getParam('redTractor') %}

{% set supplierCat = craft.categories.group('supplier').slug(supplier).first %}
{% set productCat = craft.categories.group('product').slug(product).first %}
{% set deliveryCat = craft.categories.group('delivery').slug(delivery).first %}

{% set supplierParam = supplier ? {targetElement: supplierCat} : '' %}
{% set productParam = product ? {targetElement: productCat} : '' %}
{% set deliveryParam = delivery ? {targetElement: deliveryCat} : '' %}

{% set entries = craft.entries.section('suppliers').relatedTo(productParam).relatedTo(deliveryParam).search(query).homeGrown(homeGrownParam).preparedProduce(preparedProduceParam).redTractor(redTractorParam) %}


texts: How do I handle named route variables passed to a controller?

texts: I'm writing a plugin that uses the registerSiteRoutes hook to create some new routes, and passes those routes to some controllers. In these routes, I have a few pieces of the URL that I'm capturing as named subpatterns. I'm curious how I handle these named variables in the controller that receives them.


texts: Query two sections filtered by different custom fields, then order them

texts:
Two channels:
1) exhibitions, which have a startDate and EndDate
2) events, which have a date

I need to grab the current exhibitions, future exhibitions and future events, which I do using this:

{% set allOccurrences = craft.entries.section('exhibitions').startDate('<= ' ~ now | date("U")).endDate('>= ' ~ now | date("U"))
    | merge(craft.entries.section('exhibitions').startDate('> ' ~ now | date("U")))
    | merge(craft.entries.section('events').date('>= ' ~ now | date("U"))) %}

Now what I need to do is order them, by the startDate (if an exhibition) and the date (if an event). In other words, having already fetched the entries, I need to order them by two different fields.

I'm not sure this is possible without a plugin - could anyone give me any pointers?


texts: Displaying an array returned from a hook

texts:
I'm writing a plugin which has a hook like:

craft()->templates->hook('myHook', function(&$context)
{
    return array('hello', 'there');
});

While I can call it in a template with:

{% hook myHook %}

I get an "Array to string conversion", understandably. But I can't work out how to treat the returned data like an array. How can I use hook 'myHook' in a for loop, or set it to a variable? It must be simple, but I've exhausted my random attempts.


texts: With the Charge plugin, can you add an additional one-off fee on subscription?

texts: Is there a way to add an additional one off fee using Charge plugin? Example situation: I need to charge my subscriber $150 USD per month.  However, for the first month only, there is an additional $50 USD for the set-up fee.


texts: Error when outputting assets from a field within a Neo field

texts:
Anyone with Neo experience had issues with outputting an assets field with multiple images?
I am not using a dynamic field, as I saw there are issues with that.

Code

{% for asset in block.serviceGallery %}

{% endfor %}

Error:
Key "index" for array with keys "entry, ... " does not exist.


texts: Licensing a multi-lingual site using different domains

texts:
I'm building a site for a multinational company. I have domains set up like this example:

acme.com (main portal site, different from local sites, but also aggregating content from all local sites)
acmelocal.de,
acmelocal.fr,
acmelocal.co.uk ... (local sites using the same structure only different languages)

I want to run everything on the same Craft install to be able to share data. I'll enable certain sections for main portal site only and certain for local sites only - from what I've read, Craft could handle that ... right?

How do I license this? I'm thinking I can buy a pro license for "acme.com" and use all local sites as locales of the main site. Would this work?

I'm running everything on a custom server, so I can set up all the domain stuff etc.


texts: Structure listing order & classes based on lightswitch value

texts:
I have a structure called "Projects", which I am currently listing on a page. The layout looks like the below - with the every row starting or finishing with a .wide class thumbnail:

This is the code used to generate that layout (simpified here for clarity):

  {% for project in craft.entries.section('projects').all() %}

  {# Set a variable to check if it is a wide one or not #}
  {% set wide = 0 %}
  {% if (loop.index is divisible by(6) or loop.index0 is divisible by(6)) %}
    {% set wide = 1 %}
  {% endif %}

{{ project.title }}

    {% endfor %}

Some of the projects now have a lightswitch added (project.story) which makes them a "Story". These need to have a .story class added to them, and be injected into the layout every 6 entries, for as many as there are. Apart from that the standard project entries should list in the same order they appear in Craft. The Stories have a wider thumbnail image and some different content output in the listing.

If there are more stories than standard entries they should then all list at the bottom, likewise if there are more standard entries these should list out. Below are images of those two scenarios:

1)

2)

Can anyone please help with how I need to adjust my twig template to generate these layouts? I can add the .story class based on the lightswitch but am at a loss how to adapt the layout to have them appear where I need them to.

Thanks for any help

Mike


texts:
My runtime/cache folder is over 200GB in size. Is there a config setting or some way of limiting the size of the folder, rather than the cache duration?

Secondly, what could cause such disk usage?


texts:
I'm trying to change Redactor's settings by editing craft/config/Standard.json (and Simple.json) but it doesn't seem to have any effect at all. I logged out, emptied Craft's and browser cache and still don't see any changes.

Is this feature broken in the current Craft version or am I missing something? I edit the file by removing/adding buttons, like this:

{
    "buttons": ["html","formatting","bold",],"plugins":["fullscreen","video"],
    "toolbarFixed": true
}

Thanks!


texts: Is it possible to return data/models from controller to template via setRouteVariables?

texts:
I'm trying to write a plugin that lives in the admin interface, that reads external data (a cinema program), parses it, and creates entries based on this (movie info and screening times).

While doing so I build a log of the additions/updates made, that I want to return to the template (the plugin page from where I trigger the update) and display the changes listed in a table. But I have trouble reading anything out with craft.request.getPost() from the template.

The log, basically an array of custom models (log items), seems to be fine while still in the controller. I try to pass this array via craft()->urlManager->setRouteVariables(), but at the template, it seems the only variables it finds are the action and redirect parameters from the original form.

The code in the controller looks like this:

$log = craft()->updateProgram_program->update();
craft()->urlManager->setRouteVariables(array(
   'log' => $log
));

And then I try to read the log variable in my template like this:

{% set log = craft.request.getPost('log') %}

Whatever I do, it seems to always be NULL. I've also tried to set a simple text string as the value, in case it's not possible to post an array like this, but it's still NULL when it comes to the template. It seems the log parameter is simply not found in the POST request at all.

Is there anything obvious I'm doing wrong?

I've scratched my head all day over this, so any tips are extremely welcome!


texts: Can I eager load data within a template?

texts:
I have a Matrix field with a single block type and within that, a number of fields that I need to pull out:

{% for roomContent in hotelEntry.roomsAvailable %}
    {% if roomContent.code == room.roomTypeCode %}

room code = {{ roomContent.code }}

            description = {{ roomContent.description }}

            {% for image in roomContent.images %}

            {% endfor %}

    {% endif %}
{% endfor %}

I am doing this on a listing page where there are around 60 entries, so this is resulting in a lot of calls to the DB.

Is there a way I can eager load all of the data for all of the entries outside of this loop so I'm not recursively calling for data?


texts:
When listing entries with lots of assets (and therefore thumbnails), the server slows down significantly.

I realized, that the assets all have the path:
https://mypage.url/index.php?p=admin/actions/assets/thumb&uid=a59e2c6f-1d32-4568-ab34-8655d33427d8&width=30&height=30&v=1559381105. However, I thought they were located in the cpresources folder?

Is there a way to make Craft use direct links to the thumbnails instead of using PHP to deliver the images?


texts: Why is Live Preview scrolling to the top of page after every change?

texts: Having an issue with Live Preview scrolling to the top of the page in the preview area on every update made (even title field). Narrowed it down to it not being a browser issue as it works plum good on another site. Here’s the error I’m seeing in console with the site giving me the issues. Can anyone point me in the right direction? Please and thanks]1


texts: Templating repeatable blocks in a matrix field

texts:
I have a matrix field that has two different block types. The matrix field is on an entry that lists a number of benefits for a given product on a corporate website. The two different blocks are firstly an "intro" block that has a couple of text fields for a headline and description and then secondly a "benefits" to create a list of benefits. I then output the items in the template as follows:

{% for intro in entry.benefits %}
    {% for image in intro.leadImage %}

    {% endfor %}

{{ intro.introTitle }}

{{ intro.introParagraph }}

{% endfor %}

    {% for benefitsItem in entry.benefits %}

{{ benefitsItem.benefit }} - {{ benefitsItem.description }}

    {% endfor %}

There are two different for loops, one that lists the "intro" block and one that lists the "benefitsItem" block. The problem I have is that I want to be able to separate lists of benefits into sections by inserting another "intro" block in the CMS content but of course no matter where I order my "intro" blocks in the admin they will always appear above all the benefits where the for loop puts them out. Does anyone know how I would go about creating a matrix field or changing my template so that I can order things as follows:

Intro
Benefit
Benefit
Intro
Benefit
Benefit

Any ideas greatly appreciated. Thanks.


texts:
In the backend, I could upload an image. I see it loads fine in the backend admin CP.

But it goes to a 404 error on the front end.

File System Path:
/home/devserv1/colorcomputergames.com/assets/clones/

The URL to your folder:
http://www.colorcomputergames.com/assets/clones/

The direct URL to the image is:
www.colorcomputergames.com/assets/clones/lunar_lander.png

But it brings up a 404 Error. I read here to look into the server settings. I'm running Apache.

Thanks


texts: How to get one random entry from among multiple sections

texts:
I'm trying to pull a random entry from among an array of sections, but I can't get it to work.

I tried the code below, but I'm just getting errors. I've tried multiple ways of listing the sections -- "section","section" ['section,section'],etc, but none work. Do I need to specify my sections in a different way?

{% set random = craft.entries.section('quotes,didYouKnow').limit(1).order('RAND()').find() %}
{% for content in random %}
...
{% endfor %}


texts:
Is there a technique for displaying a list of “Next Entries”, which come from the current Channel. The solution I am using at the moment isn’t cutting it…

I’m using an Entry Offset of 1 to display Entries in a sidebar. This works OK if the Entry Detail page the user is looking at happens to be for the most recent Entry, but this quickly breaks down if displaying any other Entry, as the sidebar always displays a list starting at the second most recent Entry.

How would I display the next entries in the sequence, regardless of which Entry detail page the user is on?

Thank you


texts:
I'd like to reopen this question:

The answer was a plugin called Nice Time

But This plugin is depricated and the creator stats that this functionality is acheivable via the date_modify filter.

Yes okay, but how?

I have a event archive where I want to show "This event happend xy days ago".

There is a time_diff filter in twig. But it seems as if this is not activated in craft.


texts: Re-using path segments for an additional domain?

texts:
I have a Craft installation with two domains pointing at it. The first domain is all working and has a number of sections including a blog located at /blog. What I want to be able to do is have a different blog section for the second domain that is also at the path /blog so naming conventions are all consistent i.e.

domain.com/blog
domain-two.com/blog

Of course in the CP when you add another section it will not let you use the same path which makes sense. As there is a lot of shared information but also a couple of sections/pages that will be different I thought perhaps using the .htaccess to rewrite the URL to include an additional path segment for the second site which could then be used in the CP to distinguish unique paths.

I tried modifying the .htaccess RewriteRule but could not get this to reflect in the information passed through to Craft.

RewriteCond %{HTTP_HOST} ^domain-two.com$
RewriteRule (.+) domain-two/index.php?p=$1 [QSA,L]

or

RewriteCond %{HTTP_HOST} ^domain-two.com$
RewriteRule (.+) index.php?p=domain-two/$1 [QSA,L]

Is there a way to make the rewrite work, I'm probably doing something wrong, or is there a better way to trigger a unique path from the same URL path? I really need to keep the URLs consistent.


texts: Localization - linking to other pages goes to 404

texts:
I have a localized site set up where the language switcher and translations are working fine. However when I link to internal pages it goes to a 404.

general.php has this:

 //local only
 'etf-craft.dev' => array(
    'devMode' => true,
    'siteUrl' => array(
       'en' => 'http://etf-craft.dev/en/',
       'fr' => 'http://etf-craft.dev/fr/'
   ),
   'environmentVariables' => array(
        'environment' => 'local',
        'basePath' => 'D:\sites\etf-craft\public_html',
        'baseUrl'  => 'http://etf-craft.dev',
    )
),

site structure is like this:

craft
public
public/en/
public/fr/

index.php in /fr/ and /en/ directories contains the following where french says /fr/ instead of /en/:

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

// Tell Craft to serve the English content
define('CRAFT_LOCALE', 'en');

One link I've created that 404s on me is:

    {{ "News" | t}}

What I expect is that it takes me to http://etf-craft.dev/en/news and the news page shows up. However I end up going to a 404.

However if I manually remove the /en/ from the address bar the news template shows up correctly.

not working - http://etf-craft.dev/en/news
working - http://etf-craft.dev/news

What am I doing wrong?


texts: Has anyone used Dreamhost's cloud service: DreamObjects, an Object-Based-Storage to host their assets? If so, how do you configure this with Craft 2.6.2911?


texts: How to write a segment that is not two other segments

texts:
How can I write:

is segment 3, and is not itemA and is not itemB?
both itemA and itemB are segment 3 as well.

{% if craft.app.request.getSegment(3) and craft.request.getSegment(3) !== 'itemA' and craft.request.getSegment(3) !== 'itemB' %}

To clarify, I want to target a category that is segment 3, but I want to omit two other categories that are on the same segment(level):

Topics Category

Subcategory
Subcategory

itemA(omit)
itemB(omit)
itemC(yes)
itemD(yes)

In code, I want to achieve this:

{% if craft.request.getSegment(2) == 'Subcategory' %}
   // do something
{% elseif craft.app.request.getSegment(3) and craft.request.getSegment(3) !== 'itemA' and craft.request.getSegment(3) !== 'itemB' %}
   // do other stuff
{% else %}
   // do a generic thing
{% endif %}


texts: I'm trying to follow this tutorial, but I'm stuck. I create the layout.html file and the index.html and it's still not working. Any ideas?


texts:
This one is new to me. I've got the timezone set in my admin panel to Denver but I get this this error when I try using a global in my template...

DateTime::__construct(): Failed to parse time string (End Date) at position 0 (E): The timezone could not be found in the database

Here is my code in the template

{{ endDate | date("U") }}

My global is called End Date (endDate) and is using a date field type


texts:
I have a matrix inside of which I have 2 fields, 1. dropdown list containing download types and another asset field. I would like to search first by a category and then I would like to further filter them and see if they have downloads of a certain type.

I would like to avoid a 2 step searching if possible and search articles that belong to certain category that have a certain download type associated with it.

Any idea on how to achieve this?


texts: For loop does not display all entries in section

texts:
I have a for loop for all entries.  There is no limit set, yet the loop is not displaying all the entries.  The missing entries are the oldest.  These missing entries do appear on category specific pages.

There are no errors.  I have approximately 100 entries.  The for loop is only displaying the most recent 80 or so.

Any ideas?
Thanks

{% for post in craft.entries.section('posts') %}
                {% if loop.first and craft.request.pageNum == 1 %}

                                {{post.title}}{{post.tagline}}

                {% else %}

                                {{post.title}}

                {% endif %}
                {% endfor %}


texts: JS - Determine that an entry is unsaved?

texts:
I've created a custom fieldtype... which is basically a button that triggers an AJAX action. When I add this field to my section, I can click the button while I'm editing an entry to perform an action.

Here's the thing... How can I tell if the entry needs to be saved? Clearly Craft is aware of whether an entry is unsaved or not, because it'll warn you before navigating away from the page. Is it possible for my button to tap into that same behavior?

MORE INFO:

This button does not take people away from the page, so I'm not sure if data-confirm-unload really comes into play here. If the entry is unsaved, the button will be replaced with a message saying, "you must first save the entry".


texts: Default settings for HTML purifier and how to extend it

texts:
Is there a default.json file for the html purifier settings in Craft? Now we can configure this I want to extend to include the stripping on non-breaking spaces. However, I don't want to just extend my requirements and not replace the default.

As I understand I would create a new json file in craft/config/htmlpurifier and this file would contain the following;

{
  "AutoFormat.RemoveEmpty.RemoveNbsp": true,
}

Is this all that is required?


texts: How to add a subTask to an already running Task?

texts:
I have a plugin which creates a task every time a specify form is submited. Now I want to create a WrapperTask and run each of those tasks as a subTask:

I know that I can create a sub-task within the WrapperTask by using $this->runSubTask, but how can I add a subTask to an already running WrapperTask from outside (the service for example)? Or at least send a new settings-array to an already running Task?

Example:

User submits form
Service creates WrapperTask
Service adds subTask to WrapperTask
Nothing happens for some time
User submits form again
Service checks if WrapperTask is still running, and adds subTask

.

If that's not possible, can I at least show them visually as subtasks of my plugin in the task-list?


texts: Display matrix block which share the same date field value

texts:
I think a better way to achieve this would be with Supertable, but for now I'm wondering if there is a way to group the example output

W/C: 27 Aug 2018 {{ block.week }}

1.5 {{ block.totalTime }}

W/C: 27 Aug 2018 {{ block.week }}

2.5 {{ block.totalTime }}

W/C: 27 Aug 2018 {{ block.week }}

3 {{ block.totalTime }}

instead like

W/C: 27 Aug 2018

1.5

2.5

3

so values from the 'number' field {{ block.totalTime }}
which share the same value from the 'date' field {{ block.week }}
are somehow grouped together?

from the matrix fields in use below:

     {% for block in entry.timeSheet %}

        {% if block.totalTime | length %}

        W/C: {{ block.week|date('j M Y') }}

        {{ block.totalTime }}
        {% endif %}{{ not loop.last ? '
' }}

     {% endfor %}


texts:
I have Codeception running on my local install without errors, but it's not yet actually doing anything. I am building several plugins and I can't figure out how you actually test a plugin? I have no app code at all, all functionality comes from the plugins.
I have seen other plugins running their own custom PhpUnit code inline, but shouldn't I be able to fire off Codeception from the root app and it will test available plugins?
Fully aware that this is a vague question, but I can't find any information about specifically testing Craft plugins.


texts: How can I show the child category and not it's parent - but other times show it's parent?

texts:
I have a categories field on an entry that can have one or many children. I am able to output everything - but would like to restrict the field a bit more.

If a child has been selected, I do not want to show the parent. In my example, I only want to show "child".

It is possible, that I might only choose "parent" and I only want that to show. Or, is there a different way I should go about doing this? Thank you for any suggestions!

I've tried something like this:

{% for service in entry.servies %}
   {% set subCategories = craft.categories.descendantOf(service) %}

   {% if subCategories|length %}
       ...
   {% endif %}
{% endfor %}

But that will show the child category if it's selected or not. I would only like to show the "Child" category if it was actually selected. Otherwise, show the "parent" category.

UPDATE/SOLUTION

First, I want to thank Robin for your help. I tried different variations and was unsuccessful. I ended up taking my existing category and making it a structure. This gave me the flexibility that I needed.


texts: Image Transforms - Image not processed until second page refresh

texts:
I'm new to Craft, and am not sure whether I've got something weird happening or if what I'm experiencing is expected behavior.

I notice that when I add new entries containing image assets that get transformed (using a control panel transform in this case), that the images don't get transformed until the (template) page is loaded a second time. Therefore, each new page contains empty images and alt-text on its first load. Once I refresh the page, the images appear as expected.

Is this expected behavior? Right now this requires me to visit the page of every entry I create, in order to 'seed' it for use.

Not a deal breaker, but I'm just curious whether there's something I'm doing wrong on my end.


texts: Convert a PHP image resource to a new Asset

texts:
I am trying to merge two images and save it as a new asset and I am using the PHP function called "imagecopymerge" (https://www.php.net/manual/en/function.imagecopymerge.php) however thats returning a "resource" and I have tried figuring out how I can turn that "resource" into something I can use to save using perhaps $tempath?

$newAsset = new Asset();
$newAsset->avoidFilenameConflicts = true;
$newAsset->setScenario(Asset::SCENARIO_CREATE);
$newAsset->tempFilePath = $tempPath;
Craft::$app->getElements()->saveElement($newAsset);


texts: "Craft is unable to determine if an update is available at this time."

texts:
I am receiving the following error when I click on Check for Updates ...

  Craft is unable to determine if an update is available at this time.

Do you know what could be causing this?


texts: Database Backup Contains Perplexing Number Of Duplicates

texts:
I recently had a craft update fail when moving from 2.4x to 2.5x. This was probably caused because the linux user craft was using did not have the proper permissions. This is all good and fine. Craft created a DB backup before updating and this is where I am having a very strange issue. This DB backup has tons of duplicates, seemingly on every table. Importing the database always ends in Duplicate entry '1' for key 'PRIMARY'. The dump is also trying to add the same tables multiple times. The database I am importing also into has nothing in it. Has anyone run into this issue?

Here is a partial database dump:
http://pastebin.com/FRgp1FPy

If you for example look at line 100 and 135, you can see that the dump has duplicate primary keys in the table craft_assetfiles. This dump also shows that the craft_assetfiles table is being added twice and with different data each time.


texts: Guest Entries plugin with Paypal integration?

texts:
I was wondering if someone with Paypal/PHP experience could give some suggestions on how to integrate Paypal with the Guest Entries plugin...

I want to use the Guest Entries plugin to build a job listing (it has been done before, check it out http://pasesetter.org/jobs) and would have to charge a small fee for users (no registration required) to submit job listings.

Before the entry/listing becomes published, users would be redirected directly to PayPal where they can make the payment. Paypal already has an auto-return option for websites payments, so users are redirected back to the site after payment.

Any guidance would be highly appreciated!


texts: How does Craft handle uploading assets to AWS?

texts:
When users upload assets to a Craft CMS site setup to use AWS, do the assets go directly to AWS or are they uploaded to the Craft server first?

The reason I ask is I'm building an area where users upload potentially large files from the frontend, and it's quite likely a lot of users will choose to do it at the same time.

If the files are uploaded to the Craft server first, I might have to spec-up the server a bit more and would welcome any tips for helping Craft handle the multiple large uploads as efficiently as possible.

If the files are simply uploaded to AWS, I take it that means there will be little impact on the Craft server and I won't need to worry about any of this. Is that right?


texts: I want to know if I can interface Craft address details into DPD shipping site

texts: New to this and just looking at a few solutions for a small start-up. Would I be able to take address details directly from Craft and interface directly to preferred carrier which is DPD here in UK? Currently my customer is typing address details from existing e-commerce site into DPD !!!


texts: Home page loop once, other pages loop through all

texts:
I only want one block on the home page, other pages can loop through all of them. Is there a more efficient way to write this?

{% if craft.request.getSegment(1) is empty %}
        {% for block in memberships.memberships.limit(1) %}

            {% for asset in block.logo %}

            {% endfor %}

        {% endfor %}
    {% else %}
        {% for block in memberships.memberships %}

            {% for asset in block.logo %}

            {% endfor %}

        {% endfor %}
    {% endif %}


texts:
I am trying to create a plugin that takes the POST data from an order and emails it to the end user. Which property should I use to do this? I've already tried to use getContent() and getContentFromPost().

So for example if I have

         <input type="text" name="dataName" value="">

And in my plugin I'm trying to get the value of "dataName" which property should I use?


texts: Can a Table Column be Rich Text / WYSIWYG?

texts: The only types in the list are Single-line text, Multi-line text, Number or Checkbox.


texts:
I'm trying to auto-post from my blog to Facebook using Buffer and this plugin (https://straightupcraft.com/craft-plugins/buffer). The addon requires me to create a plugin to do the actual posting to Buffer. This is my first foray into plugins at all. I used his example and got something that works.

However, the question I have is somewhat general. How do I pull an asset from an entry that has been saved to be able to post to the plugin?

This is the relevant portion of the plugin:

$picture = craft()->request->getUrl($entry->blogImage);

craft()->buffer_utils->queueBufferUpdate($updateString, true, $link, $picture, $thumbnail);

Obviously, my asset field name is blogImage.

Also, and let me know if I need to create a new question for this, how does onBeforeSaveEntry affect scheduled content? Does/will the plugin run when it's actually saved or when it becomes "live"? If so, is there a workaround for that?

Thanks.

edit: I did reach out directly to the developer but have not had any luck yet and was hoping the question was general enough that someone else might be able to help!


texts:
So a client is setting up a subscription website. It has an initial payment of $10, and then $0.99 monthly. Has anyone gotten trial amounts to work? I basically need to charge them $10 then set up a subscription. I'm trying to figure out a way to make it seamless for the user.

There's no way to make a charge programmatically via Charge without writing a second plugin. I know this is doable via vanilla Stripe, but I'd like to use Charge for all the convenient features.

Any ideas?


texts: sort by checkbox field with multiple options and by postDate desc

texts:
Section handle: players
field handle: teamName
The checkbox field has two options:

Cubs
Tigers

Not all players will have the teamName field checked.
I want to order players who are Cubs or Tigers first and order those players by their postDate desc, while ordering the non Cubs/Tigers players by their postDate desc.
{% set players = craft.entries.section('players').orderBy('teamName, postDate desc').all() %}

This kind of works, but it orders Cubs players before Tigers players, regardless of their postDate, so a Cubs player could of been added 30 days ago and still show up before a Tigers player who was added 2 days ago.
I know the teamName is being ordered, I don't know how to add the postDate desc to the teamName logic. It needs to support pagination.


texts: Allow a dropdown custom field to be edit from a front end form

texts:
I want users to be able select their own name prefix/title (Mr, Mrs, Dr. etc) as part of front end form that allows them to update their user details.

I have created a custom dropdown field and populated this with the titles that users can select. However, I'm having trouble displaying the dropdown on the front end form that allows users to select one option.

Any guidance on how I would go about achieving this would be helpful!

EDIT

This is what I had initially. However, this just prints each option as a separate select?

{% set dropdownField = craft.fields.getFieldbyHandle('honorific') %}

{% for option in dropdownField.settings.options %}
    <select id="honorific" name="honorific">
        <option value="{{ option.value }}">{{ option.label }}</option>
    </select>
{% endfor %}


texts: How do I set up a section of text on my home page to rotate through, rather than stay static?

texts:
I am a site owner who's new to Craft and whose site is nearing completion. I now realize I would like to have multiple versions of text rotate through in the box on the top of my home page, rather than having one "fixed" paragraph of text that doesn't change, unless I change it manually. (Think of scrolling testimonials, even though I don't plan to use it for that ...)

Will this change in setup require major surgery on the developer's part, minor surgery, or just a simple plugin, for example? Or might this functionality be built into Craft already? What's the upper limit on how many chunks of text I can have cycle through for the viewer to see?

Many thanks for your help and input!


texts: Feed Me: Valid JSON file returning as invalid

texts:
Can anyone see why this data would return as invalid in Feed Me? It's valid JSON.

    [
      {
        "FIELD1":"1",
        "FIELD2":"Airmax",
        "FIELD3":"150-08ACW-134 ",
        "FIELD4":"09 Apr 2013",
        "FIELD5":"31 Dec 2030",
        "FIELD6":"24",
        "FIELD7":"23",
        "FIELD8":"28",
        "FIELD9":"29",
        "FIELD10":"29"
      },
      {
        "FIELD1":"2",
        "FIELD2":"Airmax",
        "FIELD3":"270-11AC3-134",
        "FIELD4":"01 Nov 2012",
        "FIELD5":"31 Dec 2030",
        "FIELD6":"23",
        "FIELD7":"21",
        "FIELD8":"27",
        "FIELD9":"28",
        "FIELD10":"28"
      }
    ]

The JSON example tab in the docs just shows the XML version so I can't see what it's supposed to be! I know there needs to be a primary element so my data just might not be right.

Thanks


texts:
How can I get the details of an asset volume in Craft 3, if I only know the handle?

I found the Volumes and the Assets service, but I believe none of them provides a method for that purpose. The only thing I found was this:

Craft::$app->getVolumes()->getVolumeById($id)

But how do I get the id? I do not want to iterate over getAllVolumes()...


texts: Calls to /actions return 400 Bad Request

texts:
I'm trying to use jquery ( and/or VueJS with axios) to delete an asset from a frontend form (user is logged in and they have permissions to delete assets from this volume)

I have an HTML element that contains the fileID of the asset in question:

Delete

I have the following jQuery click action:

$('.deleteAsset').click(function() {
    window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName|e('js') }}";
    window.csrfTokenValue = "{{ craft.app.request.csrfToken|e('js') }}";

    var assetID = $(this).attr("data-fileID");
    var data = {};

    data[csrfTokenName] = csrfTokenValue;
    data['assetId'] = assetID;
    data['dataType'] = 'json';
    data['action'] = '/actions/assets/delete-asset';

    $.post('/', data, function(response, textStatus, jqXHR) {
      console.log('clickResponse', response);
    });
});

However I keep getting the following error in the console when I click the "Delete" button:

POST https://website.com/ 404 (Not Found)

I have tried having the action URL in the $.post() call, but it has the same effect.
Anyone have any suggestions?


texts: How do I get entries of a child category, related to a parent category, defined in a URL segment?

texts:
My entry url structure looks like this:

http://site.com/section/category/subcategory/entry_slug

I'm trying to drill down to specific entries by using the url structure and I'm currently having trouble getting the following to work:

{% set secondSeg = craft.request.getSegment(2) %}
{% set subCategories = craft.categories.group('section').level(2) %}

{% for cat in subCategories.relatedTo(secondSeg).slug(lastSeg) %}
    {{category.title}}
{% endfor %}

Currently nothing is returned. If I remove the .relatedTo(secondSeg) parameter in the cat loop, I'm properly getting all of the entries in child category that match the slug. But, the problem is that there is a possibility of certain entries having the same slug under different child categories. I'm not sure if I'm using the relatedTo parameter properly or not.


texts: How do you handle complex navigation in Craft?

texts:
This seriously can't be this hard. How are you handling complex navigation on your sites? Do you hard-code them? Do you use a dedicated "Menu" Structure Section? I am curious what everyone is doing.

I have a few customers who really need to have control over their menu and its structure, but as I build the templates, I am finding I need complete control over the first level and especially the sub/children of them. I am finding it nearly impossible to come up with a way to be able to loop through children and style them how I need to.

Basically, I am trying to access the Dropdown portion of this menu example and as you can see, I need to be able to add a class and data-toggle to those items.

Link

Link

        Dropdown

Action

Another action

Something else here

Separated link

One more separated link


texts: Are there any tradeoffs if you use the null-coalescing operator in place of first()?

texts:
With the addition of the null-coalescing operator (??) in Twig, it now appears that the following two examples both provide a way to retrieve the first entry and fallback to null if no entry exists:

{# Get the first entry using the `first` method on the ElementCriteriaModel #}
{% set entry = craft.entries.section('news').first() %}

{# Get the first entry by accessing it in the result array directly #}
{% set entry = craft.entries.section('news').limit(1)[0] ?? null %}

It seems, with the addition of eager-loading and the alternative results syntax required for accessing eager-loaded elements in our templates, that the latter option may provide a consistent syntax to use throughout our templates vs. swapping between the former and the latter depending on which type of query you are performing.

Aside from the uglier syntax in the option that uses the null-coalescing operator, are there any other tradeoffs to consider in choosing the first method vs. the null-coalescing method when retrieving a single entry?


texts: Different setPasswordSuccessPath for different user groups

texts: I have a couple different user groups that access the front end of our site and I would like to send them to different paths depending on their user group after setting their password. Is it possible to access a user's group in general config for this purpose?


texts: Algolia indexing disabled items in Craft

texts:
We have Algolia search running on our Craft install through the Search Plus plunin. When I disable an entry I'm finding that it is still searchable through Algolia, which then results in a broken link.

Has anyone else experienced this or do you know of a way to filter out results that are disabled?


texts:
I have tried to follow this guide: https://github.com/pixelandtonic/AppleNews

The API's and keys I provided appear to be valid as I double-checked with my iCloud News Partner account several times.

However when I follow the link inside the plugin (https://news-api.apple.com/sections/2c427e7c-fbc0-31a8-ba00-b563dad6f998) I receive the : {"errors":[{"code":"UNAUTHORIZED"}]} response.

Not sure what it could be. Any advice?


texts:
I get a 404 page when I try to open an Italian page. Homepage www.domain.com/it/ works, but when I proceed to www.domain.com/it/assistenza-e-supporto it gives me a 404.

English version works. Any idea where I should look to fix this?

I've followed the steps as desribed here:
https://craftcms.com/docs/localization-guide

Config looks like this:

return array(
    'cpTrigger' => 'admin',
    'omitScriptNameInUrls' => true,
    'devMode' => true,
    'siteUrl' => array(
        'en_US' => 'http://local.crafttraining.craft.dev/',
        'es' => 'http://local.crafttraining.craft.dev/es/',
        'it' => 'http://local.crafttraining.craft.dev/it/',
    ),
);

Update:
After a day of trying and searching I found out that once I remove the omitScriptNameInUrls from the general.php it works fine, but I would like to have nice url's.

.htaccess looks like this:

<IfModule mod_rewrite.c>
RewriteEngine On

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

What am I doing wrong. Thanks for helping me out with this.