Yii2 dropdown2 selected depending on dropdown1 - yii2

I have two standard dropdowns:
$form->field($model, 'typ_id')->dropDownList(
\yii\helpers\ArrayHelper::map(app\models\Plra::find()->all(), 'id', 'name'),
);
and
$form->field($model, 'tol_id')->dropDownList(
\yii\helpers\ArrayHelper::map(app\models\Plratol::find()->all(), 'id', 'name')
);
and I would like to make one certain value selected (virtually as a suggestion, as a default) in dropdown tol_id if one certain typ_id value is selected. Basically the two dropdowns are independent. As a workaround to achieve what I want, I can make it work as a dependent dropdown:
$form->field($model, 'typ_id')->dropDownList(
\yii\helpers\ArrayHelper::map(app\models\Plra::find()->all(), 'id', 'name'), [
'onchange' => '$.post("' . \Yii::$app->urlManager->createUrl('plra/listtol?typ_id=') . '"+$(this).val(), function(data) {$("select#tol_id").html(data);});',
]
);
and
$form->field($model, 'tol_id')->dropDownList(
\yii\helpers\ArrayHelper::map(app\models\Plratol::find()->all(), 'id', 'name'), [
'id' => 'tol_id'
]
);
Controller:
public function actionListtol($typ_id) {
if ($typ_id == 2) {
$plratol = Plratol::find()->where(['typ_id' => 2])->one();
echo "<option value='" . $plratol->id . "'>" . $plratol->name . "</option>";
} else {
$plratols = Plratol::find()->where(['typ_id' => NULL])->all();
echo "<option>Select</option>";
foreach ($plratols as $plratol) {
echo "<option value='" . $plratol->id . "'>" . $plratol->name . "</option>";
}
}
}
but I'm wondering is there a more simple way maybe mit js for such a simple dependency/scenario? If yes, can you please provide me sample code 'cause unfortunately js is not something I'm familiar with.
I would like to solve it without Kartik's DepDrop extension.

You can use pure javascript or jquery,
Add an onchange() event on 1st dropdown and using ajax in onchange() function get the required value of 2nd dropdown and set its html.

Although you don't have any code to reference. If I understand correctly, your dependent dropdown won't work onload if you pass it a selected value. You can still get around this with JS.
$( document ).ready( function(){
e = $('#parent'); // replace with your elements name
e.change();
});
The above code will trigger the change event and whatever value you have provided will be used in the dependent dropdown.

Related

How to convert HTML page to PDF in YII framework

