Drupal with Knockout Javascript - drupal

I'm trying to get Knockout.js to work with Drupal. Seems like the Knockout calls inside a Drupal template file is not reading any of my Knockout calls. Has anyone gotten these two to work together?

You probably forgot all about this but I got it to work by including the js inline in the footer:
$header = array(
'type' => 'file'
);
$footer = array(
'type' => 'file',
'scope' => 'footer'
);
drupal_add_js(drupal_get_path('theme', 'MyTheme'). '/js/knockout.js', $header);
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
drupal_add_js('var ViewModel = function(first, last) {
this.firstName = ko.observable(first);
this.lastName = ko.observable(last);
this.fullName = ko.computed(function() {
// Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
return this.firstName() + " " + this.lastName();
}, this);
};
ko.applyBindings(new ViewModel("Planet", "Earth")); // This makes Knockout get to work
',
array('type' => 'inline', 'scope' => 'footer', 'weight' => 1)
);
If you found a way to do it from a file let me know, this is no good having to do it this way.
Edit: nevermind, it works if you include the file at the footer:
drupal_add_js(drupal_get_path('theme', 'MyTheme'). '/js/MyKnockoutScript.js', $footer);

Related

Zend Framework 3 Form Fieldset

Hy,
I'm really new to Zend-Framework 3 and I'm practicing OOP, I can't find a simple explanation/tutorial on making a Zend Form with a fieldset and legend. Basically I'm trying to create this in HTML:
<form name="my_name">
<fieldset>
<legend>My legend value</legend>
<input type="checkbox" name="name_1" value="value_1">Value 1</input>
<input type="checkbox" name="name_2" value="value_2">Value_2</input>
<input type="checkbox" name="name_3" value="value_3">Value_3</input>
</fieldset>
<input type="button" value="Get values" id="btn"/>
</form>
I checked the official documentation about Zend Forms and Collections and Fieldsets, but it's really confusing me. Any help would be greatly appreciated.
First, I am sorry as it is going to be a bit long one. But this would describe the form in action. So be patient please!
Assuming you are known to ZF3 default Application module. Some folders are created in the Application module for separation of each element. You need to create them as follows.
Let's get started by creating your fieldsets first. Zend\Form\Fieldset component represents a reusable set of elements and is dependent on Zend\From\Form component. This means you need to attach this to Zend\Form\Form.
module/Application/src/Form/Fieldset/YourFieldset.php
<?php
namespace Application\Form\Fieldset;
use Zend\Form\Element;
use Zend\Form\Fieldset;
class YourFieldset extends Fieldset
{
public function __construct($name = null)
{
parent::__construct('your-fieldset');
$this->add([
'name' => 'name_1',
'type' => Element\Checkbox::class,
'options' => [
'label' => 'Value 1',
'use_hidden_element' => true,
'checked_value' => 'yes',
'unchecked_value' => 'no',
],
'attributes' => [
'value' => 'no',
],
]);
// Creates others as your needs
}
}
Now we would create the form using Zend\From\Form attaching the fieldset created from Zend\From\Fieldset.
module/Application/src/Form/YourForm.php
<?php
namespace Application\Form;
use Application\Form\Fieldset\YourFieldset;
use Zend\Form\Form;
class YourForm extends Form
{
public function __construct($name = null)
{
parent::__construct('your-form');
$this->add([
// This name will be used to fetch each checkbox from
// the CheckboxFieldset::class in the view template.
'name' => 'fieldsets',
'type' => YourFieldset::class
]);
$this->add([
'name' => 'submit',
'attributes' => [
'type' => 'submit',
'value' => 'Get Values',
'class' => 'btn btn-primary'
],
]);
}
}
Our from is almost ready. We need to make it serviceable if we want it to be used in any action of a controller. So let's do that.
Update your module config file. If service_manager key does not exist then add the following snippet of code, otherwise, update only factories and aliases key as the following.
Fix namespaces in module config file.
module/Application/config/module.config.php
'service_manager' => [
'factories' => [
// Form service
Form\YourForm::class => Zend\ServiceManager\Factory\InvokableFactory::class,
// Other services
],
'aliases' => [
// Make an alias for the form service
'YourForm' => Form\YourForm::class,
],
],
Now the form is ready to be used. This needs to be injected into our controller. As I am working on Application module, I would inject the form into the IndexController::class's constructor. Then we would be using that form inside IndexController::fieldsetAction() method.
module/Application/src/Controller/IndexController.php
<?php
namespace Application\Controller;
use Zend\Form\FormInterface;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class IndexController extends AbstractActionController
{
protected $YourForm;
public function __construct(FormInterface $YourForm)
{
$this->YourForm = $YourForm;
}
public function fieldsetAction()
{
$request = $this->getRequest();
$viewModel = new ViewModel(['form' => $this->YourForm]);
if (! $request->isPost()) {
return $viewModel;
}
$this->YourForm->setData($request->getPost());
if (! $this->YourForm->isValid()) {
return $viewModel;
}
$data = $this->YourForm->getData()['fieldsets'];
echo '<pre>';
print_r($data);
echo '</pre>';
return $viewModel;
}
}
As this controller is taking argument in its constructor, we need to create a factory for this controller (a factory creates other objects).
module/Application/src/Factory/Controller/IndexControllerFactory.php
<?php
namespace Application\Factory\Controller;
use Application\Controller\IndexController;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
class IndexControllerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
// We get form service via service manager here
// and then inject controller's constructor
$YourForm = $container->get('YourForm');
return new IndexController($YourForm);
}
}
Once again, we need to update the module config file. We would add this time the factory under controllers key as follows
'controllers' => [
'factories' => [
Controller\IndexController::class => Factory\Controller\IndexControllerFactory::class,
],
],
At the end, echo the form in the view template as follows:
module/Application/view/application/index/fieldset.phtml
<h1>Checkbox Form</h1>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url());
// Here is the catch, remember this name from the CheckboxForm::class
$fieldset = $form->get('fieldsets');
$name_1 = $fieldset->get('name_1');
$name_2 = $fieldset->get('name_2');
$name_3 = $fieldset->get('name_3');
$submit = $form->get('submit');
$submit->setAttribute('class', 'btn btn-primary');
$form->prepare();
echo $this->form()->openTag($form);
?>
<fieldset>
<legend>My legend value</legend>
<?= $this->formElement($name_1) ?>
<?= $this->formLabel($name_1) ?>
<?= $this->formElement($name_2) ?>
<?= $this->formLabel($name_2) ?>
<?= $this->formElement($name_3) ?>
<?= $this->formLabel($name_3) ?>
<?= $this->formSubmit($submit) ?>
</fieldset>
<?php
echo $this->form()->closeTag();
Hope this would help you!
Actually the example you are looking for is in "collections" part of zend form. Its not the exact one but kinda like.
Here you are a little example. I ignored namespaces and hope so there's no typo :)
class myFieldset extends Fieldset {
public function init(){
$this
->add([
'name' => 'name_1,
'type' => 'text',
])
->add([
'name' => 'name_2,
'type' => 'text',
])
->add([
'name' => 'name_3,
'type' => 'text',
]);
}
}
class MyForm extends Form {
public function init(){
$this->add([
'type' => myFieldset,
'name' => 'fieldset'
])->add([
'type' => 'button',
'name' => 'action'
]);
}
}
And in view file;
<?=$this-form($form);?>

