Cannot use Carbon_Fields\Container

I install https://carbonfields.net/ in theme
composer require htmlburger/carbon-fields
Add to functions.php next code


use Roots\Sage\Config;
use Roots\Sage\Container;
use Carbon_Fields\Container;
use Carbon_Fields\Field;

and get error
Fatal error: Cannot use Carbon_Fields\Container as Container because the name is already in use

how can I use: use Roots\Sage\Container; and use Carbon_Fields\Container; toogether ?

I replace

// use Carbon_Fields\Container;
// to
use Carbon_Fields\Container as CarbonContainer;

Everything worked, but will not I get problems in the future?

now I change my code to
functions.php

// ...
    require_once $composer;
    // + add next line
     \Carbon_Fields\Carbon_Fields::boot();
}
// ...
// add to end of file
/**
 * Carbon_Fields
 */
require_once get_stylesheet_directory().'/../carbon/theme-options.php';

carbon/theme-options.php

<?php
use Carbon_Fields\Container;
use Carbon_Fields\Field;

add_action( 'carbon_fields_register_fields', 'crb_attach_theme_options' );
function crb_attach_theme_options() {
  
    Container::make( 'theme_options', __( 'Theme Options', 'crb' ) )
    ->add_tab( 'Social', array(
        Field::make( 'complex', 'crb_social_urls', 'Social Links' )
            ->add_fields( array(
                Field::make( 'text', 'label', 'Label' )
                    ->set_width( 50 ) // condense layout so field takes only 50% of the available width
                    ->set_required(),
                Field::make( 'text', 'url', 'URL' )
                    ->set_width( 50 )
                    ->set_required(),
            ) ),
    ) );
}

maybe not the best way, but it all worked

You could add carbon or fields to the array of app files in resources/functions.php, then add the new file to app/. You don’t need to use Roots\Sage\Container so there will be no naming conflict.

Here, for the sake of simplicity, I’ve copied the example code from the Carbon Fields quickstart guide to app/carbon.php:

<?php

namespace App;

use Carbon_Fields\Container;
use Carbon_Fields\Field;

add_action( 'carbon_fields_register_fields', function () {
    Container::make( 'theme_options', __( 'Theme Options', 'crb' ) )
        ->add_fields( array(
            Field::make( 'text', 'crb_text', 'Text Field' ),
        ) );
});

add_action( 'after_setup_theme', function () {
    // Notice I’ve left out require_once( 'vendor/autoload.php' ).
    // Sage has already taken care of this.
    \Carbon_Fields\Carbon_Fields::boot();
});
3 Likes