checkboxList use arrayHalper and get values yii2 - html

This is my form checkboxList with arrayhalper:
<div class="form-group">
<?= $form->field($model, 'reg_id')->checkboxList(
arrayHelper::Map(Riders::find()->where(['user_id' => Yii::$app->user->identity->id])->all(),'rider_id',
function($model) { return **$model->rider_firstname . " (" . $model->cagoriesCategory->category_name . ")"**; }),
['class' => 'checkbox-inline', 'id' => 'person' ]), ?>
</div>
The label its work correctly, example: Jilly (MasterA). But I want to get value difference with label, example like this Jilly:MasterA. How to give values like this?

You need to change array value syntax. like as,
<div class="form-group">
<?= $form->field($model, 'reg_id')->checkboxList(
arrayHelper::Map(Riders::find()->where(['user_id' => Yii::$app->user->identity->id])->all(), function($model) { return $model->rider_firstname . " : " . $model->cagoriesCategory->category_name; },
function($model) { return $model->rider_firstname . " (" . $model->cagoriesCategory->category_name . ")"; }),
['class' => 'checkbox-inline', 'id' => 'checkbox' ]); ?>
</div>

Its work what i want, thank to #GAMITG
<div class="form-group">
<?= $form->field($model, 'reg_id')->checkboxList(
arrayHelper::Map(Riders::find()->where(['user_id' => Yii::$app->user->identity->id])->all(), function($model) { return $model->rider_firstname . ":" . $model->cagoriesCategory->category_name; },
function($model) { return $model->rider_firstname . " (" . $model->cagoriesCategory->category_name . ")"; }),
['item' => function($index, $label, $name, $checked, $value) {
$return = '<label>';
$return .= '<input type="checkbox" name="' . $name . '" value="' . $value . '" class="checkbox-inline" id="person1">';
$return .= '<span>' . ucwords($label) . '</span>';
$return .= '</label>';
return $return;
} ]); ?>
</div>
then javascript code to cek it:
$('[id="person1"]:checked').each(function() {
var arr = $(this).val();
alert(arr);
});

Related

My custom post type in WordPress is not showing content through short-code

function diwp_services_custom_post_type()
{
$labels = array(
'name' => 'Services',
'singular_name' => 'Service',
'add_new' => 'Add Service',
'add_new_item' => 'Enter Service Details',
'all_items' => 'All Services',
'featured_image' => 'Add Service Image',
'set_featured_image' => 'Set Service Image',
'remove_featured_image' => 'Remove Service Image'
);
// Set Options for this custom post type;
$args = array(
'public' => true,
'label' => 'Services',
'labels' => $labels,
'description' => 'Services is a collection of services and their info',
'menu_icon' => 'dashicons-hammer',
'supports' => array('title', 'editor', 'thumbnail'),
'capability_type' => 'page',
);
register_post_type('services', $args);
}
add_action('init', 'diwp_services_custom_post_type');
// >> Create Shortcode to Display Services Post Types
function diwp_create_shortcode_services_post_type()
{
$args = array(
'post_type' => 'services',
'posts_per_page' => '10',
'publish_status' => 'published',
);
$query = new WP_Query($args);
if ($query->have_posts()) :
while ($query->have_posts()) :
$query->the_post();
$result .= '<div class="card">';
$result .= '<div class="card-block block-1">';
$result .= ' <h3 class="card-title">' . get_the_title() . '</div>';
$result .= ' <p class="card-text">' . get_the_content() . '</div>';
$result .= '</div>';
$result .= '</div>';
endwhile;
wp_reset_postdata();
endif;
return $result;
}
add_shortcode('services-list', 'diwp_create_shortcode_services_post_type');
// shortcode code ends here
I visited below link and implemented same as that but find no results
DIVEIN WP
Here is the screenshot as I am working on localhost
Any help regarding this will be appreciatable.
Thanks
First, you must fetch permalink from Setting >> permalink, and click Save changes
Seconds, Now you must add do_shortcode on the position you need to show all post from custom post type like :
echo do_shortcode('[services-list]');
I test your code in my end and work good https://abukotsh.me/wp/services/test-service/
Scroll down and you see test services

Cannot use modal in panel in yii2