Symfony2 Collection of Choises

I'm making my first Symfony web app.
Now after creating a couple of forms I found some problem creating a form with a collection of choises.
Creating a collection of TextTypes is very easy and is working in a couple of my forms. Now when I create a collections of ChoiseTypes it does not show anything on the screen. After checking the html code it only show the select statement without any options. Also the prototype contains only the select and not the options.
Where is how I add the collections of choises to the form:
->add('fieldTypes', CollectionType::class, array(
'entry_type' => ChoiceType::class,
'entry_options' => array(
'choices' => $fieldTypes,
'required' => true,
),
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
))
And this is the twig part of the sollution:
<td>
<ul id="typeTable" data-prototype="{{ form_widget(form.fieldTypes.vars.prototype)|e }}">
{% for fieldType in form.fieldTypes %}
<li>
{{ form_widget(fieldType) }}
</li>
{% endfor %}
</ul>
</td>
And the full JS code:
<script type="text/javascript">
// keep track of how many email fields have been rendered
var nameCount = '{{ form.fieldNames|length }}';
var typeCount = '{{ form.fieldTypes|length }}';
var optionCount = '{{ form.fieldOptions|length }}';
jQuery(document).ready(function () {
jQuery('#add-new-field').click(function (e) {
e.preventDefault();
var nameList = jQuery('#nameTable');
var typeList = jQuery('#typeTable');
var optionList = jQuery('#optionTable');
// grab the prototype template
var newNameWidget = nameList.attr('data-prototype');
var newTypeWidget = typeList.attr('data-prototype');
var newOptionWidget = optionList.attr('data-prototype');
//var newTypeWidget = jQuery('#fieldType_prototype');
// replace the "__name__" used in the id and name of the prototype
// with a number that's unique to your emails
// end name attribute looks like name="contact[emails][2]"
newNameWidget = newNameWidget.replace(/__name__/g, nameCount);
newTypeWidget = newTypeWidget.replace(/__name__/g, typeCount);
newOptionWidget = newOptionWidget.replace(/__name__/g, optionCount);
var $options = $("#fieldType_prototype > option").clone();
//$(newTypeWidget).append($options);
$("#form_fieldTypes_" + typeCount).html( $("#fieldType_prototype").html() );
// newTypeWidget.attr("id","form_fieldTypes_" + typeCount);
// newTypeWidget.attr('name', 'form[fieldTypes][' + typeCount + ']');
nameCount++;
typeCount++;
optionCount++;
// create a new list element and add it to the list
var newLi = jQuery('<li></li>').html(newNameWidget);
newLi.appendTo(nameList);
var newLi = jQuery('<li></li>').html(newTypeWidget);
newLi.appendTo(typeList);
var newLi = jQuery('<li></li>').html(newOptionWidget);
newLi.appendTo(optionList);
});
})
</script>
Variable $fieldTypes contains this:
array('Text Field' => TextType::class,
'Text area' => TextareaType::class,
'Email' => EmailType::class,
'Number' => IntegerType::class,
'Url' => UrlType::class,
'Drop down' => ChoiceType::class,
'Date' => DateType::class,
'Checkbox' => CheckboxType::class);
}
Can someone help me with this issue?
It was a bug:
xabbuh:
'I guess you might be affected by a regression that will be fixed by github.com/symfony/symfony/pull/17162. Can you test if the changes from that PR solve your problem?'

