How to use a custom form view helper in Zend Framework 2? - forms

I wrote a form view helper, that extends the Zend\Form\View\Helper\FormMultiCheckbox and overwrites its renderOptions(...) method:
<?php
namespace MyNamespace\Form\View\Helper;
use Zend\Form\View\Helper\FormMultiCheckbox as ZendFormMultiCheckbox;
class FormMultiCheckbox extends ZendFormMultiCheckbox
{
protected function renderOptions(...)
{
...
$label = $escapeHtmlHelper($label);
$labelOpen = $labelHelper->openTag($labelAttributes);
switch ($labelPosition) {
case self::LABEL_PREPEND:
$template = $labelOpen . $label . $labelClose . '%s';
break;
case self::LABEL_APPEND:
default:
$template = '%s' . $labelOpen . $label . $labelClose;
break;
}
$markup = sprintf($template, $input);
$combinedMarkup[] = $markup;
...
}
}
The next step is to register the new view helper. I'm doing this like here shown:
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
class Module {
...
public function getViewHelperConfig() {
return array(
'invokables' => array(
'FormMultiCheckboxViewHelper' => 'MyNamespace\Form\View\Helper\FormMultiCheckbox',
)
);
}
}
Now my question: How can I make the application use my form view helper instead of Zend\Form\View\Helper\FormMultiCheckbox?

Although Andrews answer works, it's not necessary, just use the default view helper name and map it to your helper class, the application will then use your helper instead
public function getViewHelperConfig() {
return array(
'invokables' => array(
'formmulticheckbox' => 'MyNamespace\Form\View\Helper\FormMultiCheckbox',
),
);
}

here's an example of overriding a view helper:
http://ctrl-f5.net/php/zf2-servicemanager-custom-viewhelpers/
Example:
class Module {
public function onBootstrap(MvcEvent $mvcEvent)
{
$application = $mvcEvent->getApplication();
$serviceManager = $application->getServiceManager();
$viewHelperManager = $serviceManager->get('ViewHelperManager');
$viewHelperManager->setInvokableClass('formmulticheckbox', 'MyNamespace\Form\View\Helper\FormMultiCheckbox');
}
...
}

Related

display the product name in custom tab in admin grid

hello everyone I want to display the product name in a custom tab in admin grid
image is shown below
$fieldset->addField(
'field_name',
'label',
[
'name' => 'field_name',
'label' => __('Productname'),
'title' => __('Product Name'),
'renderer' => 'VendorName\ModuleName\Block\Adminhtml\Extension\Grid\Renderer\Productname',
]
);
Define Render :-
<?php
namespace VendorName\ModuleName\Block\Adminhtml\Extension\Grid\Renderer;
class Produtcname extends \Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer {
public function __construct(
\Magento\Backend\Block\Context $context,
array $data = []) {
parent::__construct($context, $data);
$this->_authorization = $context->getAuthorization();
}
public function render(\Magento\Framework\DataObject $row) {
//write your code
}
}

how to convert the pure soap php to laravel 5

I am new in laravel 5. This code is ok in pure php. But I don't know how to convert this to laravel 5. Can you tell me how to transfer this code to laravel 5.
client.php:
<?php class client {
public function __construct()
{
$params = array('location' => 'http://localhost:8888/csoap/server.php',
'uri' => 'urn://localhost:8888/csoap/server.php');
/* Initialize webservice */
$this->instance = new SoapClient(NULL, $params);
}
public function getString($id)
{
return $this->instance->__soapCall('getOutputString', $id);
}
}
$client = new client();
$id = array('id' => '1');
echo $client->getString($id);
?>
csoap/server.php:
<?php class server {
public function getOutputString($id)
{
$str = 'Youre ID is ' . $id . '.';
return $str;
}
}
$params = array('uri' => 'http://localhost:8888/csoap/server.php');
$server = new SoapServer(NULL, $params);
$server->setClass('server');
$server->handle();
?>
This is how I performed my installation in laravel 5.1
"require": {
"artisaninweb/laravel-soap": "0.2.*"
}
run: composer install or composer update
Add the service in config/app.php.
'providers' => [
...
...
Artisaninweb\SoapWrapper\ServiceProvider',
]
'aliases' => [
...
...
'SoapWrapper' => 'Artisaninweb\SoapWrapper\Facades\SoapWrapper'
]
This is my client soap:
use Artisaninweb\SoapWrapper\Facades\SoapWrapper;
class DataSoap {
public function demo()
{
// Add a new service to the wrapper
SoapWrapper::add(function ($service) {
$service
->name('mydata')
->wsdl('http://localhost:8888/csoap/Server.php')
->trace(true)
});
$data = [
'str' => 'Hello World',
];
// Using the added service
SoapWrapper::service('mydata', function ($service) use ($data) {
var_dump($service->getFunctions());
var_dump($service->call('getString', [$data])->getSringResult);
});
}
}
When I run the this code, I get an error
Class 'Artisaninweb\SoapWrapper\ServiceProvider' not found
You should change:
Artisaninweb\SoapWrapper\ServiceProvider
to:
Artisaninweb\SoapWrapper\ServiceProvider::class
and also:
SoapWrapper' => 'Artisaninweb\SoapWrapper\Facades\SoapWrapper
to:
SoapWrapper' => Artisaninweb\SoapWrapper\Facades\SoapWrapper::class