this is my output I need to convert my HTML page to PDF format in YII framework.
I have tried HTML2PDF where it gives me this error.
[ERROR] It seems that HTML2PDF dependencies are not installed… you must install them with composer install
Then I have installed composer also. But the error is same.
Suggest me solution of this or give any new idea.
this is my view code..
<tr>
<?php echo "<td>".$record->inv_article."</td>" ?>
<?php echo "<td>".$record->inv_no."</td>" ?>
<?php echo "<td >".$record->inv_weight."</td>" ?>
<?php echo "<td >".$record->inv_amt."</td>" ?>
<?php echo "<td >".$record->inv_freight."</td>" ?>
<?php echo "<td >".$record->inv_bilticharges."</td>" ?>
<?php echo "<td >".$record->inv_bilticharges."</td>" ?>
<?php $i++; ?>
</tr>
Here is my controller in my project
public function actionGeneratePDF($id){
$mpdf1 = Yii::app()->ePdf->mpdf();
$myhtml=$this->renderPartial('lorryprint', array(
'model'=>$model,'invid'=>$id), true);
$mpdf1->WriteHTML($myhtml);
$file_name= $id.'.pdf';
ob_end_clean();
$mpdf1->Output($file_name,EYiiPdf::OUTPUT_TO_DOWNLOAD );
}
CHECK OUT HERE
I have the same problem couple of months ago, I wanted to convert the html page into pdf in Yii Framework. It took me 3 days to find out how to use it properly. So there are two ways to generate PDF from html by using PHP classes below:
HTML2PDF
mPDF
I have used both but I will prefer you to use mPDF. it is much better than HTML2PDF. Here is method on How to use mPDF in Yii Framework.
First of all you need
YiiPDF - Small Yii extension, that wraps a few PHP libraries (mPDF and HTML2PDF so far) to convert HTML to PDF.
mPDF - is a PHP class to generate PDF files from HTML with Unicode/UTF-8 and CJK support.
I have used mPDF Version 5.7 Because you don't need a composer to install it.
So just download Yii PDF and mPDF from above links and extract them and then Rename the folders to yii-pdf and mpdf and place them into your project in protected\extensions.
Then open your protected/config/main.php and add the below code.
'components'=>array(
'ePdf' => array(
'class' => 'ext.yii-pdf.EYiiPdf',
'params' => array(
'mpdf' => array(
'librarySourcePath' => 'application.extensions.mpdf.*',
'constants' => array(
'_MPDF_TEMP_PATH' => Yii::getPathOfAlias('application.runtime'),
),
'class'=>'mpdf', // the literal class filename to be loaded from the vendors folder
/*'defaultParams' => array( // More info: http://mpdf1.com/manual/index.php?tid=184
'mode' => '', // This parameter specifies the mode of the new document.
'format' => 'A4', // format A4, A5, ...
'default_font_size' => 0, // Sets the default document font size in points (pt)
'default_font' => '', // Sets the default font-family for the new document.
'mgl' => 15, // margin_left. Sets the page margins for the new document.
'mgr' => 15, // margin_right
'mgt' => 16, // margin_top
'mgb' => 16, // margin_bottom
'mgh' => 9, // margin_header
'mgf' => 9, // margin_footer
'orientation' => 'P', // landscape or portrait orientation
)*/
)
),
),
Please note: In above code 'class' => 'ext.yii-pdf.EYiiPdf', means that you have a file called EYiiPdf in protected/extensions/yii-pdf/ and similarly that mPDF extension 'librarySourcePath' => 'application.extensions.mpdf.*', exists in protected/extensions/mpdf
Then you can create a function in your controller.
public function actionGeneratePDF($id){
$model = AsfiUsers::model()->findByPk($id);
$mpdf1 = Yii::app()->ePdf->mpdf();
$myhtml=$this->renderPartial('ProfileView', array(
'personal_info'=>$model), true);
$mpdf1->WriteHTML($myhtml);
$file_name= $id.'.pdf';
ob_end_clean();
$mpdf1->Output($file_name,EYiiPdf::OUTPUT_TO_DOWNLOAD );
}
So in my View in ProfileView I have added a button at the top of it.
<?php echo CHtml::link('PDF Version',array('AsfiUser/GeneratePDF','id'=>$this->id), array('class'=>'btn btn-info btn-sm')); ?>
After click on that button, It will download the PDF of that html page. My Profile View has tables too so Thats why I have used mPDF not Html2PDF. In html2pdf, It doesnot give much options to adjust tables margin etc. But in mpdf it is automatically adjust and will be a perfect PDF.
FOR HTML2PDF
In case if you want to use HTML2PDF, all the steps are same. Just download Old version of html2pdf, New version will have problem like dependencies are not installed. Just like you have them now.
All steps are same, just add this into your protected/config/main.php below the mPDF class in yii-pdf component array.
'HTML2PDF' => array(
'librarySourcePath' => 'application.extensions.html2pdf.*',
'classFile' => 'html2pdf.class.php', // For adding to Yii::$classMap
/*'defaultParams' => array( // More info: http://wiki.spipu.net/doku.php?id=html2pdf:en:v4:accueil
'orientation' => 'P', // landscape or portrait orientation
'format' => 'A4', // format A4, A5, ...
'language' => 'en', // language: fr, en, it ...
'unicode' => true, // TRUE means clustering the input text IS unicode (default = true)
'encoding' => 'UTF-8', // charset encoding; Default is UTF-8
'marges' => array(5, 5, 5, 8), // margins by default, in order (left, top, right, bottom)
)*/
)
and then your controller function will be same just replace the name with mPDF.
public function actionGeneratePDF($id){
$model = AsfiUsers::model()->findByPk($id);
$html2pdf= Yii::app()->ePdf->HTML2PDF();
$myhtml=$this->renderPartial('ProfileView', array(
'personal_info'=>$model), true);
$html2pdf->WriteHTML($myhtml);
$file_name= $id.'.pdf';
ob_end_clean();
$html2pdf->Output($file_name,EYiiPdf::OUTPUT_TO_DOWNLOAD );
}
and create the same button in view for it. I hope it will work for you. I have used the same and working perfectly.
UPDATED:
This code works, just try to check you haven't made any mistake and secondly add this below code at the top of your html view file.
<?php
ob_start(); //started buffering
?>
<?php echo CHtml::link('PDF Version',array('AsfiUser/GeneratePDF','id'=>$this->id), array('class'=>'btn btn-info btn-sm')); ?>
It will add the button on the page which u want to make PDF, when u click on the button, it will download the file while it will take few seconds to a minute depending on page size.
Updated 2
add this line to ur controller
$myhtml=preg_replace("/<\\/?a(\\s+.*?>|>)/", "", $myhtml);
So your controller will be like this
public function actionGeneratePDF($id){
$mpdf1 = Yii::app()->ePdf->mpdf();
$myhtml=$this->renderPartial('lorryprint', array(
'model'=>$model,'invid'=>$id), true);
$myhtml=preg_replace("/<\\/?a(\\s+.*?>|>)/", "", $myhtml);
$mpdf1->WriteHTML($myhtml);
$file_name= $id.'.pdf';
ob_end_clean();
$mpdf1->Output($file_name,EYiiPdf::OUTPUT_TO_DOWNLOAD );
}
OR
If the above controller part doesnot work then fix ur code.
Your this line says $model
$myhtml=$this->renderPartial('lorryprint', array(
'model'=>$model,'invid'=>$id), true);
and in ur view you are using $record instead of $model, Have u done it properly in ur loop. Is ur View file showing results or not?
If it is showing properly,then ur view file lorryprint should be like this. add <td> outside the php tag.
<?php
ob_start(); //started buffering
?>
<?php echo CHtml::link('PDF Version',array('AsfiUser/GeneratePDF','id'=>$this->id), array('class'=>'btn btn-info btn-sm')); ?>
//more code here
<td><?php echo $record->inv_article;?></td>
<td><?php echo $record->inv_no;?></td>
<td><?php echo $record->inv_weight;?></td>
<td><?php echo $record->inv_amt;?></td>
<td><?php echo $record->inv_freight;?></td>
<td><?php echo $record->inv_bilticharges;?></td>
<td><?php echo $record->inv_bilticharges;?></td>
<?php $i++; ?>

Yii2 Set selected value to dropdown which depends on another dropdown

I have a form in which there are two selectboxes, The second selectbox depends of the first one.
All form data are saved in session because there is a back button in order user to be able to change things after firs submitting.
So when user click's the back button I am able to assign the session value to the first dropdown but not to the second one which depends from the first one.
if(isset($session['form_1']['state_code']))
{ $state_code = $session['form_1']['form_1'];
$this->registerJs('$("select#state_select").trigger("change");');} else { $state_code = " "; }
echo $form->field($model, 'state_code')->dropDownList($states,
[ 'prompt' => ' Select state...',
'options' => [$state_code => ['Selected'=>'selected']],
'onchange' => '
$.get("'.Yii::$app->urlManager->createUrl('city?id=').
'"+$(this).val(),function( data ) {
$("select#city").html( data );
});'
]);
This code works for the first drop down
And the bellow code you can see the other drop down which does not work:
if(isset($session['form_2']['city_select']))
{ $c_id = $session['form_2']['city_select']; }
else{ $c_id = ''; }
echo $form->field($model, 'city_select')->dropDownList(['0' => 'Please select state..'],
[
'options' => [$c_id => ['Selected'=>'selected']],
]);
Any Idea ?
As an alternative you can use Kartik extension which solve your problem.

