checkbox styling and making it checked - javascript

The checkbox retrieved from database is so long that it is going downwards, is there any way to make it as four layers
when clicked on "all fields" checkbox all checkbox must be checked.
How this to be done?
My code :-
protected function getConfigForm()
{
$sql = 'SELECT id_order_state,name FROM '._DB_PREFIX_.'order_state_lang';
$results = Db::getInstance()->ExecuteS($sql);
$values_query = array(array(
'id' => 'AllFields',
'name' => $this->l('All Fields'),
'val' => 'All',
));
foreach ($results as $row) {
$values_query[] = array(
'id' => 'OrderID',
'name' => $this->l($row['name']),
'val' => $row['id_order_state'],
'required' => true,
);
}
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs',
),
'input' => array(
array(
'type' => 'checkbox',
'label' => $this->l('Select Required Status'),
'required' => true,
'values' => array(
'query' => $values_query,
'id' => 'id',
'name' => 'name'
),
),
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
}

Admin forms are rendered using /adminXXX/themes/default/template/helpers/form/form.tpl template file.
In classes /classes/helper/Helper.php there's a method createTemplate():
public function createTemplate($tpl_name)
{
if ($this->override_folder) {
if ($this->context->controller instanceof ModuleAdminController) {
$override_tpl_path = $this->context->controller->getTemplatePath().$this->override_folder.$this->base_folder.$tpl_name;
} elseif ($this->module) {
$override_tpl_path = _PS_MODULE_DIR_.$this->module->name.'/views/templates/admin/_configure/'.$this->override_folder.$this->base_folder.$tpl_name;
} else {
if (file_exists($this->context->smarty->getTemplateDir(1).$this->override_folder.$this->base_folder.$tpl_name)) {
$override_tpl_path = $this->context->smarty->getTemplateDir(1).$this->override_folder.$this->base_folder.$tpl_name;
} elseif (file_exists($this->context->smarty->getTemplateDir(0).'controllers'.DIRECTORY_SEPARATOR.$this->override_folder.$this->base_folder.$tpl_name)) {
$override_tpl_path = $this->context->smarty->getTemplateDir(0).'controllers'.DIRECTORY_SEPARATOR.$this->override_folder.$this->base_folder.$tpl_name;
}
}
} elseif ($this->module) {
$override_tpl_path = _PS_MODULE_DIR_.$this->module->name.'/views/templates/admin/_configure/'.$this->base_folder.$tpl_name;
}
if (isset($override_tpl_path) && file_exists($override_tpl_path)) {
return $this->context->smarty->createTemplate($override_tpl_path, $this->context->smarty);
} else {
return $this->context->smarty->createTemplate($this->base_folder.$tpl_name, $this->context->smarty);
}
}
As you can see in this method, you have the possibility to override a default admin template inside your module by creating this file /modules/my_module/views/templates/admin/_configure/helpers/form/form.tpl:
{extends file="helpers/form/form.tpl"}
{block name="input"}
{if $input.type == 'checkbox'}
{if isset($input.expand)}
<a class="btn btn-default show_checkbox{if strtolower($input.expand.default) == 'hide'} hidden{/if}" href="#">
<i class="icon-{$input.expand.show.icon}"></i>
{$input.expand.show.text}
{if isset($input.expand.print_total) && $input.expand.print_total > 0}
<span class="badge">{$input.expand.print_total}</span>
{/if}
</a>
<a class="btn btn-default hide_checkbox{if strtolower($input.expand.default) == 'show'} hidden{/if}" href="#">
<i class="icon-{$input.expand.hide.icon}"></i>
{$input.expand.hide.text}
{if isset($input.expand.print_total) && $input.expand.print_total > 0}
<span class="badge">{$input.expand.print_total}</span>
{/if}
</a>
{/if}
{* HERE WE DEFINE A CHECKBOX CHECK_ALL *}
<input type="checkbox" id="check_all" name="check_all" data-name="{$input.name}" value="1" />
{foreach $input.values.query as $value}
{assign var=id_checkbox value=$input.name|cat:'_'|cat:$value[$input.values.id]}
{* HERE YOU CAN REARRANGE THE CHECKBOXES AS YOU WANT *}
<div class="checkbox{if isset($input.expand) && strtolower($input.expand.default) == 'show'} hidden{/if}">
{strip}
<label for="{$id_checkbox}">
<input type="checkbox" name="{$id_checkbox}" id="{$id_checkbox}" class="{if isset($input.class)}{$input.class}{/if}"{if isset($value.val)} value="{$value.val|escape:'html':'UTF-8'}"{/if}{if isset($fields_value[$id_checkbox]) && $fields_value[$id_checkbox]} checked="checked"{/if} />
{$value[$input.values.name]}
</label>
{/strip}
</div>
{/foreach}
{else}
{$smarty.block.parent}
{/if}
{/block}
{* HERE WE DEFINE THE JAVASCRIPT THAT WILL ANIMATE THE CHECK ALL CHECKBOX *}
<script type="text/javascript">
$("#check_all").on('change', function() {
$("input[name=" + $(this).data('name') + "]").prop('checked', true);
$(this).prop('checked', false);
});
</script>
This template will be used for every admin controller defined in your module.
I didn't test this code, you'll have to adapt it to your needs but the overall concept is here.