Silverstripe populate form based on url

I have TeamsPage class and Team class. I am trying to figure out how to pre-populate the form with the data from the database based on the ID that was passed in the URL. Below is the code of my attempt, I tried to pass in the ID via template but that did not work. How else can I accomplish this? I would prefer if there was a way to pass the team as an object that I already have in the edit function so that I don't have to hit the database twice. Is there a way to do this?
TeamsPage:
<?php
class TeamsPage extends Page {
private static $has_many = array (
'Teams' => 'Team',
);
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab('Root.Teams', GridField::create(
'Teams',
'Teams on this page',
$this->Teams(),
GridFieldConfig_RecordEditor::create()
));
return $fields;
}
}
class TeamsPage_Controller extends Page_Controller {
private static $allowed_actions = array (
'show', 'edit', 'EditTeamForm'
);
public function EditTeamForm($teamId){
$fields = new FieldList(
new TextField('TeamName'),
new TextareaField('TeamDescription')
);
$actions = new FieldList(
new FormAction('EditTeam', 'Save Changes')
);
$requiredFields = new RequiredFields(array('TeamName','TeamDescription'));
$form = new Form($this, 'EditTeamForm', $fields, $actions, $requiredFields);
$form->setFormMethod('POST', true);
$data = Session::get("FormData.{$form->getName()}.data");
$team = Team::get()->byID($teamId);
return $data ? $form->loadDataFrom($data) : $form->loadDataFrom($team);
}
public function show(SS_HTTPRequest $request) {
$team = Team::get()->byID($request->param('ID'));
if(!$team) {
return $this->httpError(404,'That team could not be found');
}
return array (
'Team' => $team
);
}
public function edit(SS_HTTPRequest $request){
$team = Team::get()->byID($request->param('ID'));
if(!$team) {
return $this->httpError(404,'That team could not be found');
}
return array (
'Team' => $team
);
}
}
Team:
<?php
class Team extends DataObject {
private static $db = array(
'TeamCaptain' => 'Int',
'TeamName' => 'Varchar',
'TeamDescription' => 'Text'
);
private static $has_one = array (
'Photo' => 'Image',
'TeamsPage' => 'TeamsPage'
);
private static $summary_fields = array (
'GridThumbnail' => '',
'TeamCaptain' => 'Team Captain',
'TeamName' => 'TeamName',
'TeamDescription' => 'Team Description',
);
public function getGridThumbnail() {
if($this->Photo()->exists()) {
return $this->Photo()->SetWidth(100);
}
return '(no image)';
}
public function getCMSFields() {
$fields = FieldList::create(
TextField::create('TeamCaptain'),
TextField::create('TeamName'),
TextareaField::create('TeamDescription'),
$uploader = UploadField::create('Photo')
);
$uploader->setFolderName('teams-photos');
$uploader->getValidator()->setAllowedExtensions(array(
'png','gif','jpeg','jpg'
));
return $fields;
}
public function Link() {
return $this->TeamsPage()->Link('show/'.$this->ID);
}
}
TeamsPage_edit.ss
<% if GetMember() %>
Welcome $getMember.FirstName<br />
$EditTeamForm($ID)
Back to Home
<% else %>
$GoToLogin()
<% end_if %>
It looks to me like you're passing the wrong ID to EditTeamForm from the template. Unless there is a <% with %> statement that I'm not seeing I think you want to call:
$EditTeamForm($Team.ID)
Everything else looks fine to me.