page content function for wp_insert_post

I want to add two text fields of username and password in the page content. Basically i am making my plugin. I have made a page which is connected to my plugin. I want to add content in this page by using function.
my page code is:
register_activation_hook( __FILE__, 'my_plugin_install_function');
function my_plugin_install_function() {
$post = array(
'page_template' => '',
'comment_status' => 'closed',
'ping_status' => 'closed' ,
'post_author' => 1,
'post_date' => date('Y-m-d H:i:s'),
'post_name' => 'Checklists',
'post_status' => 'publish' ,
'post_title' => 'Checklists',
'post_type' => 'page',
'post_content' => 'my_function()'
);//insert page and save the id
$newvalue = wp_insert_post( $post, false ); //save the id in the database
update_option( 'hclpage', $newvalue );
}
my_function()
{
// A login form will be here.
}
Is it possible ??? what will be the best way to do it in the plugin file of wordpress ???
To add content I did not use function. But I use php variable.
$form = '<form action="..../wp-content/plugins/wp-link-with-parse/php-sdk/test.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<div id="lower">
<input type="submit" name="login" value="Login">
</form>';
to assign content use:
'post_content'=> $form
i know this post is from 5 years ago, but i'm currently trying to do a wordpress plugin, and i found a solution for adding content to a custom page in wordpress, what i did is to create a .php file with all the content, including php code, and then include that code in my post_type page by creating a variable and adding that file to that variable with file_get_contents, something like this:
enter image description here
hope it can be useful