Trouble with html form in drupal

This is part of code I have problem with
if(user_is_logged_in())
{
$cover='<form method="post">
<input type="text" name="tekst" /><input type="submit" id="add" value="Dodaj adres okładki" />
</form></td></tr>';
}
else
{
$cover=" ";
}
$description .= '<tr><td width="60px">Title</td><td>'.$this->getTytul().'</td><td rowspan="20" width="150px">'.$cover.'</td></tr>';
and I have to run that query when user click submit button
db_query("INSERT INTO okladki_publikacji(id_publikacji,adres_okladki) VALUES(".$this->getId().",".$value_from_form.")");
but I have no idea how to do it in drupal
What I want is run function with that query on action in form but how? action =add_cover() doesnt work
Drupal has an amazing forms API that can help you doing this kind of stuff in a breeze.
Basically you define a form using this API and then define the function to be invoked once the user submits it and that's it. Here's an example on how to define the form:
function myformname_form($form, &$form_state){
// define the input field
$form['name'] = array(
'#type' => 'textfield',
'#title' => t('Dodaj adres okładki'),
);
// define the submit button
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Apply'),
);
return $form;
}
Then you define the function that will be executed once the form is executed. Function basically has to be named the same + "_submit" - Drupal will do the magic behind the scenes to tie it together.
function myformname_form_submit($form, &$form_state){
// and this will be where you execute the query you wanted.
}
Would recommend installing Devel module so you can inspect the form_state variable - that's where the input field value will be.
Now, you can just render the form on your code below using drupal_get_form like this:
$cover = " ";
if(user_is_logged_in()) {
$form = drupal_get_form('myformname_form');
$cover = render($form);
}
$description .= '<tr><td width="60px">Title</td><td>'.$this->getTytul().'</td><td rowspan="20" width="150px">'.$cover.'</td></tr>';
Hope this helps!