InputFilter "setRequired" not working for html5 multiple

I'm having hard time with a weird behaviour of fileinput.
This is my form:
namespace Frontend\Form;
use NW\Form\Form;
use Zend\InputFilter;
use Zend\Form\Element;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
class EnrollStructure extends Form implements ServiceManagerAwareInterface
{
protected $sm;
public function __construct($name=null) {
parent::__construct("frmEnrollStructure");
$this->setAttribute("action", "/registrazione_struttura/submit")
->setAttribute('method', 'post')
->setAttribute("id", "iscrizione_struttura")
->setAttribute("class", "form fullpage");
$this->addInputFilter();
}
public function init()
{
$structureFs = $this->sm->get('Structure\Form\Fieldsets\Structure');
$structureFs->setUseAsBaseFieldset(true);
$structureFs->remove("id")
->remove("creationTime")
->remove("latLon");
$file = new Element\File("images");
$file->setAttribute('multiple', true);
$this->add($structureFs)->add($file);
$this->add(array(
'name' => 'submit',
'attributes' => array(
'type' => 'submit',
'value' => 'Iscriviti',
'id' => 'sbmtEnrollStructure',
'class' => 'submit_btn'
),
));
$this->setValidationGroup(
array(
'structure' =>
array(
'companyname',
'vatNumber',
'addressStreet',
'addressZip',
'addressCity',
'addressRegion',
'fax',
'publicPhone',
'publicEmail',
'website',
'status',
'ownerNotes',
'category',
'subcategory',
"facilities",
"agreeOnPolicy",
"agreeOnPrivacy",
"subscribeNewsletter",
"contact" => array("name", "surname", "email", "role", "phone"),
),
"images"
));
}
/**
* Set service manager
*
* #param ServiceManager $serviceManager
*/
public function setServiceManager(ServiceManager $serviceManager)
{
$this->sm = $serviceManager;
}
public function addInputFilter()
{
$inputFilter = new InputFilter\InputFilter();
// File Input
$fileInput = new InputFilter\FileInput('images');
$fileInput->setRequired(true);
$fileInput->getValidatorChain()
->attachByName('filesize', array('max' => "2MB"))
->attachByName('filemimetype', array('mimeType' => 'image/png,image/x-png,image/jpg,image/jpeg'))
->attachByName('fileimagesize', array('maxWidth' => 2048, 'maxHeight' => 2048));
$inputFilter->add($fileInput);
$this->setInputFilter($inputFilter);
}
}
Basically, I mainly use a fieldset which contains most of the data I request to the user, plus a File input field.
This is the Fieldset Structure: (most important parts..)
use Zend\Form\Element;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Validator\Identical;
use Zend\Validator\NotEmpty;
use Zend\Validator\Regex;
use Zend\Validator\StringLength;
class Structure extends Fieldset implements InputFilterProviderInterface, ServiceManagerAwareInterface
{
protected $sm;
public function __construct()
{
parent::__construct('structure');
}
public function init()
{
$this->setHydrator(new DoctrineHydrator($this->_entityManager(),'Structure\Entity\Structure'));
$this->setObject($this->sm->getServiceLocator()->get("Structure_Structure"));
$id = new Element\Hidden("id");
$name = new Element\Text("companyname");
$name->setLabel("Ragione Sociale");
...........
}
public function getInputFilterSpecification()
{
return array
(
"id" => array(
"required" => false,
),
"companyname" => array(
"required" => true,
"validators" => array(
array('name' => "NotEmpty", 'options' => array("messages" => array( NotEmpty::IS_EMPTY => "Inserire la ragione sociale")))
),
),
.....
}
}
This is my controller:
public function submitAction()
{
try {
$this->layout("layout/json");
$form = $this->getForm('Frontend\Form\EnrollStructure');
//$form->addInputFilter();
$structure = $this->getServiceLocator()->get("Structure_Structure");
$viewModel = new ViewModel();
$request = $this->getRequest();
if ($request->isPost())
{
$post = array_merge_recursive
(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($post);
if ($form->isValid())
{
$structure = $form->getObject();
$contact = $structure->getContact();
$this->getServiceLocator()->get('Structure_ContactService')->save($contact);
$files = $request->getFiles()->toArray();
if(isset($files['images']))
{
$count = 3;
foreach($files['images'] as $pos => $file)
{
$fpath = $this->getServiceLocator()->get('RdnUpload\Container')->upload($file);
if(!empty($fpath))
{
if(--$count ==0) break;
$asset = $this->getServiceLocator()->get("Application_AssetService")->fromDisk($fpath, $file['name']);
$this->getServiceLocator()->get("Application_AssetService")->save($asset);
$structure->addImage($asset);
}
}
}
$this->getServiceLocator()->get('Structure_StructureService')->save($structure);
$retCode = RetCode::success(array("iscrizione_struttura!" => array("form_submit_successfull")), true);
}
else
{
$messages = $form->getMessages();
if(empty($messages))
$retCode = RetCode::error(array("iscrizione_struttura" => array("need_at_least_one_file" => "missing file")), true);
else
$retCode = RetCode::error(array("iscrizione_struttura" => $messages), true);
}
$viewModel->setVariable("retcode", $retCode);
return $viewModel;
}
} catch(Exception $e)
{
throw $e;
}
}
The strange thing is that if i remove from the field "images" the "multiple" attribute everything works fine, causing the form not to validate and i get this message:
[images] => Array
(
[fileUploadFileErrorFileNotFound] => File was not found
)
While, if i set the attribute multiple, and the user does not upload a file i get no error, but the form gets invalidated (this is the reason for this "bad" code in my controller:)
$messages = $form->getMessages();
if(empty($messages))
$retCode = RetCode::error(array("iscrizione_struttura" => array("need_at_least_one_file" => "missing file")), true);
else
$retCode = RetCode::error(array("iscrizione_struttura" => $messages), true);
I found the problem was caused by the Jquery form plugin, without it it works fine. :( In case somebody needs, I think the correct action code can be found here (I haven't tryied it anyway)
https://github.com/cgmartin/ZF2FileUploadExamples/blob/master/src/ZF2FileUploadExamples/Controller/ProgressExamples.php

Zend skeleton application Class 'Album\Model\AlbumTable' not found

I'm trying to figure out what's wrong with my first tutorial using Zend Skeleton App. I'm using Zend Studio 10 + ZendServer and Zf2.2; managed to get the skeleton app working and now got stuck on a missing class problem (see error below). I have tried various approaches but the result is the same: it's not working. Here are my files, any help would be appreciated.
My error:
Fatal error: Class 'Album\Model\AlbumTable' not found in C:\Program
Files\Zend\Apache2\htdocs\zf2album\module\Album\Module.php on line 55
Album/Module.php
namespace Album;
use Album\Model\Album;
use Album\Model\AlbumTable;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ServiceProviderInterface;
class Module implements ServiceProviderInterface {
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
// if we're in a namespace deeper than one level we need to fix the \ in the path
__NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
// Add this method:
public function getServiceConfig()
{
return array(
'factories' => array(
'Album\Model\AlbumTable' => function($sm) {
$tableGateway = $sm->get('AlbumTableGateway');
$table = new AlbumTable($tableGateway);
return $table;
},
'AlbumTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Album());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
}
the AlbumController.php
namespace Album\Controller;
use Zend\Mvc\Controller\AbstractActionController; use
Zend\View\Model\ViewModel;
class AlbumController extends AbstractActionController { protected
$albumTable;
public function indexAction()
{
return new ViewModel(array(
'albums' => $this->getAlbumTable()->fetchAll(),
));
}
public function addAction()
{
}
public function editAction()
{
}
public function deleteAction()
{
}
public function fooAction()
{
// This shows the :controller and :action parameters in default route
// are working when you browse to /album/album/foo
return array();
}
public function getAlbumTable()
{
if (!$this->albumTable) {
$sm = $this->getServiceLocator();
$this->albumTable = $sm->get('Album\Model\AlbumTable');
}
return $this->albumTable;
} }
AlbumModel.php
namespace Album\Model;
use Zend\Db\TableGateway\TableGateway;
class AlbumTable {
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function fetchAll()
{
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function getAlbum($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
public function saveAlbum(Album $album)
{
$data = array(
'artist' => $album->artist,
'title' => $album->title,
);
$id = (int)$album->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getAlbum($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Form id does not exist');
}
}
}
public function deleteAlbum($id)
{
$this->tableGateway->delete(array('id' => $id));
} }
Assuming this isn't a typo in your question, the filename for the class AlbumTable should be AlbumTable.php, not AlbumModel.php.