Form themeing show pictures

I went to this tutorial. I got the example to work. But I don't get it because I can't customize it for my case.
I want to display a picture for each of my facebook friend and pass the adress of the profile picture from facebook to an image tag in front of the checkbox element.
Update
part of my action:
//the array is on part of my update.
$choice_test = array();
$choice_test[] = array('id' => 1, 'username' => 'test');
$choice_test[] = array('id' => 2, 'username' => 'test2');
->add('friend', 'choice', array(
'required' => true,
'expanded' => true,
'choice_list' => $choice_test, //this is my update
'choices' => $fb_friends_form, //$fb_friends_form[1]= 'First Lastane';
'multiple' => true,
'constraints' => array(new CheckChoicesFbFriends(array('fb_friends_form' => $fb_friends_form))),
'mapped' => true
))
return $this->render('FrontendChancesBundle::createrequest.html.php', array(
'form' => $form->createView()));
template:
<?php $view['form']->setTheme($form, array('FrontendDemoBundle:Form')) ;?>
<?php echo $view['form']->widget($form['friend'])?>
in FrontendDemoBundle/Ressources/views/Form/form_widget_pics.html.php:
<input
type="<?php echo isset($type) ? $view->escape($type) : 'checkbox' ?>"
<?php if (!empty($value)): ?>value="<?php echo $view->escape($value) ?>"<?php endif ?>
<?php echo $view['form']->block($form, 'checkbox_widget') ?>
/>
How can I pass even a variable, in my case the username (`$fb_username[0] = 'username' of facebook to from_widget_pics.html.php and how can I display it like this with the form bulider in my aciton:
<img src="www.facebook.com/+FirstLastname>
<input type="checkbox"
id="form_friend_0"
name="form[friend][]"
value="1"/>
<label for="form_friend_0" >First Lastname</label>
<img src="www.facebook.com/+nextfriend>
I had the very same exception message when trying to pass an array or collection of custom selected objects to a form using 'choice_list' option.
I solved it this way (simplified example):
Controller code:
use Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList;
class UsedCarsController extends Controller {
..... action code:
$usedCars = $carRepository->findAllUsed();
$choiceList = new SimpleChoiceList($usedCars);
$form = $this->createForm(new UsedCarsType($choiceList),null, array('label' => 'Used cars form'));
... now render view, etc.
UsedCarsType:
class UsedCarsType extends AbstractType
{
private $choicesList;
public function __construct($choicesList)
{
$this->choicesList = $choicesList;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('usedCars', 'choice',array('label'=>'Used cars',
'required'=>true,
'choice_list' => $this->choicesList,
'empty_value' => '-- used car --'))
;
}
Choice_list option must be an instance of SimpleChoiceList class, not an array.
A bit late but hope this helps.
BTW: I am using Symfony 2.3

Symfony 1.4. How to add attributes of fields to the embedded form?

I embed one form to another. I need to add HTML attributes to the fields embedded form.
Trying to do so:
$this->widgetschema['email'] = new sfWidgetFormInputText(array(), array('class' => 'email'));
but it does not work.
Did you try it this way?
creating a class
class YourForm extends sfForm {
$array= array('array');
$this->setWidgets(array(
'field1' => new sfWidgetFormSelect(array('choices' => $array), array('placeholder' => 'field1', 'required' => 'true', 'data-empty' => 'U did not enter field1!')),
'email_address' => new sfWidgetFormInputText(array('type' => 'email'), array())
));
}
You can even change the type in the first array. Then include your form in the actions by calling it like
$this->form = new YourForm();
Then echo your form in the template:
<?php echo $form; ?>
I hope this helps. I use it like this as well, to add extra attributes to use in javascript.

Resources