I want to use panel in yii2 project, so I download helpers from kartik-v. In the panel I want to make a button open a popup window or modal, but there is a problem. The modal/popup window working only in the first panel, but when I click button in the second panel, third panel, etc.. nothing happen. What's the problem?
This is the code:
<?php
foreach ($dataProvider->models as $myKandidat)
{
echo '<div class="col-md-4">'
. Html::panel([
'body' => '<div class="panel-body ">'
. '<div class="row">'
. '<div class="col-md-6"><center>'
. Html::img(Yii::getAlias('#web') . '/uploads/' . "{$myKandidat->foto}", ['width' => '129px', 'height' => '150px'])
. '</center></div>'
. '<div class="col-md-6">'
. '<p>' . "{$myKandidat->nama}" . '<b>--' . "{$myKandidat->noInduk}" . '</b><br />From ' . "{$myKandidat->prodi}" .'</p>'
. '<p class="JustifyFull small"><b>Motivation: </b>' . substr("{$myKandidat->motivasi}", 0, 100)
. '... <br />'
. Html::button('Testing', ['value' => Url::to('index.php?r=kandidat/view&id=' . "{$myKandidat->idKandidat}"), 'class' => 'btn btn-success', 'id' => 'modalButton'])
. '</p>'
. '</div>'
. '</div>'
. '</div>',
'footer'=> '<center>Panel Footer</center>',
'footerTitle' => true,
Html::TYPE_DEFAULT,
])
. '</div>';
}
Modal::begin([
'header' => 'Testing',
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
This is the main.js
$(function(){
// Get the click of the button
$('#modalButton').click(function(){
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
});
And this is my controller:
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
Thanks.
You assign an id to a button,
but when you use a loop, your id is repeating
id should be unique or you can use class for showing your modal
<?php
foreach ($dataProvider->models as $myKandidat)
{
echo '<div class="col-md-4">'
. Html::panel([
'body' => '<div class="panel-body ">'
. '<div class="row">'
. '<div class="col-md-6"><center>'
. Html::img(Yii::getAlias('#web') . '/uploads/' . "{$myKandidat->foto}", ['width' => '129px', 'height' => '150px'])
. '</center></div>'
. '<div class="col-md-6">'
. '<p>' . "{$myKandidat->nama}" . '<b>--' . "{$myKandidat->noInduk}" . '</b><br />From ' . "{$myKandidat->prodi}" .'</p>'
. '<p class="JustifyFull small"><b>Motivation: </b>' . substr("{$myKandidat->motivasi}", 0, 100)
. '... <br />'
. Html::button('Testing', ['value' => Url::to('index.php?r=kandidat/view&id=' . "{$myKandidat->idKandidat}"), 'class' => 'btn btn-success modalButton'])
. '</p>'
. '</div>'
. '</div>'
. '</div>',
'footer'=> '<center>Panel Footer</center>',
'footerTitle' => true,
Html::TYPE_DEFAULT,
])
. '</div>';
}
Modal::begin([
'header' => 'Testing',
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
in main.js
$(function(){
// Get the click of the button
$('.modalButton').click(function(){
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
});

dependent dropdown yii2. How to do?

can I create a dependent dropdown in yii2?
I have two tables:
'id','name_country"
'id','name_city','country_id'
and have two methods in my model:
public function getCountryList()
{
$models = NetCountry::find()->asArray()->all();
return ArrayHelper::map($models, 'id', 'country_name');
}
and
public function getCityList($parent_id) {
$models = \common\models\City::find()->where(['parent_id' => $country_id])->asArray()->all();
return ArrayHelper::map($models, 'id', 'name_city','country_id');
}
I have the first field:
<?= $form->field($model, 'country')->dropDownList($model->countryList),['id'=>'parent_id'];
and the second
<?= $form->field($model, 'city')->dropDownList($model->cityList);
I need to 'transmit' parent_id to controller and return city_list by AJAX (with JSON).
How can I do this? I saw an example in Yii1, but what about Yii2?
use the krajee extension for dependent drop down
Details is here Krejee dependent dropdown for yii2
or follow following instructions:
Install the extension via composer:
$ php composer.phar require kartik-v/dependent-dropdown "dev-master"
In your view :
use kartik\widgets\DepDrop;
// Normal parent select
echo $form->field($model, 'cat')->dropDownList($catList, ['id' => 'cat-id']);
// Dependent Dropdown
echo $form->field($model, 'subcat')->widget(DepDrop::classname(), [
'options' => ['id' => 'subcat-id'],
'pluginOptions' => [
'depends' => ['cat-id'],
'placeholder' => 'Select...',
'url' => Url::to(['/site/subcat'])
]
]);
// THE CONTROLLER
public function actionSubcat() {
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$cat_id = $parents[0];
$out = self::getSubCatList($cat_id);
// the getSubCatList function will query the database based on the
// cat_id and return an array like below:
// [
// ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
// ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
// ]
echo Json::encode(['output'=>$out, 'selected'=>'']);
return;
}
}
echo Json::encode(['output'=>'', 'selected'=>'']);
}
creating dependent dropdown in yii2 without using any third party libraries is
quite as simple as yii1. you have to try following code written below as per your requirements.
use gii to create models,views, controller for respective tables.
suppose there r two table like country, city as u written.
then write the following code into views file for one controller(like country):
<?php
use yii\helpers\ArrayHelper;
use yii\widgets\ActiveForm;
?>
<div>
<?php
$dataCountry=ArrayHelper::map(\app\models\Country::find()->
asArray()->all(),'id', 'name');
$form = ActiveForm::begin();
echo $form->field($model, 'id')->dropDownList($dataCountry,
['prompt'=>'-Choose a Name-',
'class'=>'adjust',
'onchange'=>'
$.post("'.Yii::$app->urlManager->createUrl('city/lists?id=').
'"+$(this).val(),function( data )
{
$( "select#city" ).html( data );
});
']);
$dataPost=ArrayHelper::map(\app\models\City::find()->
asArray()->all(), 'id', 'city');
echo $form->field($model, 'id')
->dropDownList(
$dataPost,
['id'=>'city',
'class'=>'adjust'
]
);
ActiveForm::end();
?>
</div>
and after this in another controller for city write following code as:
<?php
namespace app\controllers;
class CityController extends \yii\web\Controller
{
public function actionLists($id)
{
//echo "<pre>";print_r($id);die;
$countPosts = \app\models\City::find()
->where(['country_id' => $id])
->count();
$posts = \app\models\City::find()
->where(['country_id' => $id])
->orderBy('id DESC')
->all();
if($countPosts>0){
foreach($posts as $post){
echo "<option value='".$post->id."'>".$post->city."</option>";
}
}
else{
echo "<option>-</option>";
}
}
}
then run into url it works!
edit: fixed url construction. http requests will now work.
You can do it without any widget manually:
make your activeform as follows:
<?= $form->field($model, 'nameofyourmodel')->dropDownList(
ArrayHelper::map(\app\models\nameofyourmodel::find()->all(), 'id', 'name'),
[
'prompt'=>'smth',
'onchange' => '
$.post(
"' . Url::toRoute('getoperations') . '",
{id: $(this).val()},
function(res){
$("#requester").html(res);
}
);
',
]
); ?>
and here the second form which receives the id from the first model:
<?= $form->field($model,'nameofyourmodel')->dropDownList(
[],
[
'prompt' => 'smth',
'id' => 'requester'
]
); ?>
and the last action is to make a functionality in controller to match 2 ids and send them to your model:
public function actionGetoperations()
{
if ($id = Yii::$app->request->post('id')) {
$operationPosts = \app\models\firstmodel::find()
->where(['id' => $id])
->count();
if ($operationPosts > 0) {
$operations = \app\models\secondmodel::find()
->where(['firstmodelid' => $id])
->all();
foreach ($operations as $operation)
echo "<option value='" . $operation->firstmodelid. "'>" . $operation->name . "</option>";
} else
echo "<option>-</option>";
}
}
The above code is not working properly. There is an error in the line
$.post("'.Yii::$app->urlManager->createUrl('city/lists&id=').'"+$(this).val(),function( data )
console shows the error :
Not Found (#404): Unable to resolve the request: subcategory/lists&id=54
is there any solution for this
my controller looks like below
public function actionLists($id)
{
$posts = SubCategory::find()
->where(['category_id' => $id])
->orderBy('id DESC')
->all();
if($posts){
foreach($posts as $post){
echo "<option value='".$post->id."'>".$post->name."</option>";
}
}
else{
echo "<option>-</option>";
}
}
when i remove the id from the url and hard coded it in to controller it works properly.
I have find a solution for this
please change your view as follows
<?= $form->field($model, 'category_id')->dropDownList($data,['prompt'=>'-Choose a Category-',
'onchange'=>'
$.get( "'.Url::toRoute('product/catlists').'", { id: $(this).val() } )
.done(function( data )
{
$( "select#product-sub_categoryid" ).html( data );
});
']); ?>
and controller like this
public function actionCatlists($id)
{
$mymodel = new Product ();
$size = $mymodel->modelGetCategory ( 'product_sub_category',$id );
if($size){
echo '<option value="">Choose Sub category</option>';
foreach($size as $post){
echo "<option value='".$post['id']."'>".$post['name']."</option>";
}
}
else{
echo '<option value="0">Not Specified</option>';
}
}
don't forget to include this on your view
use yii\helpers\Url;

issue getting the value from database to combobox

This is my controller:
<?PHP
class combobox extends CI_Controller
{
function dynamic_combobox()
{
$this->load->model('combobox_model');
$data['college'] = $this->combobox_model->getcollege();
$this->load->view('header', $data);
$this->load->view('left_menu', $data);
$this->load->view('manage_user', $data);
$this->load->view('footer', $data);
}
}
?>
This is my model:
$this->db->get('colleges');
$data = array();
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){ $data[] = $row; }
}
$query->free_result();
return $data;
This is my view:
<form action="<?php echo site_url(''); ?>" method="post">
College
<select name="id" id="id" style="width: 350px;">
<option class="droplist">Please select colleges</option>
<?
if (count($college)>0)
{
foreach ($college as $row)
{
echo "<option value='". $row['college_id'] . "'>" . $row['college_name'] . "</option>";
}
}
?>
</select>
Courses
<select>
<!--<option>UG</option>
<option>PG</option>-->
</select>
<input class="button" type="button" value="Refresh"/>
</form>
Try if it works or not, Your model:
$rs = $this->db->get('colleges');
$data = array();
if ($query->num_rows() > 0) {
$data = $rs->result_array();
}
$query->free_result();
return $data;
Your View:
if (count($college)>0){
foreach ($college as $row){
echo "<option value='". $row['college_id'] . "'>" . $row['college_name'] . "</option>";
}
}
Edit 1:
$arr[] = array('college_id' => '1', 'college_name' => 'Nadar Saraswathi College of Engineering and Technology', 'status' => '1', 'created_by' => '1', 'modified_by' => '1', 'created_date' => '2012-09-30 22:51:25', 'modified_date' => '2012-09-30 22:50:28' );
print_r($arr);
echo "<select>";
foreach ($arr as $row){
echo "<option value='". $row['college_id'] . "'>" . $row['college_name'] . "</option>";
}
echo "</select>";
i think you missed to add $query in your model
$query=$this->db->get('colleges'); //<---- here notice $query=
$data = array();
if ($query->num_rows() > 0) {
$data=$query->result_array(); //<--no need of using loop as you are already looping it in you view
}
$query->free_result();
return $data;

Wordpress - Display Posts Newer Than 30 Days

I'm going nuts trying to figure out why I'm having such a difficult time getting WordPress to only show posts newer than 30-days and I could really use a second set of eyes. I'm using the following code but nothing is showing up on my site.
<?php
// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
// posts in the last 30 days
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
return $where;
}
add_filter( 'posts_where', 'filter_where' );
$the_query = new WP_Query( $query_string );
remove_filter( 'posts_where', 'filter_where' );
?>
<?php if ($the_query->have_posts()) : ?>
<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
<h2 class="title"><?php the_title(); ?></h2>
<div class="meta">
<span class="date">
<strong><?php the_time('d'); ?></strong>
<strong><?php the_time('M'); ?></strong>
</span>
</div>
<div class="entry">
<?php if ( function_exists( 'get_the_image' ) ) {
get_the_image( array( 'custom_key' => array( 'post_thumbnail' ), 'default_size' => 'full', 'image_class' => 'alignleft', 'width' => '170', 'height' => '155' ) ); }
?>
<?php the_content('Read More'); ?>
</div>
</div>
<?php endwhile; ?>
<div class="navigation">
<?php
include('includes/wp-pagenavi.php');
if(function_exists('wp_pagenavi')) { wp_pagenavi(); }
?>
</div>
<?php else : ?>
<h2 class="center">Not Found</h2>
<p class="center">Sorry, but you are looking for something that isn't here.</p>
<?php get_search_form(); ?>
<?php endif; ?>
<?php
function filter_where($where = '') {
//posts in the last 30 days
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
return $where;
}
add_filter('posts_where', 'filter_where');
query_posts($query_string);
?>
This works
The way you're doing looks fine. Try putting posts_per_page => -1 as the argument.
The following works for me:
function filter_where( $where = '' ) {
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
return $where;
}
add_filter( 'posts_where', 'filter_where' );
$args = array(
'posts_per_page' => -1,
);
$the_query = new WP_Query($args);
remove_filter( 'posts_where', 'filter_where' );
while ($the_query->have_posts()) {
$the_query->the_post();
// do stuff
}
Hope it helps.
I know this is super old but, you can do this with WP_Query now.
$args = array(
'post_type' => 'post', // or whatever post type you want
'posts_per_page' => -1, // get all posts that apply, i.e. no limit
'date_query' => array(
array(
'after' => '-30 days',
'column' => 'post_date',
),
),
);