How do I pass data to a component in Laravel Livewire? - laravel-livewire

class Counter extends Component
{
public $counter = 0;
public $name;
public function mount($name)
{
$this->name = $name;
}
public function render()
{
return view('livewire.counter');
}
}
I'm trying to pass the name variable as parameter to the livewire component call like so #livewire('counter', ['name' => $name]) but receiving "Undefined variable $name" error. I have been following the livewire docs too, still same error. what could possibly be wrong? Thank you.

If $name is not defined, then it is not a property available in the blade file where you are including Livewire. Since we don't know anything about your blade file or controllers, I can't give you a direct answer. However, you should check if $name is set anywhere and if so, if it's available in your blade view. This error is not related to Livewire. If you've simply copied the docs without checking the variables, you might as well set it right away:
#livewire('counter', ['name' => 'Gilles'])

Related

Laravel Livewire Life hook livewire, v.2.11 updated/updating

When it try trigger to updated life hook when property is changed/updated not work
example
...
public function updatedName($name){
dd($this->name);
}
and I find this message from livewire doc.
Please note that mutating a property directly inside a Livewire component class doesn't trigger any of the updating/updated hooks.
Please. do someone can explain in detail this message from https://laravel-livewire.com/docs/2.x/lifecycle-hooks meaning and what should be done instead
The warning means that the Lifecycle Hooks are not called when you update a property inside the PHP component class.
An example usage is to catch when a user updates a property via the wire:model attribute.
class HelloWorld extends Component
{
public $foo;
public function updatedFoo($value)
{
//
}
public function mount()
{
$this->foo = "New Value";
// updatedFoo will NOT be called
}
}
<input type="text" wire:model="foo" />
<!-- Entering text into this field will cause the hook to be called -->
try this
public $name;
public function updatedName($value)
{
// if you want get value
dd($value);
// if you want change name to new value
$this->name = $value
}

Issue testing Laravel Controller with Mockery | trying to get property of non-object

I'm very new to testing controllers and I'm running into a problem with a method(). I believe I'm either missing something in my test or my Controller / Repository is designed incorrectly.
The application I'm writing is basically one of those secure "one time" tools. Where you create a note, the system provides you with a URL, once that url is retrieved the note is deleted. I actually have the application written but I am going back to write tests for practice (I know that's backwards).
My Controller:
use OneTimeNote\Repositories\NoteRepositoryInterface as Note;
class NoteController extends \Controller {
protected $note;
public function __construct(Note $note)
{
$this->note = $note;
}
public function getNote($url_id, $key)
{
$note = $this->note->find($url_id, $key);
if (!$note) {
return \Response::json(array('message' => 'Note not found'), 404);
}
$this->note->delete($note->id);
return \Response::json($note);
}
...
I've injected my Note interface in to my controller and all is well.
My Test
use \Mockery as M;
class OneTimeNoteTest extends TestCase {
public function setUp()
{
parent::setUp();
$this->mock = $this->mock('OneTimeNote\Repositories\EloquentNoteRepository');
}
public function mock($class)
{
$mock = M::mock($class);
$this->app->instance($class, $mock);
return $mock;
}
public function testShouldReturnNoteObj()
{
// Should Return Note
$this->mock->shouldReceive('find')->once()->andReturn('test');
$note = $this->call('GET', '/note/1234567890abcdefg/1234567890abcdefg');
$this->assertEquals('test', $note->getContent());
}
}
...
The error I'm getting
1) OneTimeNoteTest::testShouldReturnNoteObj
ErrorException: Trying to get property of non-object
/Users/andrew/laravel/app/OneTimeNote/Controllers/NoteController.php:24
Line 24 is in reference to this line found in my controller:
$this->note->delete($note->id);
Basically my abstracted repository method delete() obviously can't find $note->id because it really doesn't exist in the testing environment. Should I create a Note within the test and try to actually deleting it? Or would that be something that should be a model test? As you can see I need help, thanks!
----- Update -----
I tried to stub the repository to return a Note object as Dave Marshall mentioned in his answer, however I'm now receiving another error.
1) OneTimeNoteTest::testShouldReturnNoteObj
BadMethodCallException: Method Mockery_0_OneTimeNote_Repositories_EloquentNoteRepository::delete() does not exist on this mock object
I do have a delete() method in my repository and I know it's working when I test my route in the browser.
public function delete($id)
{
Note::find($id)->delete();
}
You are stubbing the note repository to return a string, PHP is then trying to retrieve the id attribute of a string, hence the error.
You should stub the repository to return a Note object, something like:
$this->mock->shouldReceive('find')->once()->andReturn(new Note());
Building upon Dave's answer, I was able to figure out what my problem is. I wasn't mocking the delete() method. I didn't understand the need to mock each individual method in my controller that would be called.
I just added this line:
$mock->shouldReceive('delete')->once()->andReturnNull();
Since my delete method is just deleting the note after it is found, I went ahead and mocked it but set it to return null.

