Can't retrieve array using carbon_get_theme_option in a nested complex Field (Carbon Fields) - carbon-fields

I am new with Carbon Fields. I am trying to show in frontend social logos (facebook, twitter) using Carbon Fields. It is a complex Field ('team_social') inside another complex Field ('team') that contains the information of workers.
But the function carbon_get_theme_option('team_social') doesn't retrieves the expected array, retrieves null. However, carbon_get_theme_option('team') it works right.
How can I show the logos in each card? What am I doing wrong?
Here is the function to show in the frontend:
function hrd_show_team() {
ob_start(); ?>
<div class="flex flex-col items-center md:flex md:flex-row md:items-stretch md:flex-wrap md:justify-evenly pb-4 px-4 lg:space-x-4">
<?php
$teams = function_exists( 'carbon_get_theme_option' ) ? carbon_get_theme_option( 'team' ) : array();
//echo '<pre>';print_r($teams);echo '<pre/>';die;
if( $teams) {
foreach ( $teams as $team ) { ?>
<!--card--><div class="flex flex-col basis-full sm:basis-2/5 md:basis-[30%] bg-white shadow-card rounded-md mx-4 my-6 h-full">
<div class="rounded-md">
<img class="object-cover h-auto w-full rounded-t-md" src="<?php echo wp_get_attachment_image_src( $team['team_photo'], array(200,200), false )[0]; ?>" alt="<?php echo esc_attr( $team ['team_name'] ); ?>" width="<?php echo esc_attr( $team['team_photo'] )[1]; ?>" height="<?php echo esc_attr( $team['team_photo'] )[2]; ?>">
</div>
<div class="flex flex-col items-center text-center pt-8 pb-3">
<p class="text-lg text-heading font-bold font-montserrat mb-2"><?php echo esc_html( $team['team_name'] ); ?></p>
<p class="text-base text-paragraph font-bold font-montserrat mb-1"><?php echo esc_html( $team['team_role'] ); ?></p>
</div>
<div class="flex flex-row items-center justify-center mb-4">
<?php
//Social icons
$social_links = carbon_get_theme_option( 'team_social' );
if( $social_links) {
foreach ( $social_links as $social ) {
$social_logo = wp_get_attachment_image_src( $social['team_social_logo'], array(20,20), false );
echo '' . '<img src=" ' . $social_logo[0]. ' " width="30" height="30" class="mr-2 rounded-full">';
}
}
?>
</div><!--social icons-->
</div><!--card-->
<?php } //end foreach
} //end if
?>
</div>
<?php return ob_get_clean();
}```
And here is the function in the backend with the Carbon Fields methods:
```//Web settings in admin
add_action( 'carbon_fields_register_fields', 'hrd_attach_theme_options' );
function hrd_attach_theme_options() {
// Default options page
Container::make( 'theme_options', __( 'Web Settings', 'hrd' ) )
->add_tab( __('Banner Slider', 'hrd' ), array(
Field::make( 'complex', 'banner_slider', 'Slider' )
->add_fields( array(
Field::make( 'text', 'banner_title', 'Title' ),
Field::make( 'textarea', 'banner_desc', 'Description' ),
Field::make( 'image', 'banner_photo', 'Photo' ),
) )
->set_collapsed( true )
) )
->add_tab( __('Team', 'hrd') , array(
Field::make( 'complex', 'team', 'Team' )
->add_fields( array(
Field::make( 'image', 'team_photo', __( 'Photo', 'hrd') ),
Field::make( 'text', 'team_name', __( 'Name', 'hrd' ) ),
Field::make( 'text', 'team_role', __( 'Role', 'hrd' ) ),
Field::make( 'textarea', 'team_content', __( 'Description', 'hrd' ) )
-> set_rows( 5 ),
Field::make( 'complex', 'team_social', __( 'Social Links', 'hrd' ) )
->add_fields( array(
Field::make( 'image', 'team_social_logo', __( 'Social Logo', 'hrd' ) )// We're only changing the label field to an image one
->set_width( 50 )
->set_required(),
Field::make( 'text', 'team_url', __('URL', 'hrd' ) )
->set_width( 50 )
->set_required(),
) )
) )
->set_collapsed( true ),
) );
}```

Related

How to sort the columns of my query in WordPress

hello thanks to the query here below I manage to display various information from my wordpress database it works very well
But now I would like each column to be able to be sorted ascending and descending when the user clicks on the column title, is this possible?
<?php
// Example for adding WP PageNavi to a new WP_Query call
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
// les 5 dernieres journees de peche
// 1. On définit les arguments pour définir ce que l'on souhaite récupérer
$args = array(
'post_type' => 'post',
'posts_per_page' => '10',
'category_name' => 'nouveautes',
'paged' => $paged
);
?>
<div >
<div >Detail</div>
<div >Date</div>
<div >Nbre de prise</div>
<div >Membre</div>
</div>
<?php
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$total_des_prises = get_post_meta( get_the_ID(), 'total_des_prises', true );?>
<?php $variable=get_the_title();?>
<?php //echo get_the_author_meta ; ?>
<div style=' display: flex;border:3px solid #8ebf42;'>
<div ><?php echo '' . 'Détail' . '';?></div>
<div ><?php echo get_the_date() ; ?></div>
<div ><?php echo $total_des_prises ;?></div>
<div ><?php echo get_the_author() ;?></div>
</div>
<?php
}
wp_pagenavi( array( 'query' => $the_query ) );
}
wp_reset_postdata();
?>

Add field in product Prestashop 1.7

Why is prestashop don't save my modification into database?
Using prestashop 1.7
/override/classes/Product.php
class Product extends ProductCore {
public $por_gan; public function __construct ($idProduct = null, $idLang = null, $idShop = null) {
$definition = self::$definition;
$definition['fields']['por_gan'] = array('type' => self::TYPE_INT, 'required' => false);
parent::__construct($idProduct, $idLang, $idShop); } }
In ProductInformation.php
->add('por_gan', 'Symfony\Component\Form\Extension\Core\Type\NumberType', array(
'required' => false,
'label' => $this->translator->trans('Beneficio', [], 'Admin.Catalog.Feature'),
'constraints' => array(
new Assert\NotBlank(),
new Assert\Type(array('type' => 'numeric'))
),
))
In form.html.twing
<div class="col-md-6">
<label class="form-control-label">% de beneficio</label
{{ form_widget(form.step1.por_gan) }}
</div>
Thanks
I’ve successfully added an extra tab in admin product page.
It's working fine. I think a better approach would be to create a module in order to make that modification easier to maintain.
Or you can use displayAdminProductsExtra hook, actionProductUpdate hook and actionProductAdd
The extra field is : frais_a_prevoir
I show all the files to modify but you have to check where the modification should be done inside the file (make a search and you will find)
Override /classes/Product.php
In class /classes/Product.php, there are 3 modifications to do :
1)
/** #var string Frais à prévoir */
public $frais_a_prevoir;
2)
'frais_a_prevoir' => array('type' => self::TYPE_HTML, 'lang' => true, 'validate' => 'isCleanHtml'),
3)
$sql->select(
'p.*, product_shop.*, stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity, pl.`description`, pl.`description_short`, pl.`frais_a_prevoir`, pl.`link_rewrite`, pl.`meta_description`,
pl.`meta_keywords`, pl.`meta_title`, pl.`name`, pl.`available_now`, pl.`available_later`, image_shop.`id_image` id_image, il.`legend`, m.`name` AS manufacturer_name,
(DATEDIFF(product_shop.`date_add`,
DATE_SUB(
"'.$now.'",
INTERVAL '.$nb_days_new_product.' DAY
)
) > 0) as new'
);
In /src/PrestaShopBundle/Resources/views/Admin/Product/form.html.twig
<ul class="nav nav-tabs bordered">
<li id="tab_description_short" class="nav-item">{{ 'Summary'|trans({}, 'Admin.Catalog.Feature') }}</li>
<li id="tab_description" class="nav-item">{{ 'Description'|trans({}, 'Admin.Global') }}</li>
<li id="tab_frais_a_prevoir" class="nav-item">{{ 'frais_a_prevoir'|trans({}, 'Admin.Global') }}</li>
</ul>
<div class="tab-content bordered">
<div class="tab-pane panel panel-default active" id="description_short">
{{ form_widget(form.step1.description_short) }}
</div>
<div class="tab-pane panel panel-default " id="description">
{{ form_widget(form.step1.description) }}
</div>
<div class="tab-pane panel panel-default " id="frais_a_prevoir">
{{ form_widget(form.step1.frais_a_prevoir) }}
</div>
</div>
In /src/PrestaShopBundle/Form/Admin/Product/productInformation.php
->add('frais_a_prevoir', 'PrestaShopBundle\Form\Admin\Type\TranslateType', array(
'type' => 'Symfony\Component\Form\Extension\Core\Type\TextareaType',
'options' => [
'attr' => array('class' => 'autoload_rte'),
'required' => false
],
'locales' => $this->locales,
'hideTabs' => true,
'label' => $this->translator->trans('frais_a_prevoir', [], 'Admin.Global'),
'required' => false
))
in src/PrestaShopBundle/Model/Product/AdminModelAdapter.php:
$this->translatableKeys = array(
'name',
'description',
'description_short',
'frais_a_prevoir',
'link_rewrite',
'meta_title',
'meta_description',
'available_now',
'available_later',
'tags',
);
//define unused key for manual binding
$this->unmapKeys = array('name',
'description',
'description_short',
'frais_a_prevoir',
'images',
'related_products',
'categories',
'suppliers',
'display_options',
'features',
'specific_price',
'virtual_product',
'attachment_product',
);
2)
'frais_a_prevoir' => $this->product->frais_a_prevoir,
In database, add a column frais_a_prevoir in table product_lang
Here is an option to do this using module and does not change core files
in your MyModule.php
use PrestaShopBundle\Form\Admin\Type\TranslateType;
use PrestaShopBundle\Form\Admin\Type\FormattedTextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
public function hookDisplayAdminProductsExtra($params)
{
$productAdapter = $this->get('prestashop.adapter.data_provider.product');
$product = $productAdapter->getProduct($params['id_product']);
$formData = [
'ebay_reference' => $product->ebay_reference,
];
$formFactory = $this->get('form.factory');
$form = $formFactory->createBuilder(FormType::class, $formData)
->add('ebay_reference', TranslateType::class, array(
'required' => false,
'label' => 'Ebay reference',
'locales' => Language::getLanguages(),
'hideTabs' => true,
'required' => false
))
->getForm()
;
return $this->get('twig')->render(_PS_MODULE_DIR_.'MyModule/views/display-admin-products-extra.html.twig', [
'form' => $form->createView()
]) ;
}
public function hookActionAdminProductsControllerSaveBefore($params)
{
$productAdapter = $this->get('prestashop.adapter.data_provider.product');
$product = $productAdapter->getProduct($_REQUEST['form']['id_product']);
foreach(Language::getLanguages() as $language){
$product->ebay_reference[ $language['id_lang'] ] =
$_REQUEST['form']['ebay_reference'][$language['id_lang']];
}
$product->save();
}
in your display-admin-products-extra.html.twig
<div class="row" >
<div class="col-md-12">
<div class="form-group">
<h3>Ebay reference</h3>
{{ form_errors(form.ebay_reference) }}
{{ form_widget(form.ebay_reference) }}
</div>
</div>
</div>

Yii2 Dynamic Form

I'm using wbraganca's dynamicform samples codes for mine own project. My code with its corresponding errors are as follows.
Under the view folder
_form.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use frontend\models\Items;
use frontend\models\Employees;
use frontend\models\Departments;
use dosamigos\datepicker\DatePicker;
use wbraganca\dynamicform\DynamicFormWidget;
/* #var $this yii\web\View */
/* #var $model backend\models\Borrow */
/* #var $form yii\widgets\ActiveForm */
$js = '
jQuery(".dynamicform_wrapper").on("afterInsert", function(e, item) {
jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
jQuery(this).html("Items: " + (index + 1))
});
});
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
jQuery(this).html("Items: " + (index + 1))
});
});
';
$this->registerJs($js);?>
<div class="borrow-form">
<?php $form = ActiveForm::begin(['id'=>'dynamic-form']); ?>
<div class="row">
<div class="col-xs-4">
<?= $form->field($model,'dept_id')->dropDownList(
ArrayHelper::map(Departments::find()->all(),'id','dept_name'),
['prompt'=>'select departments'])
?>
</div>
<div class="col-xs-4">
<?=$form->field($model, 'return_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
</div>
<div class="padding-v-md">
<div class="line line-dashed"></div>
</div>
<!-- beginning of dynamic form -->
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 10, // the maximum times, an element can be added (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsAddress[0],
'formId' => 'dynamic-form',
'formFields' => [
'items_id',
'unit',
'request',
'allowed',
],
]); ?>
<div class="panel panel-default">
<div class="panel-heading">
<h4><i class="glyphicon glyphicon-envelope"></i> Items
</h4>
</div>
<div class="panel-body">
<div class="container-items"><!-- widgetBody -->
<?php foreach ($modelsAddress as $i => $modelAddress): ?>
<div class="item panel panel-default"><!-- widgetItem -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Items</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelAddress->isNewRecord) {
echo Html::activeHiddenInput($modelAddress, "[{$i}]id");
}
?>
<div class="row">
<div class="col-xs-4">
<?= $form->field($modelAddress, "[{$i}]items_id")->dropDownList(
ArrayHelper::map(Items::find()->all(),'id','item_name'),
['prompt'=>'select items']) ?>
</div>
<div class="col-xs-2">
<?= $form->field($modelAddress, "[{$i}]unit")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-xs-2">
<?= $form->field($modelAddress, "[{$i}]request")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-xs-2">
<?= $form->field($modelAddress, "[{$i}]allowed")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-xs-2">
<?= $form->field($modelAddress, "[{$i}]unit_price")->textInput(['maxlength' => true]) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</div><!-- .panel -->
<?php DynamicFormWidget::end(); ?>
<!-- end dynamic form-->
<div class="row">
<div class="col-xs-5">
<?= $form->field($model,'emp_id')->dropDownList(
ArrayHelper::map(Employees::find()->all(),'id','emp_name'),
['prompt'=>'select employees'])
?>
<?= $form->field($model,'head_id')->dropDownList(
ArrayHelper::map(Employees::find()->all(),'id','emp_name'),
['prompt'=>'select dept heads'])
?>
<?= $form->field($model,'man_id')->dropDownList(
ArrayHelper::map(Employees::find()->all(),'id','emp_name'),
['prompt'=>'select stoke managers'])
?>
<?= $form->field($model,'keeper_id')->dropDownList(
ArrayHelper::map(Employees::find()->all(),'id','emp_name'),
['prompt'=>'select stoke keepers'])
?>
</div>
<div class="col-xs-5">
<?=$form->field($model, 'emp_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<?=$form->field($model, 'head_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<?=$form->field($model, 'man_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<?=$form->field($model, 'keeper_date')->widget(
DatePicker::className(), [
'inline' => false,
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
The create action under the controller
public function actionCreate()
{
$model = new Borrow();
$modelsAddress = [new Borrow];
if ($model->load(Yii::$app->request->post())) {
$modelsAddress = Model::createMultiple(Borrow::classname());
Model::loadMultiple($modelsAddress, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsAddress) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsAddress as $modelAddress) {
$modelAddress->id = $model->id;
if (! ($flag = $modelAddress->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
return $this->render('create', [
'model' => $model,
'modelsAddress' => (empty($modelsAddress)) ? [new Address] : $modelsAddress
]);
}
The Model Class under the Model Folder
<?php
namespace frontend\models;
use Yii;
use yii\helpers\ArrayHelper;
class Model extends \yii\base\Model
{
/**
* Creates and populates a set of models.
*
* #param string $modelClass
* #param array $multipleModels
* #return array
*/
public static function createMultiple($modelClass, $multipleModels = [])
{
$model = new $modelClass;
$formName = $model->formName();
$post = Yii::$app->request->post($formName);
$models = [];
if (! empty($multipleModels)) {
$keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
$multipleModels = array_combine($keys, $multipleModels);
}
if ($post && is_array($post)) {
foreach ($post as $i => $borrow) {
if (isset($borrow['id']) && !empty($borrow['id']) && isset($multipleModels[$borrow['id']])) {
$models[] = $multipleModels[$borrow['id']];
} else {
$models[] = new $modelClass;
}
}
}
unset($model, $formName, $post);
return $models;
}
}
It gives the following error when I run my code:
PHP Fatal Error – yii\base\ErrorException Class 'frontend\controllers\Model' not found as shown below.
It looks like you have not namespaced frontend\models\Model in the controller.
Add there at the beginning:
use frontend\models\Model;

Bootstrap3 Modal not working with GridView's pjax

I have a following GridView, but unfortunately Bootstrap modal isn't working properly if I have used Pjax pagination or search. Well, the modal does show up, but it won't submit the form. And when I leave the modal out of Pjax(), then it isn't loaded at all.
Pjax::begin(['id' => 'pjax_id', 'timeout' => false, 'enablePushState' => false]);
echo GridView::widget([
'dataProvider' => $details,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['format' => 'raw',
'label' => 'Category',
'value' => function ($data) {
$string = '';
foreach ($data['Category'] as $category) {
$string .= $category->category_name . '<br/>';
}
return $string;
}],
'book_name',
['format' => 'raw',
'contentOptions' => ['class' => 'form-cell'],
'label' => '',
'value' => function ($data) {
$buttons = Html::button('Edit', ['class' => 'btn btn-default mleft modallink', 'data-toggle' => 'modal', 'data-target' => '#'.$data->cat_id]);
return $buttons;
}
],
[
'format' => 'raw',
'label' => '',
'value' => function ($data) {
if (Yii::$app->user->identity->user_type == 'admin') {
$string = '</span>';
$string .= '<a class=\'mleft\' href=\''.Url::to(['category/update', 'id' => $data->cat_id]).'\'><span class="glyphicon glyphicon-pencil"></span></a>';
return $string;
}
}
],
],
]);
$details = $details->getModels();
foreach ($details as $detail) {
?>
<div class="modal fade" id="<?= $detail->cat_id ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel"><?= $detail->category_name ?></h4>
</div>
<div class="modal-body">
<?php
echo Html::beginForm(Url::to(['category/details', 'id' => $detail->cat_id]), 'post', ['id' => 'popup']);
echo Html::beginTag('div', ['class' => 'form-group']);
echo Html::activeLabel($detail, 'cat_description');
echo Html::activeTextarea($detail, 'cat_description', ['class' => 'form-control']);
echo Html::endTag('div');
echo Html::beginTag('div', ['class' => 'form-group']);
echo Html::activeLabel($detail, 'link');
echo Html::activeInput('text', $detail, 'link', ['class' => 'form-control']);
echo Html::endTag('div');
echo Html::beginTag('div', ['class' => 'form-group']);
echo Html::activeLabel($detail, 'resource');
echo Html::activeInput('text', $detail, 'resource', ['class' => 'form-control']);
echo Html::endTag('div');
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<?= Html::submitButton('Submit', ['class' => 'btn btn-success']) ?>
<?= Html::endForm(); ?>
</div>
</div>
</div>
</div>
<?php
}
Pjax::end();
So how do I keep GridView's Pjax functionality so that the modal still works?
Pjax widget has a formSelector attribute that, by default, will find all forms with data-pjax attribute set to something not falsy.
The easiest way to fix your form is to add that attribute to your form definition:
echo Html::beginForm(
Url::to(['category/details', 'id' => $detail->cat_id]),
'post',
[
'id' => 'popup',
'data-pjax' => 1,
]
);

How to show timepicker based jqrelcopy yii?

How to show timepicker based yiibooster, with Jqrelcopy.
I've code like this :
<div class="control-group "><label class="control-label required">Jam Kerja</label>
<div class="controls">
<a id="copylink" href="#" rel=".copy">Tambah Jam Kerja / Shift</a>
<div class="row copy">
<?php echo CHtml::label('',''); ?>
<?php $this->widget('bootstrap.widgets.TbTimePicker',
array(
'name' => 'some_time',
'value' => '00:00',
'htmlOptions'=>array('width'=>'50px'),
'noAppend' => true, // mandatory
'options' => array(
'disableFocus' => true, // mandatory
'showMeridian' => false // irrelevant
),
)
);
?>
<?php
$this->widget('bootstrap.widgets.TbTimePicker',
array(
'name' => 'some_time',
'value' => '00:00',
'noAppend' => true, // mandatory
'options' => array(
'disableFocus' => true, // mandatory
'showMeridian' => false // irrelevant
)
)
);
?>
</div>
</div>
</div>
When I add new, Timepicker always on field 1. Can't on field changed.