Yii2 Set selected value to dropdown which depends on another dropdown - yii2

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.

Related

Yii2 dropdown2 selected depending on dropdown1

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.

Wordpress: programmatically create sub menu for frontend

I'd like to write a wordpress-plugin, where you can add a page.
If you submit the page it should also create a submenu under the menu "Teams".
Until now I can create a page through my code, but not the submenu.
I tried different functions I found on google, but nothing will work.
Does anyone know a function or a script that will help?
Yes sure, use the following as a sample to get you going. The clause to check if you are in the right menu may need altering or deleting if you don't have multiple menu objects defined.
menu_item_parent is vital and that is the parent item uid. find that by viewing your front end source code. You should find that each menu item inserted via WP menu creating functions inserts the unique items id.
// add a sub menu dynamically via code!
function aj_add_menu_item( $items, $args ) {
// check we are in the right menu
if( $args -> theme_location =="primary" ) {
$new_links = array();
// Create a nav_menu_item object
$newItem = array(
'title' => "Offers",
'menu_item_parent' => 71,
'ID' => 'loginout',
'db_id' => '12312332', // something random
'url' => "offers",
'classes' => array( 'menu-item' )
);
$items[] = (object) $newItem; // add to end of existing object.
menu_item_parent value will ensure it goes in right place
return $items;
}else{
return $items;
}
}
add_filter( 'wp_nav_menu_objects', 'aj_add_menu_item', 10, 2 );

cmb2 tinymce menu bar not showing

I'm using CMB2 to allow for front end submissions using a custom post type. The code works well but the problem is that it doesn't support menu bar. There's the textarea, submit button and the title but menu bar is not showing. What could be the problem?
Below is my code:
$cmb->add_field( array(
'name' => __( 'New Post Content', 'wds-post-submit' ),
'id' => 'submitted_post_content',
'type' => 'wysiwyg',
'options' => array(
'wpautop' => true, // use wpautop?
'media_buttons' => true, // show insert/upload button(s)
'textarea_name' => $editor_id, // set the textarea name to something different, square brackets [] can be used here
'textarea_rows' => get_option('default_post_edit_rows', 10), // rows="..."
'tabindex' => true,
'editor_css' => '', // intended for extra styles for both visual and HTML editors buttons, needs to include the `<style>` tags, can use "scoped".
'editor_class' => '', // add extra class(es) to the editor textarea
'teeny' => false, // output the minimal editor config used in Press This
'dfw' => false, // replace the default fullscreen with DFW (needs specific css)
'tinymce' => array(
'menubar' => true;
), // load TinyMCE, can be used to pass settings directly to TinyMCE using an array()
'quicktags' => true // load Quicktags, can be used to pass settings directly to Quicktags using an array()
),
) );
A little late, but: change
'menubar' => true;
to
'menubar' => true,

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!

Add button column in Html.Grid

I am very new to MVC. I have an Html.Grid with some column in it.I want to add a new column with its heading as "New Column".This column will have a button for each row.The button should be disabled based on the value of another column.For example,if 'status' column for a row is "complete",then the button should be enabled otherwise it should be disabled. When the button is clicked,"myMethod" in "MyController" will be called.
The existing code in my View looks like this:
Html.Grid(Model.Results)
.RowAttributes(row => new Hash(#class => row.Item.Priority1 ? "redgrid" : row.IsAlternate ? "alternategrid" : "grid"))
.Columns(column =>
{
column.For(c =>
(c.ExistsInPatRec == true) ?
Html.ActionLink(c.CaseNumber.ToString(), "Details", new { id = c.CaseNumber }, new { target = "_blank" })
: Html.Label(c.CaseNumber.ToString())
)
.Named("Case Number").SortColumnName("CaseNumber")
.Encode(false)
;
//I have to add my column here.It will be disabled if "Status"="Incomplete"
column.For(c => c.Status).Named("Status").SortColumnName("Status")
.Attributes(x =>
{
if (x.Item.Status == "Complete")
return new Hash(style => "background-color:#33CC00");
else if (x.Item.Status == "Incomplete")
return new Hash(style => "background-color:orange");
else
return new Hash(style => "");
});
column.For(c => c.SomeId);
I have added this line:
column.For(c => "<button onclick='location.href='www.gmail.com';'>gmail</button>").Named("My New Column").Encode(false);
but it's not working.When I click the button,it doesnt take me to the link.
Can someone help me please?
Did not yet go through your entire code but try this:
Change:
column.For(c => "<button onclick='location.href='www.gmail.com';'>gmail</button>").Named("My New Column").Encode(false);
To:
column.For(c => "<button onclick=\"javascript:window.open('http://gmail.com');\">gmail</button>").Named("My New Column").Encode(false);
This should at least make your links work. Your links were not working since your buttons were not properly formed.
To trigger Controller Actions, you need to use the following type of code.
column.For(c => "<input type=\"button\" value=\"Go Somewhere Else\" onclick=\"location.href='<%: Url.Action(\"myMethod\", \"myController\") %>'\" />").Encode(false);