Joomla 2.5 Virtuemart hook method in a custom plugin wont fire

I managed to create this simple plugin that I need it to fire a method when ever an item is added to the cart and a method to fire when a checkout has happend. But those methods wont fire in anyway. I also seen another plugin named stockable in virtuemart that uses plgVmOnAddToCart and it fires there correctly. But in my plugins class it wont fire at all.
Here is my code in my plugin, what can I do to make it work? thank you
<?php
defined('_JEXEC') or die( 'Direct Access to ' . basename( __FILE__ ) . ' is not allowed.' ) ;
if (!class_exists('vmCustomPlugin')) require(JPATH_VM_PLUGINS . DS . 'vmcustomplugin.php');
class plgVmAftercheckout extends vmCustomPlugin {
private $stockhandle = 0;
function __construct(& $subject, $config) {
parent::__construct($subject, $config);
$varsToPush = array(
'selectname1'=>array('','char'),'selectname2'=>array('','char'),'selectname3'=>array('','char'),'selectname4'=>array('','char'),
'selectoptions1'=>array('','char'),'selectoptions2'=>array('','char'),'selectoptions3'=>array('','char'),'selectoptions4'=>array('','char')
);
$this->setConfigParameterable('custom_params',$varsToPush);
}
public function plgVmOnAddToCart(&$product){
echo "plgVmOnAddToCart fired";
die();
}
public function plgVmOnUserInvoice(){
echo "plgVmOnUserInvoice fired";
die();
}
}
?>
Ok I found the solution. The problem was the class name. In the joomla 1.5 documentation
http://docs.joomla.org/Creating_a_Plugin_for_Joomla_1.5
it mentions that the class name must follow this rule:
class plg extends JPlugin
But this is not mentiond in any joomla 2.5 documentation, since it is probably considered " an already known rule ".
So my solution was to change the class name from
class plgVmAftercheckout extends vmCustomPlugin {
to
class plgVmCustomAftercheckout extends vmCustomPlugin {
"Custom" because the plugin belongs to a specific group called Custom. So we need to mention the group name in order to make those hook methods observe the events.

Symfony2: global variables in php templating engine

There is a cookbook for adding globals to the twig templating engine, but it doesn't get into doing the same thing for the php engine. How would I do this?
So I might have something like:
# config.yml
someSortOfReferenceToThePHPEngineInstance:
calls:
- [ addGlobals, ["foo", "bar"] ]
- [ addGlobals, ["myService", "#myService"] ]
And then access those like:
// templateName.contentType.php
<?
echo $foo; // echos "bar"
echo $myService->myMethod($foo); // echos the result of modifying "bar" with "myMethod" method of "myService" service
I could not find any documention on this for the PHP engine...
What does work however is:
Config:
//config.yml
parameters:
hello: "YO!"
PHP Template:
// index.html.php
<?php
print $view->container->parameters['hello'];
This does not fit as nicely as the twig convention... Maybe there is better way - I have not debugged any further...
Here are a couple of options:
If you create a base controller that all others inherit from, you can override symfony's render function and add keys to the parameters argument, like:
public function render($view, array $parameters = array(), Response $response = null){
if(!array_key_exists("bar", $parameters){
$parameters["foo"] = $this->get("foo");
}
if(!array_key_exists("bar", $parameters){
$parameters["bar"] = $this->get("bar");
}
return parent::render($view, $parameters, $response);
}
This is the only way I see to modify the "global" variables "globally", though they'll not be available in any views rendered by controllers you don't create (of course, those'll likely be done in Twig anyway and you can use the normal twig means of adding functionality).
The PHP rendering engine has what're called "helpers", which you can access via array keys of $view, like:
$view["foo"]->doSomething();
We created a class for easily making services into helpers:
use Symfony\Component\Templating\Helper\Helper as BaseHelper;
class Helper extends BaseHelper{
protected $name;
public $service;
public function __construct($name, $service){
$this->name = $name;
$this->service = $service;
}
public function __get($name){
if(isset($this->service->$name)){
return $this->service->$name;
}
}
public function __call($name, $arguments){
if(method_exists($this->service, $name)){
return call_user_func_array(array($this->service,$name), $arguments);
}
}
public function getName(){
return $this->name;
}
}
Then in our configuration under the services we'd add:
helper.foo:
class: %helper.class%
arguments:
name: "foo"
helper: "#foo"
tags:
- { name: templating.helper, alias: foo }
This would theoretically be available then to any view files, even those with controllers you don't have control of.
I had a very same problem. For some reason this feature is only available for Twig templating with TwigBundle. Both Twig and PHP templating engines provide possibility to define global variables, but only Twig engine has configuration for that. For me the only real way to achieve that is something you proposed in the question post - to define method calls (and this is the way Twig globals are registered).
Problem is, that with DI extensions you can't access service definition from outside your extension, so you can't add these calls from your DI extension. The way for me was to do that with DI compiler pass.
But I'm also developer of ChillDevViewHelpersBundle and since I was facing this problem in most of my projects I decided to implement it there for common use and you can use 0.1.8 release for this feature.

Codeigniter always load in controller

I`m from Russia, so sorry for bad English.
I want to load template in every page in controller.
For example (library parser in autoload),
class Blog extends CI_Controller {
$header = array(
'header' => 'Welcome to my blog!'
);
$this->parser->parse('header', $header);
function index() {
...
echo "My text";
}
header.php:
<h1>{header}</h1>
<script>
alert("Welcome!");
</script>
But I get an PHP error:
syntax error, unexpected T_VARIABLE, expecting T_FUNCTION in line 6. Line 6:
$header = array(
How can I load header in every page? Thanks.
config.php:
$autoload['libraries'] = array('parser');
controller blog.php:
<?php
class Blog extends Controller {
function __construct()
{
parent::Controller();
$header = array('header' => 'Welcome to my blog!');
$this->parser->parse('header', $header);
}
function index()
{
echo "Мой текст";
}
}
?>
view header.php:
{header}
it works for me..
try calling the array with $this->header
Maybe it's a typing error but in the code from header.php you have typed {header} where I guess it should be {$header}
When loading class properties, like your $header above, php expects the property's visibility to be declared before the variable name. PHP5 has three visibility options: 'public', 'private', or 'protected'. I think this is why you are getting "unexpected T_VARIABLE". The difference between them are described at swik.net as:
To protect from accessibility pollution, PHP v5 introduces 3 prefixes for declaring class methods or variables: public, protected, and private.
Public methods and variables are accessible outside of the class. Protected are only accessible from inside of the class and inherited or parent classes. Private are only accessible from within the class itself.
try this: (I chose 'public' visibility, you can determine which is appropriate for your use)
public $header = array('header'=>'Welcome to my blog");
Next, I think you should call your parser in a constructor, rather than outside of a class method.
function _construct(){
parent::_construct();
$this->parser->parse('header',$this->header);
}
The constructor will be called every time the class is instantiated, loading your parser library method along with it.
Update:
Your comment suggests that the parser isn't working like you expect. I assume you have placed
$this->parser->parse('header,$this->header);
in the constructor function like I suggested. If that isn't working, create a function with the same name as your class and put the parser in there, that function will load every time the class is called, similar to the constructor, but let's see if that does the trick. I suggest taking the parser library out of auto load until you've resolved your problem, just to simplify things.
function blog(){
$this->load->library('parser');
$this->parser->parse('header',$this->header);
}