Related

Laravel Eloquent Many to Many Search with Ajax

I had this question last week. I found the solution to add and remove related models. But this time i want to make a search.
Database
drugs table
Schema::create('drugs', function (Blueprint $table) {
$table->BigIncrements('id')->unique();
$table->string('name')->unique();
$table->mediumText('info');
$table->timestamps();
});
interactions table
Schema::create('interactions', function (Blueprint $table) {
$table->BigIncrements('id');
$table->string('name');
$table->string('description');
$table->string('category');
$table->timestamps();
});
drug_interaction table
Schema::create('drug_interaction', function (Blueprint $table) {
$table->integer('interaction_id')->unsigned();
$table->foreign('interaction_id')->references('id')->on('interactions');
$table->integer('drug_id')->unsigned();
$table->foreign('drug_id')->references('id')->on('drugs');
$table->timestamps();
});
Models
Drug
class Drug extends Model
{
//Table Name
protected $table = 'drugs';
//Primary Key
public $primaryKey = 'id';
//Timestamps
public $timestamps = true;
public function interactions()
{
return $this->belongsToMany(Interaction::class);
}
}
Interaction
class Interaction extends Model
{
//Table Name
protected $table = 'interactions';
//Primary Key
public $primaryKey = 'id';
//Timestamps
public $timestamps = true;
//Relationship
public function drugs()
{
return $this->belongsToMany(Drug::class);
}
}
InteractionsController
Since edit/update function works properly and kinda' a part of what i look for, i am only adding the update function of conrtoller.
public function update(Request $request, Interaction $interaction)
{
$interaction->name = $request->name;
$interaction->description = $request->description;
$interaction->category = $request->category;
$interaction->save();
$interaction->drugs()->sync($request->drugs);
return redirect('/interactions')->with('success', 'Interaction Updated');
}
The Form to Add Drugs to Interactions
<div class="container">
<div class="row">
<div class="col-md-12">
{!! Form::open(['url' => 'interactions/' . $interaction->id, 'method' => 'patch']) !!}
<div class="form-group">
{{Form::label('name', 'Etkileşim İsmi')}}
{{Form::text('name', $interaction->name, ['class' => 'form-control', 'placeholder' => 'Etkileşim İsmi'])}}
</div>
<div class="form-group">
{{Form::label('description', 'Etkileşim Açıklaması')}}
{{Form::textarea('description', $interaction->description, ['class' => 'form-control', 'placeholder' => 'Etkileşim Bilgisi'])}}
</div>
<div class="form-group">
{{Form::label('category', 'Kategori')}}
{{Form::text('category', $interaction->category, ['class' => 'form-control', 'placeholder' => 'Etkileşim Kategorisi'])}}
</div>
<div class="form-group">
{!! Form::label('İlaçları Seçin') !!}
{!! Form::select('drugs[]', $drugs, null, ['multiple' => 'multiple', 'class' => 'form-control drugs']) !!}
</div>
{{Form::submit('Güncelle', ['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
</div>
</div>
</div>
select2.js
$(document).ready(function() {
$('.drugs').select2({
minimumResultsForSearch: '25',
minimumInputLength: '3',
placeholder: "Etkileşimi olan 2 İlacı Seçiniz."
});
});
SearchController
class SearchController extends Controller
{
public function index()
{
$drugs = Drug::pluck('name','id');
}
I also have the form i used on interaction/create.blade on search.blade:
<div class="col-md-12">
{!! Form::open(['url' => 'getInteraction', 'method' => 'get']) !!}
<div class="form-group">
{!! Form::label('İlaçları Seçin') !!}
{!! Form::select('drugs[]', $drugs, null, ['multiple' => 'multiple', 'class' => 'form-control drugs', 'type' => 'hidden']) !!}
</div>
{!! Form::submit('Ara', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
I couldn't build a query to search the "related interactions" for each selected "drug" , array those interactions and print them only if an interaction_id exists twice in array.
All help is appreciated. Thanks All !

How to show pagination in Wordpress for categories?

I am displaying my categories on a page. Now, when I have more than x posts, I want to show a pagination to navigate to the next page with the posts.
This is my code:
<?php
$cat_id = get_query_var('cat');
$paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
$args = array(
'cat' => $cat_id,
'posts_per_page' => 5,
'paged' => $paged
);
$query = new WP_Query( $args );
while ( $query->have_posts() ) : $query->the_post();
//Post data
echo get_the_post_thumbnail(get_the_ID());
?>
<li>With some posts</li>
<?php
endwhile;
?>
And then I try to spit out my navigation like this:
<?php
function pagination_nav() {
global $wp_query;
if ( $wp_query->max_num_pages > 1 ) { ?>
<nav class="pagination" role="navigation">
<div class="nav-previous"><?php next_posts_link( '← Older posts' ); ?></div>
<div class="nav-next"><?php previous_posts_link( 'Newer posts →' ); ?></div>
</nav>
<?php }
}
?>
<?php echo pagination_nav();
?>
But whatever I do, I can't return it. How exactly should I do this? $paged should work, right? I have more than 20 posts, but I can't see my navigation/paging button anywhere.
Lastly, I tried the code below, yet this does not go to the second page of my query. The URL says /category/categoryname/page/2, but it just sends me to a blank page...
<div class="pagination">
<?php
echo paginate_links( array(
'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
'total' => $query->max_num_pages,
'current' => max( 1, get_query_var( 'paged' ) ),
'format' => '?paged=%#%',
'show_all' => false,
'type' => 'plain',
'end_size' => 2,
'mid_size' => 1,
'prev_next' => true,
'prev_text' => sprintf( '<i></i> %1$s', __( 'Newer Posts', 'text-domain' ) ),
'next_text' => sprintf( '%1$s <i></i>', __( 'Older Posts', 'text-domain' ) ),
'add_args' => false,
'add_fragment' => '',
) );
?>
</div>
Alright, so let me answer my own question. I solved it by using the same code, but changing the settings (!) in my Wordpress page. When enabling the pagination setting, try to change the default "paginate by 50 posts" to something like "10" or so. That triggers the code to work.

Jetpack Infinite Scroll not working

I have been trying to get infinite scroll to work but can not seem to get it to work.
I have three files the post loop content-post-ft.php, the functions.php and then my front page where the posts are loading frontpage.php
Functions.php
add_theme_support( 'infinite-scroll', array(
'container' => 'main-content',
'type' => 'scroll',
'footer' => 'foot',
'render' => 'infinite_scroll_render'
));
function infinite_scroll_render() {
get_template_part( 'content-post-ft', 'standard' );
}
content-post-ft.php
<div class="hub-cont">
<?php
$thumb_id = get_post_thumbnail_id();
$thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true);
$thumb_url = $thumb_url_array[0];
?>
<div id="newsitem">
<div id="newsimg" style="background-image: url('<?php echo $thumb_url ?>')">
</div>
<div id="newsname"> <?php the_title(); ?> </div>
<div id="newstext"><?php $text = $post->post_content; $trimmed = wp_trim_words( $text, 40, null ); echo $trimmed; ?></div>
<div class="clear"></div>
</div>
<?php
// endwhile;
// endif;
wp_reset_postdata();?>
</div>
Frontpage.php
<div id="main-content">
<?php
$myargs = array (
//'showposts' => 2,
'post_type' => 'post',
'category_name' => 'News'
);
$myquery = new WP_Query($myargs);
if($myquery->have_posts() ) :
while($myquery->have_posts() ) : $myquery->the_post();
get_template_part( 'content-post-ft', get_post_format() );
endwhile;
endif;
?>
</div>
I have tried looking at so many tutorials and other people having similar problems but nothing seems to be working.
The page is showing 10 posts because of the loop but its just adds the 10 and does not "scroll"
Getting this fixed would really help my stress levels!
Solved it. I had to make Jetpack allow the infinite scroll to be used on Custom fields and pages. By default it only works on the original posts page.
Functions file:
function tweakjp_custom_is_support() {
return true;
$supported = current_theme_supports( 'infinite-scroll' ) && ( is_home() || is_archive() || is_front_page() );
return $supported;
}
add_filter( 'infinite_scroll_archive_supported', 'tweakjp_custom_is_support' );
function mm_infinite_scroll_render() {
while ( have_posts() ) : the_post();
get_template_part( 'content' );
endwhile;
}
function mm_infinite_scroll_query_args($args) {
$new_args = array(
'posts_per_page' => $args['posts_per_page'],
'paged' => $args['paged'],
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
);
return $new_args;
}
function mm_infinite_scroll_posts_where($clause) {
return "";
}
add_filter( 'infinite_scroll_posts_where', 'mm_infinite_scroll_posts_where' );
add_filter( 'infinite_scroll_query_args', 'mm_infinite_scroll_query_args', 9999 );
add_theme_support( 'infinite-scroll', array(
'container' => 'main-content',
'render' => 'mm_infinite_scroll_render'
) );
Then the content.php file has the rendering code. Mine looks like this to help those who are unsure.
<div class="news-list">
<ul class="promo-list-items">
<?php
// Fetch all posts relating to a certain tag then display 4 of them
//Get the Thumbnail URL
$src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 720,405 ), false, '' );
?>
<div id="promolink"></div><li class="news-list-item" style="background-image: url(' <?php echo $src[0];?> '); background-repeat: no-repeat; background-size: cover;"> <a class="gdbnewslink" href="<?php echo get_permalink();?>" >
<?php the_title();?>
</a>
<?php wp_reset_postdata(); ?>
</li>
<div class="clear"></div>
</ul>
</div>
Hope this helps someone with the same problem as me.

Different Wordpress menus at different screen sizes

I am trying display different wordpress menus depending on the device/screen width.
<script>
$(function() {
if ($(window).width() > 959) {
<?php wp_nav_menu( array( 'menu' => 'primary', 'container' => '', 'menu_id' => 'menu' ) ); ?>
} else {
<?php wp_nav_menu( array( 'theme_location' => 'mobile' ) ); ?>
}
});
</script>
I've tried using this code, as well as several other variations, but nothing seems to be working. Any ideas?
Thanks in advance
Willem
As far as I know, wp_nav_menu just output the menu html, so on the client side, you would get this:
<script>
$(function() {
if ($(window).width() > 959) {
<div>....menu html....</div>
} else {
<div>....menu html....</div>
}
});
</script>
I think there should be javascript errors there.
Try this:
<div id="menu_a" style="display:none">
<?php wp_nav_menu( array( 'menu' => 'primary', 'container' => '', 'menu_id' => 'menu' ) ); ?>
</div>
<div id="menu_b" style="display:none">
<?php wp_nav_menu( array( 'theme_location' => 'mobile' ) ); ?>
</div>
<script>
$(function() {
if ($(window).width() > 959) {
$("#menu_a").show();
} else {
$("#menu_b").show();
}
});
</script>
Or in response design style, no Javascript involved:
#media all and (max-width: 958px) { #menu_a{display:none};}
#media all and (min-width: 959px) { #menu_b{display:none};}
I ended up using this:
<?php
/* USER-AGENTS
================================================== */
function check_user_agent ( $type = NULL ) {
$user_agent = strtolower ( $_SERVER['HTTP_USER_AGENT'] );
if ( $type == 'bot' ) {
// matches popular bots
if ( preg_match ( "/googlebot|adsbot|yahooseeker|yahoobot|msnbot|watchmouse|pingdom\.com|feedfetcher-google/", $user_agent ) ) {
return true;
// watchmouse|pingdom\.com are "uptime services"
}
} else if ( $type == 'browser' ) {
// matches core browser types
if ( preg_match ( "/mozilla\/|opera\//", $user_agent ) ) {
return true;
}
} else if ( $type == 'mobile' ) {
// matches popular mobile devices that have small screens and/or touch inputs
// mobile devices have regional trends; some of these will have varying popularity in Europe, Asia, and America
// detailed demographics are unknown, and South America, the Pacific Islands, and Africa trends might not be represented, here
if ( preg_match ( "/phone|iphone|itouch|ipod|symbian|android|htc_|htc-|palmos|blackberry|opera mini|iemobile|windows ce|nokia|fennec|hiptop|kindle|mot |mot-|webos\/|samsung|sonyericsson|^sie-|nintendo/", $user_agent ) ) {
// these are the most common
return true;
} else if ( preg_match ( "/mobile|pda;|avantgo|eudoraweb|minimo|netfront|brew|teleca|lg;|lge |wap;| wap /", $user_agent ) ) {
// these are less common, and might not be worth checking
return true;
}
}
return false;
}
?>
and then:
<?php
$ismobile = check_user_agent('mobile');
if($ismobile) {
wp_nav_menu( array( 'theme_location' => 'mobile' ) );
} else {
wp_nav_menu( array( 'menu' => 'primary', 'container' => '', 'menu_id' => 'menu' ) );
}
?>
This doesn't work on the device size but rather whether or not the site is being accessed from a mobile device.
Source: Detect mobile browser
Thanks
Willem

How to display validation messages with javascript alert window?

I use LogOn partial view on Index view and use default LogOnModel of MVC3. But, there is not enough place to display validation messages in view. How can I display validation messages with javascript alert window?
[HttpPost]
public ActionResult LogOn( LogOnModel model, string returnUrl )
{
if ( ModelState.IsValid )
{
if ( ( model.UserName != null ) && ( model.Password != null ) )
{
if ( Membership.ValidateUser( model.UserName, model.Password ) )
{
FormsAuthentication.SetAuthCookie( model.UserName, true );
if ( Url.IsLocalUrl( returnUrl ) && returnUrl.Length > 1 && returnUrl.StartsWith( "/" )
&& !returnUrl.StartsWith( "//" ) && !returnUrl.StartsWith( "/\\" ) )
{
return Redirect( returnUrl );
}
else
{
return RedirectToAction( "Index", "Home", model );
}
}
else
{
return RedirectToAction( "Index", "Home" );
}
}
else return RedirectToAction( "Index", "Home" );
}
return RedirectToAction( "Index", "Home" );
}
In Index view:
#Html.Partial( "LogOn" )
And LogOn view:
#model OnlineMarket.Models.LogOnModel
#using ( Html.BeginForm( "LogOn", "Home", FormMethod.Post ) )
{
#Html.ValidationSummary( true )
#Html.Hidden( "RememberMe", "true" )
<ul class="forms">
<li class="txt">Username</li>
<li class="inputfield">
#Html.TextBoxFor( m => m.UserName, new { #class = "logininputs" } )
</li>
</ul>
<ul class="forms">
<li class="txt" style="width: 26px;">Password</li>
<li class="inputfield">
#Html.TextBoxFor( m => m.Password, new { #class = "logininputs" } )
</li>
</ul>
<ul class="forms">
<li class="txt" style="width: 50px; margin-top: -5px; margin-left: 4px;">
<input type="submit" value="Enter" class="buttonforinput" style="height: 23px;" />
</li>
</ul>
}
For the unobtrusive client validation you could subscribe to the showErrors callback and display the errors the way you want (alert in your case):
(function ($) {
$.validator.setDefaults({
onsubmit: true,
onkeyup: false,
onfocusout: false,
showErrors: function (errorMap, errorList) {
if (errorList.length > 0) {
var errors = errorList.map(function (element) {
return element.message;
}).join('\r\n');
alert(errors);
}
}
});
})(jQuery);
In order to display server side errors with alert on the client you shouldn't be using the #Html.ValidationSummary( true ) helper because this helper outputs the errors directly in the view and you said that you don't have enough place.
So you could emit javascript dynamically when there are errors and display them in an alert:
#if (!ViewData.ModelState.IsValid)
{
<script type="text/javascript">
var errors = #Html.Raw(
Json.Encode(
string.Join(
Environment.NewLine,
ViewData.ModelState
.Where(x => x.Value.Errors.Count > 0)
.SelectMany(x => x.Value.Errors)
.Select(error => error.ErrorMessage))
)
);
alert(errors);
</script>
}

Categories

Resources