Output post for second wordpress editor

I recently added a new editor to all my pages and posts admin area with the Wordpress 3.3 new feature to do this
add_action( 'edit_page_form', 'my_second_editor' );
function my_second_editor() {
// get and set $content somehow...
wp_editor( $content, 'mysecondeditor' );
}
My question is how do I output what I enter in this second editor on my website/page? Do I need to make a custom loop? The codex is not very helpful unfortunately.
Thanks
You'll need get_post_meta(), use it like:
echo get_post_meta(get_the_id(), 'mysecondeditor');
Read more: http://codex.wordpress.org/Function_Reference/get_post_meta
To save the data entered in your second editor you'll need this code in your functions.php file:
add_action( 'save_post', 'save_post', 10, 2 );
function save_post( $post_id, $post ) {
if ( !current_user_can( 'edit_post', $post_id ) )
return $post_id;
update_post_meta( $post_id, 'mysecondeditor', stripslashes( $_POST['mysecondeditor'] ) );
}
So after that he's the full code for your second editor:
wp_editor( get_post_meta(get_the_id(), 'mysecondeditor', true), 'mysecondeditor' );
The true above makes sure only a single variable is returned and not an array so you can use it right away.
user2019515I's (Apr 18 '13 at 12:06) answer works for me, I can add text and gallery, but when I display that with this code:
<?php echo get_post_meta(get_the_ID(),'mysecondeditor')['0']; ?>
I got gallery code instead of the images, so:
mytext [gallery ids="102,62"]
How could I display the text (mytext) and the images too?

Registering custom WordPress widgets

I have created a custom widget in my themes plugin directory and it seems to be working as expected but when I register a second custom widget the 1st one seems to get overridden and I no longer have access to it. Below is my code for the widgets:
add_action( 'widgets_init', create_function( '', 'register_widget( "staffWidget" );' ) );
class staffWidget extends WP_Widget{
function staffWidget() {
parent::WP_Widget(true, 'Staff');
}
function widget($args, $instance){
echo "test widget";
}
function update($new_instance, $old_instance){
return $new_instance;
}
function form($instance){
$instance = wp_parse_args( (array) $instance, array( 'title' => '' ) );
if($instance['title']){
$title = $instance['title'];
}
else{
$title = "Add title here";
}
?>
<p><label for="<?php echo $this->get_field_id('title'); ?>">Title: <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo attribute_escape($title); ?>" /></label></p>
<?php
}
}
Both widgets have this kind of code structure but with different class names and both widgets have been activated in the plugins section of the WP dashboard. Any help or suggestions would be very much appreciated. Thanks in advance :)
You are calling the class WP_Widget with the wrong parameters.
/**
* PHP5 constructor
*
* #param string $id_base Optional Base ID for the widget, lower case,
* if left empty a portion of the widget's class name will be used. Has to be unique.
* #param string $name Name for the widget displayed on the configuration page.
* #param array $widget_options Optional Passed to wp_register_sidebar_widget()
* - description: shown on the configuration page
* - classname
* #param array $control_options Optional Passed to wp_register_widget_control()
* - width: required if more than 250px
* - height: currently not used but may be needed in the future
*/
function __construct( $id_base = false, $name, $widget_options = array(), $control_options = array() ) {
If you put false (default value) or a string, it'll work. So, supposing we have a widget Staff and another Stuff, this would do:
parent::WP_Widget('staff', 'Staff', array(), array() );
parent::WP_Widget('stuff', 'Stuff', array(), array() );
Your code is using attribute_escape, which is deprecated. If you enable WP_DEBUG, you'll see the warning. Anyway, it's a good practice to develop always with it turned on.
All this indicates that you are using a bad source as example. This one is the article about custom widgets.